The Token Census

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
L3
Asked in
Apple

Problem

The platform team needs a headcount of how many token owners issued at least one API token during 2026. Return a single count of unique owners.

How many tokens are out there?

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 1 of 1 rows
distinct_owners
10

Worked solution and explanation

What this really is

This is a headcount across a one-to-many table dressed up as a platform metric. api_tokens holds one row per token, and the same owner_id turns up on several of them: the ten owners who issued anything in 2026 issued two tokens each. Everyone gets the year filter roughly right. What separates candidates is whether the count collapses tokens back to people. Count rows and you report 20, a token count wearing an owner label, and it grows every time someone rotates a key.


Break down the requirements

Step 1: Force the grain question

'Headcount of owners who issued at least one token' means COUNT(DISTINCT owner_id), not COUNT(*) and not COUNT(DISTINCT token_id). Say the cohort out loud: unique owner_id values from api_tokens, restricted to the year.

Step 2: Filter on issuance, not expiry

The prompt says 'issued ... during 2026', so the predicate is on issued, not expires or last_used. Every sample row was last used in 2026, so filtering on activity quietly answers a different question.

Step 3: Read the year off issued

issued is stored as 'YYYY-MM-DD' text, so strftime('%Y', issued) = '2026' reads the year straight off it. Say out loud that in production you would write the half-open range issued >= '2026-01-01' AND issued < '2027-01-01' instead, so an index or partition on issued can be used.

Step 4: Return one scalar

One SELECT, one COUNT(DISTINCT owner_id), aliased distinct_owners. No GROUP BY, no HAVING. The output is one row and one column.


The solution

DISTINCT OWNERS ISSUED IN YEAR
SELECT COUNT(DISTINCT owner_id) AS distinct_owners
FROM api_tokens
WHERE strftime('%Y', issued) = '2026'

Common follow-up questions

Common follow-up questions