Sub topic 6
Restricting Rows with LIMIT
Assume you know basic SELECT and FROM syntax, can filter rows with WHERE, and can sort results with ORDER BY. This chapter shows how to return only part of a result set.
What LIMIT does
LIMIT restricts the number of rows returned by a query. It does not change the data stored in the table. It changes only the result of that query.
For example, this query returns at most five rows:
SELECT order_id, order_date, total
FROM orders
LIMIT 5;The database may stop after producing five rows. However, without an ORDER BY clause, you cannot rely on which five rows it returns. The database is free to choose any qualifying rows.
LIMIT 0 returns no rows. This can be useful for testing whether a query is valid without displaying data.
SELECT order_id, order_date, total
FROM orders
LIMIT 0;LIMIT with ORDER BY
Use ORDER BY when the rows have a meaningful order. For example, to return the five most recent orders, sort by the order date in descending order:
SELECT order_id, order_date, total
FROM orders
ORDER BY order_date DESC
LIMIT 5;This still has a possible ambiguity. Several orders may have the same order_date. If the database must choose among tied rows, their order is not guaranteed.
Add a unique or otherwise stable tie-breaker. Here, order_id identifies each order:
SELECT order_id, order_date, total
FROM orders
ORDER BY order_date DESC, order_id DESC
LIMIT 5;The database first sorts by the newest date. For equal dates, it sorts by the greatest order ID. The same query and data therefore produce a stable first five rows.
How LIMIT fits into a query
A useful working model is:
FROMidentifies the source rows.WHEREremoves rows that do not match the filter.ORDER BYarranges the remaining rows when requested.LIMITkeeps only the requested number of rows.
For example, this query finds the most expensive completed orders and returns only three:
SELECT order_id, order_date, total
FROM orders
WHERE status = 'completed'
ORDER BY total DESC, order_id DESC
LIMIT 3;The filter is applied before the sort and limit. An uncompleted order with a larger total cannot appear in the result.
Database differences
LIMIT is supported by PostgreSQL, MySQL, and SQLite. Other systems use different syntax. SQL Server commonly uses TOP:
SELECT TOP 5 order_id, order_date, total
FROM orders
ORDER BY order_date DESC, order_id DESC;Oracle supports FETCH FIRST:
SELECT order_id, order_date, total
FROM orders
ORDER BY order_date DESC, order_id DESC
FETCH FIRST 5 ROWS ONLY;Check the SQL dialect used by your database before moving a query between systems.
Exercise
Write a query that returns the two lowest-priced completed orders, with a deterministic order when prices are equal.
Show answer
SELECT orderid, orderdate, total FROM orders WHERE status = 'completed' ORDER BY total ASC, order_id ASC LIMIT 2;