Most Recent Token Usage

An easy SQL interview practice problem on DataDriven. Write the query and run it against a real database, with instant feedback.

Domain
SQL
Difficulty
easy
Seniority
L4
Asked in
OpenDoor

Problem

The security team is auditing API token activity. For each token owner, pull only the single most recently used record, working through owners from the lowest owner ID up to the highest. Include all token fields (ID, owner, scope, status, issued date, expiration, last used date, request count) and a row indicator.

Each user's latest token activity.

Tables

api_tokens

Columns: token_id INTEGER, owner_id INTEGER, scope TEXT, status TEXT, issued TEXT, expires TEXT, last_used TEXT, requests INTEGER

api_tokens: 10 of 200 rows
token_idowner_idscopestatusissuedexpireslast_usedrequests
1043197writerevoked2025-02-022027-02-022026-02-0247
1086294adminexpired2025-03-032027-03-032026-03-0394
1129391read:usersActive2025-04-042027-04-042026-04-04141
1172488write:ordersREVOKED2025-05-052027-05-052026-05-05188
1215585read:analyticsactive2025-06-062027-06-062026-06-06235
1258682full_accessrevoked2025-07-07NULL2026-07-07282
1301779readexpired2025-08-082027-08-082026-08-08329
1344876writeActive2025-09-092027-09-09NULL0
1387973adminREVOKED2025-10-102027-10-102026-01-10423
14301070read:usersactive2025-11-112027-11-112026-02-11470

Expected output

First 5 of 50 rows
token_idowner_idscopestatusissuedexpireslast_usedrequestsrn
3150100writeactive2025-03-232027-03-232026-06-2323501
3193197adminrevoked2025-04-242027-04-242026-07-2423971
3236294read:usersexpired2025-05-252027-05-252026-08-2524441
3279391write:ordersActive2025-06-262027-06-262026-09-0224911
1172488write:ordersREVOKED2025-05-052027-05-052026-05-051881

Worked solution and explanation

Why this problem exists in real interviews

Per-entity latest-row queries are the bread and butter of operational reporting. Interviewers use this prompt to see whether you reach for ROW_NUMBER with a deterministic tie-break instead of GROUP BY + MAX, which silently loses non-aggregated columns or breaks on ties.


Break down the requirements

Step 1: Pick one row per owner_id, latest first

Number each token within its owner_id partition by last_used descending (token_id descending as a deterministic tie-breaker) using ROW_NUMBER().

Step 2: Tie-break on largest token_id

Keep only rn = 1, the single most recently used record per owner.

Step 3: Filter rn = 1 in the outer query and project all columns

SELECT * so every token field (token_id, owner_id, scope, status, issued, expires, last_used, requests) plus the rn row indicator is returned.


The solution

`ROW_NUMBER` per owner with explicit tie-break
SELECT *
FROM (
  SELECT *,
         ROW_NUMBER() OVER (PARTITION BY owner_id ORDER BY last_used DESC, token_id DESC) AS rn
  FROM api_tokens
)
WHERE rn = 1
ORDER BY owner_id

Common follow-up questions