Sub topic 6
Restricting rows with LIMIT
This chapter covers the LIMIT clause: what it does, how it behaves with ORDER BY and WHERE, and where it differs between databases. It assumes you can write a basic SELECT ... FROM query, filter with WHERE, and sort with ORDER BY. You should also know what tables, rows, and columns are.
The examples use two tables. customers has the columns customer_id, name, country, and city. orders has the columns order_id, customer_id, order_date, and total.
What LIMIT does
LIMIT sets the maximum number of rows a query returns. The database computes the result as usual, then hands back only the first n rows.
SELECT order_id, order_date, total
FROM orders
LIMIT 5;This returns at most five rows. If the table holds only three orders, you get three rows and no error. LIMIT is a ceiling, not a promise.
LIMIT always goes at the end of the query, after WHERE, GROUP BY, HAVING, and ORDER BY. Putting it earlier is a syntax error.
SELECT order_id, total
FROM orders
WHERE total > 100
ORDER BY total DESC
LIMIT 3;Here the database filters to orders over 100, sorts them from largest to smallest, and returns the top three.
Why use LIMIT
LIMIT is useful in four common situations.
- Previewing data.
SELECT * FROM big_table LIMIT 10;shows the shape of a table without pulling millions of rows into your client. - Top-N queries. "The five most recent orders" or "the three largest payments" combine
ORDER BYwithLIMIT. - Protecting the application. A cap on rows keeps one careless query from flooding memory or the network.
- Paging. Together with
OFFSET,LIMITlets you return results one page at a time. The next chapters cover that.
LIMIT without ORDER BY
A relational table has no built-in order. If you omit ORDER BY, the database returns rows in whatever order is convenient for its execution plan. That order can depend on the physical layout of the data, on which index the planner picks, on parallel workers, or on the cache state.
SELECT order_id, order_date, total
FROM orders
LIMIT 5;This query is valid, and it returns five rows. It does not return the first five orders, the newest five, or any other meaningful five. Running it again after an UPDATE, a VACUUM, or an index change can return a different set.
Use LIMIT without ORDER BY only when any rows will do, such as a quick look at a table. For anything the application depends on, add an explicit sort.
Making the result deterministic
An ORDER BY on one column is not always enough. If several rows share the same value in the sort column, the database can return them in any order. When the cutoff falls inside such a group, the set of rows returned can change between runs.
Suppose three orders were placed on the same day, and you ask for the top two by date only:
SELECT order_id, order_date, total
FROM orders
ORDER BY order_date DESC
LIMIT 2;Which two of the three same-day orders come back is unspecified. The fix is a tie-breaker: add a column that is unique, usually the primary key, as the last sort key.
SELECT order_id, order_date, total
FROM orders
ORDER BY order_date DESC, order_id DESC
LIMIT 5;This returns the five most recent orders. Because order_id is unique, no two rows tie on the full sort key, so the result is the same every time as long as the data does not change.
LIMIT and WHERE
WHERE runs before LIMIT. The database first discards rows that fail the filter, then sorts the survivors, then keeps the first n.
SELECT order_id, order_date, total
FROM orders
WHERE order_date >= '2024-01-01'
ORDER BY order_date, order_id
LIMIT 10;This gives the ten earliest orders of 2024 or later. It does not take ten rows and then filter them. Mixing up the two orders of operation is a common source of wrong results, and the chapter on evaluation order returns to it.
LIMIT 0 and edge values
A few edge cases are worth knowing.
| Value | Behavior |
|---|---|
| `LIMIT 0` | Returns no rows but still returns the column names and types. Useful for checking a query's shape. |
| `LIMIT` larger than the row count | Returns all rows. No error. |
| Negative value | Depends on the database. PostgreSQL raises an error. SQLite treats a negative limit as "no limit". |
| `LIMIT NULL` | PostgreSQL treats it as no limit. Other databases may reject it. |
| Non-integer value | An error in most databases. |
Do not rely on negative or NULL limits for portable code. If a query needs a limit that is sometimes absent, build the SQL string without the clause or use a very large number.
LIMIT with other clauses
LIMIT acts on the final result set, which affects how it interacts with grouping and DISTINCT.
With GROUP BY, LIMIT caps the number of groups returned, not the number of source rows read:
SELECT customer_id, SUM(total) AS spent
FROM orders
GROUP BY customer_id
ORDER BY spent DESC, customer_id
LIMIT 3;The database must still read every order to compute the sums. LIMIT here saves output, not work.
The same applies to DISTINCT. The database removes duplicates first and then cuts the list:
SELECT DISTINCT country
FROM customers
ORDER BY country
LIMIT 5;This returns the first five unique countries in alphabetical order. Asking for five rows does not mean five source rows were examined. The chapter on combining DISTINCT, ORDER BY, and LIMIT covers this in detail.
When LIMIT saves work and when it does not
LIMIT can make a query much faster, but only in some cases.
- Fast case. With no
ORDER BY, or with anORDER BYthat matches an index, the database can stop reading as soon as it has n rows. An index on(order_date, order_id)lets the top-five query above read five index entries and finish. - Slow case. With an
ORDER BYthat has no matching index, the database must read and sort all qualifying rows before it can pick the first n. Many planners use a "top-N heapsort" that keeps only n rows in memory, but the full scan still happens.
You can see which case you are in by inspecting the query plan with EXPLAIN. Look for a sort step on a large number of rows.
Dialect differences
LIMIT is not part of the SQL standard, although PostgreSQL, MySQL, MariaDB, and SQLite all support it. Other systems use different syntax for the same idea.
| Database | Syntax for "first 5 rows" |
|---|---|
| PostgreSQL, MySQL, MariaDB, SQLite | `LIMIT 5` |
| SQL Server, MS Access | `SELECT TOP 5 ...` |
| Standard SQL, Oracle 12c+, PostgreSQL, SQL Server 2012+ | `FETCH FIRST 5 ROWS ONLY` |
| Older Oracle | `WHERE ROWNUM <= 5` |
The standard form looks like this:
SELECT order_id, order_date, total
FROM orders
ORDER BY order_date DESC, order_id DESC
FETCH FIRST 5 ROWS ONLY;In SQL Server, TOP goes right after SELECT:
SELECT TOP 5 order_id, order_date, total
FROM orders
ORDER BY order_date DESC, order_id DESC;Be careful with the older Oracle form. ROWNUM is assigned before ORDER BY runs, so WHERE ROWNUM <= 5 ORDER BY ... sorts only five arbitrary rows. You must put the sorted query in a subquery and apply ROWNUM outside it. On Oracle 12c and later, use FETCH FIRST instead.
Common errors
- Syntax error near LIMIT. You are probably on SQL Server or Oracle. Use
TOPorFETCH FIRST. - Different rows on each run. The query has no
ORDER BY, or the sort key has ties. Add a unique tie-breaker. - Fewer rows than expected. The
WHEREclause removed rows beforeLIMITran, or the table simply has fewer rows than the limit. - Query is still slow.
LIMITdoes not avoid a full scan when the database has to sort everything first. Check the plan and consider an index that matches theORDER BY. - A limit applied in the wrong place. In a query with a subquery or a join, a
LIMITinside a subquery limits only that subquery. Check whichSELECTthe clause belongs to.
Summary
LIMIT n returns at most n rows after filtering, grouping, deduplicating, and sorting. It is only meaningful with ORDER BY, and the sort should end with a unique column so ties cannot change the result. It caps output, but it speeds up a query only when an index lets the database stop early. The syntax varies: TOP in SQL Server, FETCH FIRST in standard SQL, and ROWNUM in older Oracle.
Exercise
A query SELECT order_id, order_date FROM orders ORDER BY order_date DESC LIMIT 3; returns different order IDs on two runs, even though no data changed between them. Why can this happen, and how do you fix it?
Show answer
Several orders share the same order_date, so the sort key has ties. When the cutoff at row 3 falls inside a group of tied rows, the database may return any of them. Add a unique tie-breaker as the last sort key: ORDER BY order_date DESC, order_id DESC.
Exercise
Write a query that returns the three customers with the highest total spending, using orders.customer_id and orders.total. Make the result deterministic.
Show answer
SELECT customerid, SUM(total) AS spent FROM orders GROUP BY customerid ORDER BY spent DESC, customerid LIMIT 3; The `customerid at the end of ORDER BY` breaks ties between customers with equal totals.
Exercise
Translate SELECT order_id, total FROM orders ORDER BY total DESC, order_id DESC LIMIT 10; for SQL Server, and then into standard SQL.
Show answer
SQL Server: SELECT TOP 10 orderid, total FROM orders ORDER BY total DESC, orderid DESC; Standard SQL: SELECT orderid, total FROM orders ORDER BY total DESC, orderid DESC FETCH FIRST 10 ROWS ONLY;