Top Percentile API Tokens

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

Domain
SQL
Difficulty
hard
Seniority
L5
Asked in
Google

Problem

Consider tokens at or above the 95th percentile by total requests within each scope as high-risk. Show the token ID, scope, request count, and percentile rank, rounded to 2 decimal places. Present the results in alphabetical order by scope, listing each scope's busiest tokens first and, when two tokens are tied on requests, the lower-numbered one ahead.

The most suspicious tokens.

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 14 rows
token_idscoperequestspercentile_rank
5300admin47000.97
10005400admin47000.97
5171full_access45590.96
10005397full_access45590.96
5257write46530.97

Worked solution and explanation

Why this problem exists in real interviews

"95th percentile" sounds unambiguous until you try three functions and get three answers. PERCENT_RANK, CUME_DIST, and NTILE all return something defensible, and only one matches what a security engineer means when they flag the noisiest tokens in each scope.


Break down the requirements

Step 1: Partition by scope

High-volume is relative inside each scope. A read-only token doing 10k requests is normal; an admin token doing the same is not. Every percentile calculation must PARTITION BY scope.

Step 2: Pick the right percentile function

Use PERCENT_RANK() with ORDER BY requests ASC. It returns (rank - 1) / (n - 1), so the >= 0.95 filter captures the top 5 percent within each partition.

Step 3: Round for presentation only

ROUND(pct_rank, 2) shapes the output column. Do not round inside the window or before the comparison or you lose precision on the boundary.


The solution

TOP PERCENTILE API TOKENS
WITH ranked AS (
  SELECT token_id, scope, requests,
         PERCENT_RANK() OVER (
           PARTITION BY scope
           ORDER BY requests ASC
         ) AS pct_rank
  FROM api_tokens
)
SELECT token_id, scope, requests,
       ROUND(pct_rank, 2) AS percentile_rank
FROM ranked
WHERE pct_rank >= 0.95
ORDER BY scope, requests DESC, token_id

COMMON FOLLOW-UP QUESTIONS

Common follow-up questions