SQL ORDER BY, LIMIT & DISTINCT Cheat Sheet
Three SQL clauses you will use constantly, explained with practical examples, expected output, and common mistakes.
ORDER BY: sort the result
ORDER BY controls how returned rows are displayed. Use ASC for ascending order and DESC for descending order. When values can tie, add a second column so the order stays deterministic.
- ASC is the default
- DESC returns the largest values first
- Multiple columns provide stable tie-breaking
SELECT employee_name, salary
FROM employees
ORDER BY salary DESC, employee_name ASC;LIMIT: return only the rows you need
LIMIT is useful for previews, pagination, and top-N analysis. Combine it with ORDER BY when 'first' or 'top' has a business meaning.
- LIMIT without ORDER BY does not guarantee which rows are returned
- Use it to inspect a dataset before writing a larger query
SELECT employee_name, salary
FROM employees
ORDER BY salary DESC
LIMIT 3;DISTINCT: remove duplicate combinations
DISTINCT keeps one copy of each selected value combination. It is useful for exploring categories, but it should not be used to hide an incorrect join.
- DISTINCT applies to the complete selected row
- Check the join relationship before using DISTINCT after a join
SELECT DISTINCT department
FROM employees
ORDER BY department;Combine all three
This query returns the first five unique departments alphabetically. Read it in execution order: choose the table, remove duplicate selected values, sort, then limit the output.
SELECT DISTINCT department
FROM employees
ORDER BY department ASC
LIMIT 5;Turn the concept into practice
Write real queries, run them safely, and compare the result with a verified solution.
Open Practice Arena