LIMIT with DISTINCT
Return the first 3 distinct department IDs.
- CTEs
- Sorting
- Top-N
- Distinct values
Interview brief
Understand the request
Data analyst The unique-department list needs to be capped at 3 entries for a dropdown widget.
Return the first 2 distinct department_id values, ordered ascending.
Return
- Return department_id only.
Constraints
- Use DISTINCT combined with LIMIT.
Data you will use
Review the relevant tables before deciding how to join, filter, or aggregate them.
employees
department_idINTEGER
Hints, when you need them
Open one clue at a time so you still do the reasoning.
Hint 1
Logical order: SELECT runs DISTINCT, ORDER BY sorts the unique rows, LIMIT trims them.
Hint 2
DISTINCT applies to the entire SELECT list, not a single column.
Hint 3
SELECT DISTINCT department_id FROM employees ORDER BY department_id LIMIT 2
Verified SQL answer
Attempt the problem first, then compare structure and reasoning—not just syntax.
Reveal solution and explanation
SELECT DISTINCT department_id FROM employees ORDER BY department_id LIMIT 2;Why this works
A common mistake: writing `SELECT DISTINCT department_id, employee_id` and being surprised the results are not unique by department_id. DISTINCT considers every column in the SELECT.
Expected result
Use this output to verify values, aliases, ordering, and row count.
| department_id |
|---|
| 1 |
| 2 |
Learn the concepts behind this answer
Strengthen your understanding with these targeted learning topics: