User Age Ranking
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
- Airbnb
Problem
Assign each user a rank based on their age bucket in descending order (oldest bucket first). Show each user's ID and their assigned rank.
Age brackets, stacked from top to bottom.
Tables
users
Columns: user_id INTEGER, username TEXT, email TEXT, signup_date TEXT, account_status TEXT, age_bucket TEXT
| user_id | username | signup_date | account_status | age_bucket | |
|---|---|---|---|---|---|
| 100 | alice | alice@example.com | 2025-02-02 | inactive | 25-34 |
| 197 | aaron42 | aaron42@example.com | 2026-03-03 | suspended | 35-44 |
| 294 | amelia | amelia@example.com | 2024-04-04 | pending_verification | 45-54 |
| 391 | arjun | arjun@example.com | 2025-05-05 | active | 55-64 |
| 488 | ava99 | ava99@example.com | 2026-06-06 | inactive | 65+ |
| 585 | andrew_k | andrew_k@example.com | 2024-07-07 | suspended | NULL |
| 682 | anika | anika@example.com | 2025-08-08 16:34:00 | pending_verification | 18-24 |
| 779 | aiden | aiden@example.com | 2026-09-09 14:53:00 | active | 25-34 |
| 876 | aria_b | aria_b@example.com | 2024-10-10 | inactive | 35-44 |
| 973 | brian | brian@example.com | 2025-11-11 | suspended | 45-54 |
Expected output
| user_id | rank |
|---|---|
| 488 | 1 |
| 1167 | 1 |
| 391 | 2 |
| 294 | 3 |
| 197 | 4 |
Worked solution and explanation
Why this problem exists in real interviews
This tests basic window function usage with ROW_NUMBER or RANK. Interviewers verify that you can rank rows by a column value without grouping.
Break down the requirements
Step 1: Rank by age bucket descending
Prose asks: rank each user by their age bucket, oldest bucket first, output user_id and rank. A 'rank based on age bucket' means users sharing a bucket share a rank, so a ranking function over age_bucket (not a per-row ROW_NUMBER) is required.
Step 2: Return user ID and rank
The users.age_bucket values are text labels '18-24','25-34','35-44','45-54','55-64','65+' (plus some NULL). Their first digit increases monotonically with age, so plain lexical ordering equals age ordering; ORDER BY age_bucket DESC puts '65+' first and '18-24' last, exactly 'oldest bucket first'.
The solution
SELECT user_id,
DENSE_RANK() OVER (ORDER BY age_bucket DESC) AS rank
FROM users
ORDER BY rank, user_id;Common follow-up questions
- What if `age_bucket` were stored as a string like '18-24' and you needed numeric ordering? (Tests CAST or SUBSTR to extract the lower bound for sorting.)
- How would you rank within each `account_status` group? (Add PARTITION BY `account_status` to the window function.)
- What if two users have the same `age_bucket` and you need deterministic ranking? (Add `user_id` as a tiebreaker in the ORDER BY.)