Sub topic 14
Top-N queries: ORDER BY with LIMIT or FETCH FIRST
This chapter assumes you can write a SELECT with WHERE and ORDER BY, and that you know NULL means "no value". You need access to PostgreSQL, MySQL, or SQLite to try the examples. They use the employees table from earlier chapters.
What a top-N query is
A top-N query returns only the first N rows of a sorted result. Examples are the five highest-paid employees, the ten newest orders, or the three cheapest products.
The idea has two parts:
- Sort the rows with
ORDER BYso the ones you want come first. - Cut the result off after N rows.
A row limit without ORDER BY is almost always a bug. A table has no built-in row order, so the database may return any N rows. Those rows can differ between runs.
The LIMIT form
PostgreSQL, MySQL, and SQLite use LIMIT:
SELECT first_name, salary
FROM employees
ORDER BY salary DESC
LIMIT 5;ORDER BY salary DESC puts the largest salary first. LIMIT 5 keeps the first five rows of that sorted result. LIMIT is always the last clause in the statement.
The standard FETCH FIRST form
The SQL standard (since SQL:2008) uses FETCH FIRST:
SELECT first_name, salary
FROM employees
ORDER BY salary DESC
FETCH FIRST 5 ROWS ONLY;This returns the same rows as the LIMIT query. FIRST and NEXT are interchangeable, and so are ROW and ROWS. FETCH FIRST 1 ROW ONLY is valid.
Dialect differences
Support differs between databases:
| Database | Row-limit syntax |
|---|---|
| PostgreSQL | `LIMIT n` and `FETCH FIRST n ROWS ONLY` |
| MySQL | `LIMIT n` only |
| SQLite | `LIMIT n` only |
| Oracle (12c and later) | `FETCH FIRST n ROWS ONLY` |
| SQL Server | `TOP n` after `SELECT`, or `OFFSET ... FETCH` after `ORDER BY` |
| Db2 | `FETCH FIRST n ROWS ONLY` |
SQL Server's TOP goes at the start of the query:
SELECT TOP 5 first_name, salary
FROM employees
ORDER BY salary DESC;If you write portable code, FETCH FIRST works in the most databases. If you work in one database every day, use its native form.
Where the limit happens
The limit is applied after sorting, which is the last step of query evaluation:
Two things follow from this order:
WHEREremoves rows before the sort. A filter and a limit therefore give you "top N among the matching rows".- The limit never changes which rows are sorted. It only trims the sorted output.
This query returns the three highest-paid employees in Sales:
SELECT first_name, salary
FROM employees
WHERE department = 'Sales'
ORDER BY salary DESC
LIMIT 3;Smallest N and largest N
Use ASC for the smallest values and DESC for the largest. ASC is the default.
SELECT first_name, hire_date
FROM employees
ORDER BY hire_date ASC
LIMIT 3;This returns the three earliest hires. Change ASC to DESC to get the three most recent hires.
Ties at the cutoff
Suppose the fifth and sixth highest salaries are both 72000. LIMIT 5 returns one of those two employees. The database chooses which one, and the choice can change between runs or after an index is added.
You have two ways to handle this.
Add a tie-breaker
Add a column that makes the order unique. This example assumes employee_id is a unique column:
SELECT first_name, salary
FROM employees
ORDER BY salary DESC, employee_id ASC
LIMIT 5;The result is now repeatable. The rule is: if the sort columns can contain duplicates, finish the ORDER BY with a unique column.
Keep all tied rows
WITH TIES returns every row that ties with the last row in the limit:
SELECT first_name, salary
FROM employees
ORDER BY salary DESC
FETCH FIRST 5 ROWS WITH TIES;This may return more than five rows. It is available in PostgreSQL 13 and later, Oracle 12c and later, and Db2. MySQL and SQLite do not support it. SQL Server offers SELECT TOP 5 WITH TIES. WITH TIES requires an ORDER BY.
NULL values in top-N results
Chapter ordering rules for NULL matter here. Databases disagree on where NULL sorts:
| Database | NULLs in ascending order | NULLs in descending order |
|---|---|---|
| PostgreSQL | last | first |
| Oracle | last | first |
| MySQL | first | last |
| SQLite | first | last |
| SQL Server | first | last |
In PostgreSQL and Oracle, ORDER BY salary DESC LIMIT 5 can return employees whose salary is unknown. These rows appear first, and they are not the top earners.
The most portable fix is to filter them out:
SELECT first_name, salary
FROM employees
WHERE salary IS NOT NULL
ORDER BY salary DESC
LIMIT 5;PostgreSQL, Oracle, and SQLite 3.30 and later also accept NULLS FIRST and NULLS LAST in the sort:
SELECT first_name, salary
FROM employees
ORDER BY salary DESC NULLS LAST
LIMIT 5;Filtering and NULLS LAST behave differently. Filtering removes the rows. NULLS LAST keeps them, and they appear only if fewer than N rows have a real value.
Skipping rows with OFFSET
OFFSET skips a number of rows before the limit starts counting. It is the basis of simple paging.
SELECT first_name, salary
FROM employees
ORDER BY salary DESC, employee_id ASC
LIMIT 10 OFFSET 20;This skips the first 20 rows and returns rows 21 to 30. The standard form is:
SELECT first_name, salary
FROM employees
ORDER BY salary DESC, employee_id ASC
OFFSET 20 ROWS
FETCH NEXT 10 ROWS ONLY;Paging only works if the order is stable. Without a unique tie-breaker, a row can appear on two pages or on none, because tied rows may be ordered differently on each request.
Common errors
- No ORDER BY. The query runs, but the rows are arbitrary. This is the most frequent mistake, and it is hard to notice on small test data.
- Wrong direction.
ORDER BY salary LIMIT 5returns the five lowest salaries, becauseASCis the default. - Using the wrong dialect.
LIMITin SQL Server or Oracle, orFETCH FIRSTin MySQL, raises a syntax error. - Expecting LIMIT to speed up the sort. The database often still sorts every matching row. An index on the sort column can let it stop early, but this is not guaranteed.
- Putting LIMIT before ORDER BY. The clauses have a fixed order, so this is a syntax error.
Summary
- A top-N query combines
ORDER BYwith a row limit. The limit is applied after sorting. - Use
LIMIT nin PostgreSQL, MySQL, and SQLite. UseFETCH FIRST n ROWS ONLYin the standard form. UseTOP nin SQL Server. - End the sort with a unique column so ties do not make the result unpredictable.
- Check how your database sorts
NULL, and filter them out or useNULLS LASTwhen they would distort the result.
Exercise
Write a query that returns the firstname and hiredate of the 4 most recently hired employees in the Support department. Make the result repeatable even if two employees share a hire date. Assume employee_id is unique. Use LIMIT.
Show answer
SELECT firstname, hiredate FROM employees WHERE department = 'Support' ORDER BY hiredate DESC, employeeid ASC LIMIT 4; WHERE filters to Support first. DESC puts the latest hire date first. employee_id breaks ties so the same four rows come back every time.
Exercise
A colleague runs this query in PostgreSQL to find the 3 highest salaries, but one result row shows a blank salary. Why does this happen, and how can you fix it in two different ways? SELECT first_name, salary FROM employees ORDER BY salary DESC LIMIT 3;
Show answer
PostgreSQL sorts NULL as larger than any value, so in descending order the NULL salaries come first and fill the limit. Fix 1: add WHERE salary IS NOT NULL before the ORDER BY. Fix 2: write ORDER BY salary DESC NULLS LAST.
Exercise
Rewrite this query so it also returns every employee who ties with the fifth-highest salary, using the standard syntax: SELECT first_name, salary FROM employees ORDER BY salary DESC LIMIT 5;
Show answer
SELECT first_name, salary FROM employees ORDER BY salary DESC FETCH FIRST 5 ROWS WITH TIES; This works in PostgreSQL 13 and later and in Oracle 12c and later. The result can contain more than 5 rows.