DISTINCT, LIMIT, FETCH FIRST and Pagination in SQL
Removing duplicate rows with DISTINCT (and PostgreSQL's DISTINCT ON), limiting results with FETCH FIRST, LIMIT, TOP and ROWNUM, WITH TIES, OFFSET, and the two ways to paginate: OFFSET, which gets slower on every page, and keyset pagination, which doesn't.
kvi5hnuCode Sprout team member11 min readOn this page
Two questions come up in almost every application: "which different values are there?" and "show me only the first few rows". This article covers both: DISTINCT for removing duplicate rows, and the row-limiting clauses for taking the top n rows or one page of results.
DISTINCT
SELECT DISTINCT removes duplicate rows from the result. Two rows are duplicates when every selected column has the same value.
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
\pset null '(null)'
-- One row per distinct value
SELECT DISTINCT category FROM products ORDER BY category;
-- DISTINCT applies to the whole row: one row per distinct (category, brand) pair
SELECT DISTINCT category, brand FROM products ORDER BY category, brand;
-- NULLs count as one value for DISTINCT
SELECT DISTINCT brand FROM products ORDER BY brand;
-- Counting distinct values (aggregates come in Part 4)
SELECT COUNT(*) AS products, COUNT(DISTINCT category) AS categories, COUNT(DISTINCT brand) AS brands
FROM products;
category
----------
clothing
lighting
packs
tents
(4 rows)
category | brand
----------+---------
clothing | Woolly
lighting | Lumen
lighting | (null)
packs | Kestrel
tents | Alpina
(5 rows)
brand
---------
Alpina
Kestrel
Lumen
Woolly
(null)
(5 rows)
products | categories | brands
----------+------------+--------
7 | 4 | 4
(1 row)
- One column: four categories, each listed once.
- Several columns:
DISTINCTapplies to the whole selected row, not to the first column.lightingappears twice because it occurs with two different brands,Lumenand NULL. A common misconception is thatSELECT DISTINCT a, bmeans "distincta, plus someb". It doesn't. - NULLs: for
DISTINCT, all NULLs count as one value, so(null)appears once even if many rows have no brand. (In comparisons NULL isn't equal to NULL, but grouping operations treat NULLs as the same, as article 8 explains.) COUNT(DISTINCT col)counts the different non-NULL values. There are five distinct brand values if you count the NULL, butCOUNT(DISTINCT brand)is 4, because aggregates ignore NULLs. Part 4 covers counting.
SELECT ALL, the opposite of DISTINCT, is the default and is almost never written.
When DISTINCT is a warning sign
DISTINCT has to compare every result row with the others, usually by sorting or hashing, so it costs time on big results. More importantly, it's often used to hide a mistake. If a query returns duplicates you didn't expect, the usual cause is a join that matches each row several times (article 17). Adding DISTINCT hides the symptom and leaves the wrong totals in place. Use DISTINCT when you really want the set of different values, not to fix a result that looks wrong.
One row per group: DISTINCT ON
A frequent need is "for each category, the most expensive product". Plain DISTINCT can't do that, because it compares whole rows. PostgreSQL has a non-standard extension, DISTINCT ON (expressions), that keeps the first row of each group, where "first" is decided by ORDER BY:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
-- PostgreSQL's DISTINCT ON: the first row of each group, by the ORDER BY
SELECT DISTINCT ON (category) category, name, price
FROM products
ORDER BY category, price DESC;
category | name | price
----------+-------------------+--------
clothing | Merino socks | 16.00
lighting | Glow head torch | 34.50
packs | Trail 30 backpack | 89.95
tents | Summit 4 tent | 489.00
(4 rows)
The ORDER BY must start with the DISTINCT ON expressions. After that, the remaining sort keys choose which row is kept. The portable way to write the same query, which works in every product, uses the ROW_NUMBER() window function (article 27).
Limiting rows: FETCH FIRST, LIMIT, TOP and ROWNUM
Every product can return just the first n rows of a result, but the syntax varies:
| Product | First 3 rows | Skip 2, then 3 rows |
|---|---|---|
| Standard SQL (PostgreSQL, Oracle 12c+, Db2) | FETCH FIRST 3 ROWS ONLY | OFFSET 2 ROWS FETCH NEXT 3 ROWS ONLY |
| PostgreSQL, MySQL, SQLite | LIMIT 3 | LIMIT 3 OFFSET 2 |
| SQL Server | SELECT TOP (3) ..., or OFFSET 0 ROWS FETCH NEXT 3 ROWS ONLY | standard OFFSET / FETCH (both require ORDER BY) |
| Oracle before 12c | WHERE ROWNUM <= 3 (with care: see below) | nested subqueries with ROWNUM |
MySQL doesn't support the standard FETCH FIRST. It also accepts LIMIT 2, 3 (offset first, then count), which is easy to misread, so prefer LIMIT 3 OFFSET 2.
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
-- The three cheapest products: standard FETCH FIRST
SELECT name, price FROM products
ORDER BY price
FETCH FIRST 3 ROWS ONLY;
-- The same with LIMIT (PostgreSQL, MySQL, SQLite)
SELECT name, price FROM products
ORDER BY price
LIMIT 3;
-- Skip the first two, then take three
SELECT name, price FROM products
ORDER BY price
OFFSET 2 ROWS FETCH NEXT 3 ROWS ONLY;
-- WITH TIES keeps every row that ties with the last one
CREATE TABLE scores (player VARCHAR(10), points INTEGER);
INSERT INTO scores VALUES ('Ana', 90), ('Bo', 85), ('Cy', 85), ('Di', 85), ('Ed', 70);
SELECT player, points FROM scores ORDER BY points DESC FETCH FIRST 2 ROWS ONLY;
SELECT player, points FROM scores ORDER BY points DESC FETCH FIRST 2 ROWS WITH TIES;
name | price
------------------+-------
Merino socks | 16.00
Basecamp lantern | 27.00
Glow head torch | 34.50
(3 rows)
name | price
------------------+-------
Merino socks | 16.00
Basecamp lantern | 27.00
Glow head torch | 34.50
(3 rows)
name | price
-------------------+-------
Glow head torch | 34.50
Day 18 backpack | 54.00
Trail 30 backpack | 89.95
(3 rows)
player | points
--------+--------
Ana | 90
Bo | 85
(2 rows)
player | points
--------+--------
Ana | 90
Bo | 85
Cy | 85
Di | 85
(4 rows)
FETCH FIRST 3 ROWS ONLYandLIMIT 3return the same three rows.FIRSTandNEXT, andROWandROWS, are interchangeable: the standard allows both spellings so that the clause reads naturally.OFFSET 2 ROWSskipped the two cheapest products, then took the next three.WITH TIESkeeps any extra rows that tie with the last row on theORDER BYkey. Asking for the top 2 scores with ties returned four players, because Cy and Di have the same 85 points as Bo. WithoutWITH TIES, which one of the three 85-point players made the cut is arbitrary.WITH TIESis supported in PostgreSQL 13+, Oracle, and SQL Server (asTOP (2) WITH TIES). MySQL and SQLite don't have it.
Always pair a row limit with an ORDER BY. A limit without a sort returns some rows, and which ones can change from run to run. SQL Server even requires ORDER BY for OFFSET/FETCH.
The ROWNUM trap in old Oracle code
Oracle's ROWNUM pseudocolumn numbers rows as they're produced, before ORDER BY runs. So this common-looking query doesn't return the three cheapest products. It returns three arbitrary products, sorted:
SELECT name, price FROM products WHERE ROWNUM <= 3 ORDER BY price;
The classic fix sorts in a subquery first, then applies ROWNUM outside it:
SELECT * FROM (SELECT name, price FROM products ORDER BY price) WHERE ROWNUM <= 3;
Since Oracle 12c, simply use FETCH FIRST 3 ROWS ONLY.
Pagination
Web pages and APIs rarely show all results at once. They show one page at a time: rows 1–20, then 21–40, and so on. There are two ways to fetch a page.
OFFSET pagination
The simple way is to skip the earlier pages with OFFSET: page p of size n is LIMIT n OFFSET (p - 1) * n. It's easy to build, and it lets users jump straight to page 37. But it has two problems:
- It gets slower with every page. The database can't jump to row 10,001. It has to produce and throw away the first 10,000 rows of the sorted result every time someone asks for page 501.
- Rows shift between requests. If a new order arrives while someone is reading page 1, every row moves down one position, and the last row of page 1 appears again at the top of page 2. Deleted rows make other rows skip a page in the same way.
Keyset pagination
The alternative, called keyset or seek pagination, remembers where the last page ended and asks for the rows that come after it:
-- 1,000 orders, one hour apart (generate_series is PostgreSQL's row generator)
CREATE TABLE orders AS
SELECT g AS order_id,
TIMESTAMP '2026-01-01 09:00' + g * INTERVAL '1 hour' AS placed_at,
(g * 37) % 500 + 10 AS total
FROM generate_series(1, 1000) AS g;
ALTER TABLE orders ADD PRIMARY KEY (order_id);
-- Page 3 of 10 rows, newest first, with OFFSET: skip 20, take 10
SELECT order_id, placed_at, total
FROM orders
ORDER BY placed_at DESC, order_id DESC
LIMIT 10 OFFSET 20;
-- Page 4 with keyset pagination: continue after the last row of page 3
SELECT order_id, placed_at, total
FROM orders
WHERE (placed_at, order_id) < (TIMESTAMP '2026-02-10 20:00', 971)
ORDER BY placed_at DESC, order_id DESC
LIMIT 10;
order_id | placed_at | total
----------+---------------------+-------
980 | 2026-02-11 05:00:00 | 270
979 | 2026-02-11 04:00:00 | 233
978 | 2026-02-11 03:00:00 | 196
977 | 2026-02-11 02:00:00 | 159
976 | 2026-02-11 01:00:00 | 122
975 | 2026-02-11 00:00:00 | 85
974 | 2026-02-10 23:00:00 | 48
973 | 2026-02-10 22:00:00 | 11
972 | 2026-02-10 21:00:00 | 474
971 | 2026-02-10 20:00:00 | 437
(10 rows)
order_id | placed_at | total
----------+---------------------+-------
970 | 2026-02-10 19:00:00 | 400
969 | 2026-02-10 18:00:00 | 363
968 | 2026-02-10 17:00:00 | 326
967 | 2026-02-10 16:00:00 | 289
966 | 2026-02-10 15:00:00 | 252
965 | 2026-02-10 14:00:00 | 215
964 | 2026-02-10 13:00:00 | 178
963 | 2026-02-10 12:00:00 | 141
962 | 2026-02-10 11:00:00 | 104
961 | 2026-02-10 10:00:00 | 67
(10 rows)
The first query is page 3 using OFFSET. Its last row is order 971, placed at 2026-02-10 20:00. The second query fetches page 4 by asking for rows that sort after that row: (placed_at, order_id) < ('2026-02-10 20:00', 971), because the sort is descending.
- The comparison
(a, b) < (x, y)is a row value comparison. It meansa < x OR (a = x AND b < y), exactly the ordering ofORDER BY a, b. PostgreSQL, MySQL and SQLite support this kind of row comparison. In SQL Server and Oracle, write the expanded form. - With an index on
(placed_at, order_id), the database jumps straight to the start of the page. Page 4 and page 4,000 cost the same. - New and deleted rows don't shift the pages, because each page is defined by a position in the sort, not by a count of rows.
- The sort key must be unique, which is why
order_idis included as a tie-breaker. Otherwise rows with the sameplaced_atcould be skipped or repeated at page boundaries.

The trade-off is that keyset pagination can't jump to an arbitrary page number. It suits "next page" buttons, infinite scrolling and API cursors, which is what most applications need. Many sites combine the two: OFFSET for the first few pages, keyset for anything deeper.
Picking random rows
To pick a few random rows, sort randomly and take the first n:
SELECT name FROM products ORDER BY random() LIMIT 3; -- PostgreSQL, SQLite
SELECT name FROM products ORDER BY RAND() LIMIT 3; -- MySQL
SELECT TOP (3) name FROM products ORDER BY NEWID(); -- SQL Server
SELECT name FROM products ORDER BY DBMS_RANDOM.VALUE FETCH FIRST 3 ROWS ONLY; -- Oracle
These read and sort every row, which is fine for a few thousand rows. For large tables, use sampling instead: FROM products TABLESAMPLE SYSTEM (1) reads about 1% of the table's pages in PostgreSQL, SQL Server spells it TABLESAMPLE (1 PERCENT), and Oracle has a SAMPLE (1) clause. Sampling is fast, but it returns an approximate number of rows. (The results of these examples are random, so they're shown without output.)
What's current
FETCH FIRST ... WITH TIESis available in PostgreSQL (since 13), Oracle and SQL Server (TOP ... WITH TIES). MySQL and SQLite still only haveLIMIT.- PostgreSQL 18 can use a multicolumn B-tree index with a "skip scan" even when the query doesn't filter on its leading column, which helps some pagination and filtering queries. Keyset pagination with a matching index remains the standard technique for deep pages.
Common questions
Does DISTINCT apply to one column or the whole row?
The whole selected row. SELECT DISTINCT a, b returns each distinct combination of a and b.
Is SELECT DISTINCT the same as GROUP BY?
For removing duplicates, they give the same result: SELECT DISTINCT category FROM products and SELECT category FROM products GROUP BY category are equivalent, and optimizers usually produce the same plan. Use DISTINCT when you only want the distinct values, and GROUP BY when you also want aggregates for each group (Part 4).
Which is better, LIMIT or FETCH FIRST?
FETCH FIRST is standard and works in PostgreSQL, Oracle and Db2. SQL Server accepts FETCH only after an OFFSET (ORDER BY ... OFFSET 0 ROWS FETCH NEXT n ROWS ONLY). LIMIT works in PostgreSQL, MySQL and SQLite. If your code must run on MySQL, you need LIMIT; otherwise FETCH FIRST is the more portable choice.
Why does my top-10 query return different rows each time?
Either there's no ORDER BY, or the ORDER BY has ties at the cut-off. Add a unique tie-breaker, or use WITH TIES if all the tied rows should be included.
Is OFFSET always bad? No. For small offsets (the first few pages) it's perfectly fine, and it's the only simple way to support "go to page 37". It becomes a problem for deep pages on large tables.
How do I get the total number of pages?
Run a separate SELECT COUNT(*) with the same WHERE clause, or use a window function, COUNT(*) OVER () (article 26), to return the total alongside each page's rows. On very large tables, an exact count is itself expensive, which is why many sites show "about 10,000 results" or just a "next" link.
Summary
SELECT DISTINCTremoves duplicate rows, comparing every selected column. NULLs count as one value.DISTINCTis often a sign of a join that multiplies rows. Fix the join instead of hiding duplicates.- PostgreSQL's
DISTINCT ON (key)keeps the first row per group according toORDER BY.ROW_NUMBER()does the same portably. - Limit rows with standard
FETCH FIRST n ROWS ONLY(orLIMIT n,TOP (n)), always with anORDER BY.OFFSETskips rows.WITH TIESincludes rows that tie with the last one. - Oracle's
ROWNUMis assigned beforeORDER BY. UseFETCH FIRSTinstead. - OFFSET pagination slows down on deep pages and shifts when rows change. Keyset pagination (
WHERE (key) < (last key) ORDER BY key LIMIT n) costs the same on every page and needs a unique sort key.
Practice questions
How many rows does SELECT DISTINCT category, stock > 0 AS in_stock FROM products return, and why?
Answer
Five. The distinct (category, in_stock) pairs are: (tents, true), (lighting, true), (packs, true), (packs, false) and (clothing, true). Packs appear twice because one pack is in stock and the other isn't. DISTINCT compares the whole selected row, including computed columns.
Write a query that returns the second page of products, three per page, ordered by price from highest to lowest, in standard SQL.
Answer
SELECT name, price
FROM products
ORDER BY price DESC, product_id
OFFSET 3 ROWS FETCH NEXT 3 ROWS ONLY;
This skips the three most expensive products and returns the next three: the Day 18 backpack (54.00), the Glow head torch (34.50) and the Basecamp lantern (27.00). product_id is a tie-breaker, in case two products have the same price.
A teammate uses ORDER BY placed_at DESC LIMIT 20 with WHERE placed_at < :last_seen_placed_at for keyset pagination. Users report missing orders. What's wrong?
Answer
The sort key isn't unique. If several orders share the same placed_at and a page ends in the middle of them, the next page's condition placed_at < last_seen skips the remaining orders with that same timestamp. Include a unique column in both the sort and the condition: ORDER BY placed_at DESC, order_id DESC with WHERE (placed_at, order_id) < (:last_placed_at, :last_order_id).
An Oracle 11g query is SELECT * FROM orders WHERE ROWNUM <= 5 ORDER BY total DESC. Does it return the five largest orders?
Answer
No. ROWNUM is assigned as rows are produced, before the ORDER BY. So the query takes the first five rows Oracle happens to read, then sorts those five. To get the five largest, sort in a subquery first: SELECT * FROM (SELECT * FROM orders ORDER BY total DESC) WHERE ROWNUM <= 5. In Oracle 12c and later, write SELECT * FROM orders ORDER BY total DESC FETCH FIRST 5 ROWS ONLY.
Previous: Sorting With ORDER BY: Multiple Keys, Expressions, NULLs and Custom Orders

More in SQL Course
Quiz: SQL Dialect Differences (PostgreSQL, MySQL, SQL Server, Oracle, SQLite)
Twenty-four questions on how the major SQL databases differ: limiting rows, concatenation, empty strings, identifier case, upserts, identity columns, transactional DDL, error handling, isolation defaults, booleans, set operations, RETURNING, dates and typing.
Quiz: SQL Delicate Details
Twenty-five questions on SQL's subtle corners: NULLs in aggregates, IN and CHECK, sort order of NULLs, rounding, CHAR padding, window frame defaults, identity gaps, LIKE escapes, empty groups, set operations and multi-column updates.
Quiz: SQL Interview Questions
Thirty SQL questions of the kind asked in developer and analyst interviews: WHERE vs HAVING, DELETE vs TRUNCATE, keys, joins, duplicates, Nth-highest values, window functions, ACID, isolation, locking, indexes, views, procedures and performance.
Quiz: SQL Course Final Exam (All 15 Parts)
The final exam for the SQL course: thirty questions across all fifteen parts, from query processing, NULLs, joins and aggregation through windows, data changes, types, design, indexes, security, transactions, procedural SQL and tuning.
Discussion
Sign in to ask a question or share what you learned.