Part 02 / Topic 8 of 9
LIMIT, OFFSET and FETCH FIRST
LIMIT caps how many rows come back. With ORDER BY it answers every "top N" question — the three most expensive products actually in stock:
SELECT name, price, stock
FROM products
WHERE stock > 0
ORDER BY price DESC
LIMIT 3;
name | price | stock
---------------+---------+-------
Laptop Pro 14 | 1200.00 | 15
Laptop Air 13 | 950.00 | 8
Phone X | 799.00 | 25
(3 rows)
OFFSET skips rows first — page 2 of a 3-per-page product list:
SELECT name, price FROM products
ORDER BY price DESC
LIMIT 3 OFFSET 3;
name | price
--------------+--------
Phone Lite | 399.00
Coffee Maker | 120.00
Chef Knife | 80.00
(3 rows)
(Fine for small data; for paging through millions of rows, OFFSET gets slow — Stage 4 shows the better pattern, keyset pagination.)
The SQL standard spells this FETCH FIRST n ROWS ONLY, and brings one genuinely useful extra: WITH TIES keeps any rows tied with the last row returned:
SELECT name, price FROM products
ORDER BY price DESC
FETCH FIRST 2 ROWS WITH TIES;
name | price
---------------+---------
Laptop Pro 14 | 1200.00
Laptop Air 13 | 950.00
(2 rows)
No tie at the boundary, so it behaves like LIMIT 2 — but had another product cost exactly 950.00, it would have come along too. WITH TIES requires an ORDER BY (it defines what "tied" means).
🧪 Quick quiz — answer from memory, then check.
- What do you get from LIMIT without ORDER BY?
- Which keyword returns the top 3 rows plus any rows tied with the 3rd?
Show the answers
- Some n rows — no promise which. Top-N queries always need ORDER BY.
FETCH FIRST 3 ROWS WITH TIES(needs an ORDER BY;LIMIThas no ties variant).
Done here? The practice set for Part 2 — 8 exercises with solutions — is on the part page.