Sub topic 14
Top-N Queries: ORDER BY with LIMIT or FETCH FIRST
Prerequisites
Assume you know how SELECT chooses columns and how WHERE filters rows. The examples use an employees table with first_name, department, and salary columns.
A top-N query returns only the first N rows from an ordered result. The database must sort the rows before it limits them. Otherwise, “top” has no reliable meaning.
Why ORDER BY Comes First
Suppose you need the five highest-paid employees. Sort by salary in descending order, then limit the result:
SELECT first_name, department, salary
FROM employees
ORDER BY salary DESC
LIMIT 5;DESC means descending order, so the largest salaries come first. LIMIT 5 keeps only the first five rows after sorting.
To find the five lowest salaries, use ascending order:
SELECT first_name, department, salary
FROM employees
ORDER BY salary ASC
LIMIT 5;ASC is the default, but writing it explicitly can make the query easier to read.
Filtering Before Limiting
A top-N query often includes a WHERE condition. The filter is applied before sorting and limiting:
SELECT first_name, department, salary
FROM employees
WHERE department = 'Sales'
ORDER BY salary DESC
LIMIT 3;This returns the three highest-paid employees in Sales, not the three highest-paid employees overall who happen to work in Sales.
Use a deterministic second sort key when ties matter:
SELECT first_name, department, salary
FROM employees
ORDER BY salary DESC, first_name ASC
LIMIT 5;The database sorts by salary first. If two employees have the same salary, it sorts those employees by first name. Without a tie-breaker, the order among equal values may vary.
Dialect Differences
LIMIT is common in PostgreSQL, MySQL, and SQLite. Some database systems use FETCH FIRST instead:
SELECT first_name, department, salary
FROM employees
ORDER BY salary DESC
FETCH FIRST 5 ROWS ONLY;The position of the clause matters. FETCH FIRST and LIMIT follow ORDER BY. Check your database's syntax before moving a query between systems.
| Database style | Example ending | Typical use |
|---|---|---|
| PostgreSQL, MySQL, SQLite | `LIMIT 5` | Return five rows |
| SQL standard style | `FETCH FIRST 5 ROWS ONLY` | Return five rows |
Common Errors
ORDER BY salary ASCfinds the lowest salaries, not the highest.LIMIT 5withoutORDER BYdoes not mean “the first five inserted rows.”- Applying
LIMITbefore filtering changes the question. Filter the full input, then select the top rows from the matches. - Ties can make the final row unstable. Add another sort column when repeatable output is required.
- A large offset, such as
LIMIT 20 OFFSET 100000, can become slow because the database may still process and skip many rows.
Exercise
Write a query that returns the two highest-paid employees in the Support department. Sort equal salaries by last name in ascending order.
Show answer
SELECT firstname, lastname, salary FROM employees WHERE department = 'Support' ORDER BY salary DESC, last_name ASC LIMIT 2;