Ranking in SQL: ROW_NUMBER, RANK, DENSE_RANK, NTILE and Top-N per Group
How SQL's ranking window functions number and rank rows: ROW_NUMBER, RANK and DENSE_RANK and how they treat ties, NTILE buckets, PERCENT_RANK and CUME_DIST, top-N per group, keeping ties with FETCH FIRST WITH TIES, removing duplicates, and making rankings deterministic.
kvi5hnuCode Sprout team member11 min readOn this page
"Which product sells best?", "What are the two most expensive products in each category?", "What's each customer's most recent order?" and "Which rows are duplicates?" are all ranking questions. They need each row's position within its group, which a plain aggregate can't give, because it collapses the group.
SQL has a family of ranking window functions for this. They take no arguments, they need an ORDER BY inside OVER to define the ranking order, and they can use PARTITION BY to rank within groups (article 26). The differences between them all come down to one question: what happens when rows tie?
The examples rank products by the number of units sold. A view called units_sold adds up each product's quantities from the order lines, with 0 for the lantern, which has never been ordered:
CREATE VIEW units_sold AS
SELECT p.product_id, p.name, p.category, COALESCE(SUM(oi.qty), 0) AS units
FROM products p
LEFT JOIN order_items oi ON oi.product_id = p.product_id
GROUP BY p.product_id, p.name, p.category;
The socks sold 6 units and the head torch 3. Four products sold exactly 1 unit each, which gives the ties we need.
ROW_NUMBER, RANK and DENSE_RANK
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);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- Units sold per product (0 for products never ordered)
CREATE VIEW units_sold AS
SELECT p.product_id, p.name, p.category, COALESCE(SUM(oi.qty), 0) AS units
FROM products p
LEFT JOIN order_items oi ON oi.product_id = p.product_id
GROUP BY p.product_id, p.name, p.category;
-- Four ways to number the products by units sold
SELECT name,
units,
ROW_NUMBER() OVER (ORDER BY units DESC) AS row_number,
RANK() OVER (ORDER BY units DESC) AS rank,
DENSE_RANK() OVER (ORDER BY units DESC) AS dense_rank,
NTILE(3) OVER (ORDER BY units DESC) AS third
FROM units_sold
ORDER BY units DESC, name;
name | units | row_number | rank | dense_rank | third
-------------------+-------+------------+------+------------+-------
Merino socks | 6 | 1 | 1 | 1 | 1
Glow head torch | 3 | 2 | 2 | 2 | 1
Day 18 backpack | 1 | 6 | 3 | 3 | 3
Ridge 2 tent | 1 | 4 | 3 | 3 | 2
Summit 4 tent | 1 | 5 | 3 | 3 | 2
Trail 30 backpack | 1 | 3 | 3 | 3 | 1
Basecamp lantern | 0 | 7 | 7 | 4 | 3
(7 rows)
All three ranking functions agree on the first two rows. They differ on the four products tied at 1 unit:
ROW_NUMBER()gives every row a different number, 1 to 7, even tied rows. Which of the tied products gets 3, 4, 5 or 6 is arbitrary: here the database happened to number the Trail 30 backpack first. Run the same query on another database, or after the data changes, and the order among ties may differ.RANK()gives tied rows the same rank, 3, and then skips ranks: the next product is ranked 7, because six products come before it. It's the "Olympic" ranking: two gold medals mean no silver.DENSE_RANK()also gives the ties 3, but the next rank is 4, with no gap. It ranks the distinct values rather than the rows.

How to choose:
| Question | Function |
|---|---|
| "Exactly one row per position, e.g. one row per customer" | ROW_NUMBER() with a unique tie-breaker |
| "Competition ranking: ties share a place, places after them are skipped" | RANK() |
| "The Nth highest value" | DENSE_RANK() |
DENSE_RANK is the right tool for "find the second-highest price": rank 2 is the second distinct price, however many products share the top price. With RANK, if two products tie for first, no product has rank 2.
NTILE: splitting rows into buckets
NTILE(n) divides the ordered rows into n groups of as nearly equal size as possible and returns the group number. With 7 rows and 3 buckets, the sizes are 3, 2 and 2: when the rows don't divide evenly, the first buckets get one extra row each. NTILE(4) gives quartiles and NTILE(100) percentiles.
NTILE works on row positions, not values, so tied rows can end up in different buckets. In the result, the four products with 1 unit are split across buckets 1, 2 and 3. If equal values must share a bucket, compute buckets from the values instead, for example with CASE or WIDTH_BUCKET (article 46).
PERCENT_RANK and CUME_DIST
Two more functions give a row's relative position, as a fraction between 0 and 1:
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);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- Units sold per product (0 for products never ordered)
CREATE VIEW units_sold AS
SELECT p.product_id, p.name, p.category, COALESCE(SUM(oi.qty), 0) AS units
FROM products p
LEFT JOIN order_items oi ON oi.product_id = p.product_id
GROUP BY p.product_id, p.name, p.category;
-- Relative position: PERCENT_RANK and CUME_DIST
SELECT name,
units,
ROUND(PERCENT_RANK() OVER (ORDER BY units)::numeric, 3) AS pct_rank,
ROUND(CUME_DIST() OVER (ORDER BY units)::numeric, 3) AS cume_dist
FROM units_sold
ORDER BY units, name;
name | units | pct_rank | cume_dist
-------------------+-------+----------+-----------
Basecamp lantern | 0 | 0.000 | 0.143
Day 18 backpack | 1 | 0.167 | 0.714
Ridge 2 tent | 1 | 0.167 | 0.714
Summit 4 tent | 1 | 0.167 | 0.714
Trail 30 backpack | 1 | 0.167 | 0.714
Glow head torch | 3 | 0.833 | 0.857
Merino socks | 6 | 1.000 | 1.000
(7 rows)
PERCENT_RANK()is(rank - 1) / (rows - 1): the fraction of the other rows that rank below this one. The lowest row gets 0 and the highest 1. The four products with 1 unit have rank 2, so they get (2 - 1) / (7 - 1) = 0.167.CUME_DIST()is "the fraction of rows with a value less than or equal to this one". The four products with 1 unit and the lantern are 5 of the 7 rows, so they get 5 / 7 = 0.714. It's never 0: the lowest row counts itself.
Use CUME_DIST to answer "this product sells at least as well as what fraction of products?", and PERCENT_RANK for a 0-to-1 rank score. Both return floating-point numbers in PostgreSQL, so the query casts them to numeric to round them.
Top-N per group
The most common use of ranking is top-N per group: the most expensive product in each category, each customer's latest order, the three best-selling products per month. The pattern has two steps, because window functions can't be used in WHERE (article 26):
- Rank the rows within each group in a derived table or CTE.
- Filter on the rank in the outer query.
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);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- Top product per category by price (ROW_NUMBER), and the top 2
SELECT category, name, price
FROM (SELECT category, name, price,
ROW_NUMBER() OVER (PARTITION BY category ORDER BY price DESC) AS rn
FROM products) AS ranked
WHERE rn = 1
ORDER BY category;
SELECT category, name, price, rn
FROM (SELECT category, name, price,
ROW_NUMBER() OVER (PARTITION BY category ORDER BY price DESC) AS rn
FROM products) AS ranked
WHERE rn <= 2
ORDER BY category, rn;
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)
category | name | price | rn
----------+-------------------+--------+----
clothing | Merino socks | 16.00 | 1
lighting | Glow head torch | 34.50 | 1
lighting | Basecamp lantern | 27.00 | 2
packs | Trail 30 backpack | 89.95 | 1
packs | Day 18 backpack | 54.00 | 2
tents | Summit 4 tent | 489.00 | 1
tents | Ridge 2 tent | 249.99 | 2
(7 rows)
PARTITION BY category restarts the numbering in each category, and ORDER BY price DESC puts the most expensive product first. rn = 1 keeps one product per category, and rn <= 2 keeps two. The second query keeps every product, because each category has exactly two products, except clothing, which has one.
Article 23 solved the same problem with LATERAL. The window version is often simpler. LATERAL can be faster when an index lets each lookup stop after N rows and the groups are large.
Which ranking function for top-N?
With ROW_NUMBER, rn <= N returns exactly N rows per group, or fewer if the group is smaller, breaking ties arbitrarily. With RANK or DENSE_RANK, it returns every row tied at the boundary, so a group can return more than N rows:
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);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- Units sold per product (0 for products never ordered)
CREATE VIEW units_sold AS
SELECT p.product_id, p.name, p.category, COALESCE(SUM(oi.qty), 0) AS units
FROM products p
LEFT JOIN order_items oi ON oi.product_id = p.product_id
GROUP BY p.product_id, p.name, p.category;
-- Ties: the best-selling products per category, keeping ties with RANK
SELECT category, name, units, rnk
FROM (SELECT category, name, units,
RANK() OVER (PARTITION BY category ORDER BY units DESC) AS rnk
FROM units_sold) AS ranked
WHERE rnk = 1
ORDER BY category, name;
-- Top 3 overall, plus anything tied with third place
SELECT name, units
FROM units_sold
ORDER BY units DESC
FETCH FIRST 3 ROWS WITH TIES;
category | name | units | rnk
----------+-------------------+-------+-----
clothing | Merino socks | 6 | 1
lighting | Glow head torch | 3 | 1
packs | Day 18 backpack | 1 | 1
packs | Trail 30 backpack | 1 | 1
tents | Ridge 2 tent | 1 | 1
tents | Summit 4 tent | 1 | 1
(6 rows)
name | units
-------------------+-------
Merino socks | 6
Glow head torch | 3
Trail 30 backpack | 1
Ridge 2 tent | 1
Summit 4 tent | 1
Day 18 backpack | 1
(6 rows)
The first query asks for the best-selling product in each category. With RANK, both packs and both tents tie at 1 unit, so each of those categories returns two rows. With ROW_NUMBER, each category would return one arbitrary winner, and the result could change from run to run. Which is right depends on the question: "the winner" needs a tie-breaker, and "all the winners" needs RANK.
The second query shows a shortcut for the overall top N with ties: FETCH FIRST 3 ROWS WITH TIES returns the first three rows by units, plus every row that ties with the third. Because four products tie for third place at 1 unit, it returns six rows. It requires an ORDER BY. WITH TIES is supported by PostgreSQL 13+, Oracle 12c+, and SQL Server (as TOP (3) WITH TIES), but not MySQL. It doesn't work per group: use RANK for that.
Removing duplicates and picking one row per key
ROW_NUMBER is the standard tool for "keep one row per key": the latest order per customer, the newest version of each record, or one row from each set of duplicates.
\pset null '(null)'
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);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- Removing duplicates: keep each customer's most recent order only
SELECT customer_id, order_id, placed_on
FROM (SELECT customer_id, order_id, placed_on,
ROW_NUMBER() OVER (PARTITION BY customer_id
ORDER BY placed_on DESC, order_id DESC) AS rn
FROM orders
WHERE customer_id IS NOT NULL) AS latest
WHERE rn = 1
ORDER BY customer_id;
-- NULLs in the ORDER BY of a window: put them last explicitly
SELECT name, brand,
RANK() OVER (ORDER BY brand NULLS LAST) AS brand_rank
FROM products
ORDER BY brand_rank, name;
customer_id | order_id | placed_on
-------------+----------+------------
1 | 103 | 2026-03-09
2 | 102 | 2026-03-05
3 | 104 | 2026-03-15
4 | 105 | 2026-03-20
(4 rows)
name | brand | brand_rank
-------------------+---------+------------
Ridge 2 tent | Alpina | 1
Summit 4 tent | Alpina | 1
Day 18 backpack | Kestrel | 3
Trail 30 backpack | Kestrel | 3
Glow head torch | Lumen | 5
Merino socks | Woolly | 6
Basecamp lantern | (null) | 7
(7 rows)
The first query numbers each customer's orders from newest to oldest and keeps number 1. The ORDER BY placed_on DESC, order_id DESC includes a tie-breaker: if a customer placed two orders on the same day, the higher order ID wins, every time. Without it, the database could pick either.
The same pattern deletes duplicates. Number the rows within each set of duplicates, and delete every row whose number is greater than 1. Article 33 shows the full DELETE statement.
NULLs in the ranking order
The second query ranks products by brand. Ranking functions sort NULLs the same way ORDER BY does (article 9): last in ascending order in PostgreSQL and Oracle, first in MySQL, SQL Server and SQLite. Writing NULLS LAST or NULLS FIRST makes it explicit in the databases that support it. Here the lantern, with no brand, ranks last. Note the RANK gaps again: two Alpina products share rank 1, so Kestrel starts at 3.
Making rankings deterministic
A ranking is deterministic when the same data always gives the same numbers. RANK, DENSE_RANK, PERCENT_RANK and CUME_DIST always are, because tied rows get the same value. ROW_NUMBER and NTILE aren't, unless the ORDER BY inside OVER is unique.
Non-deterministic numbering causes real bugs:
- A report shows a different "top product" each time it runs.
- Pagination with
ROW_NUMBER() ... WHERE rn BETWEEN 11 AND 20shows a row on two pages, or on none. - A deduplication keeps a different row in test and in production.
The fix is always the same: add columns to the window's ORDER BY until it's unique, ending with the primary key if necessary.
Ranking in other databases
The functions in this article are standard, and their names and behaviour are the same in PostgreSQL, MySQL 8.0+, SQL Server, Oracle, SQLite 3.25+ and MariaDB 10.2+. Two differences to know:
- SQL Server returns
bigintfromROW_NUMBER,RANK,DENSE_RANKandNTILE, andfloatfromPERCENT_RANKandCUME_DIST. - Oracle has the older
ROWNUMpseudocolumn, which numbers rows beforeORDER BYis applied, a classic source of wrong "top N" queries. UseROW_NUMBER()orFETCH FIRSTinstead.
What's current
FETCH FIRST n ROWS WITH TIESarrived in PostgreSQL 13 and is in Oracle since 12c. MySQL still has noWITH TIES.- Snowflake, BigQuery, DuckDB, Databricks and Oracle AI Database 26ai support
QUALIFY, which filters on a ranking directly, as inQUALIFY ROW_NUMBER() OVER (PARTITION BY category ORDER BY price DESC) = 1. PostgreSQL, MySQL, SQL Server and older Oracle versions still need the derived-table pattern. - PostgreSQL 15 can stop computing a ranking early when the outer query filters on it, as in
WHERE rn <= 3, which makes top-N queries faster on large partitions.
Common questions
What's the difference between RANK and DENSE_RANK?
Both give tied rows the same rank. After a tie, RANK skips as many ranks as there were tied rows, while DENSE_RANK continues with the next integer.
Why does ROW_NUMBER give different results each time?
The ORDER BY inside OVER isn't unique, so tied rows are numbered in an arbitrary order. Add a tie-breaker, such as the primary key.
How do I get the second-highest value?
DENSE_RANK() OVER (ORDER BY value DESC) and keep rank 2. It handles ties at the top correctly.
Can I use a ranking function without ORDER BY in OVER?
PostgreSQL allows ROW_NUMBER() OVER (), numbering rows in an arbitrary order. RANK without ORDER BY gives every row 1, because all rows are peers. SQL Server and Oracle require ORDER BY for ranking functions.
How do I filter on a rank?
Compute it in a derived table or CTE and filter in the outer query. WHERE ROW_NUMBER() OVER (...) = 1 is an error.
How does NTILE handle uneven sizes?
The first rows mod n buckets get one extra row each. 7 rows in 3 buckets gives 3, 2 and 2.
Should I use ROW_NUMBER or LIMIT/FETCH FIRST for top N?
LIMIT or FETCH FIRST for the top N overall. ROW_NUMBER with PARTITION BY for the top N per group.
Summary
ROW_NUMBERnumbers rows uniquely,RANKshares ranks among ties and leaves gaps, andDENSE_RANKshares ranks without gaps.NTILE(n)splits rows into n nearly equal buckets by position.PERCENT_RANKandCUME_DISTgive relative positions between 0 and 1.- Top-N per group: rank with
PARTITION BYin a derived table or CTE, then filter on the rank. ROW_NUMBERreturns exactly N rows per group.RANKandDENSE_RANKinclude ties at the boundary.FETCH FIRST ... WITH TIESkeeps ties for the overall top N.ROW_NUMBERwith a uniqueORDER BYpicks one row per key, which is how you find the latest record or remove duplicates.- Add a unique tie-breaker to make
ROW_NUMBERandNTILEdeterministic.
Practice questions
Prices are 50, 40, 40 and 30. What do ROW_NUMBER, RANK and DENSE_RANK return for each, ordered by price descending?
Answer
ROW_NUMBER: 1, 2, 3, 4 (the two 40s get 2 and 3 in an arbitrary order). RANK: 1, 2, 2, 4. DENSE_RANK: 1, 2, 2, 3.
Write a query that returns the second-highest product price, even if several products share the highest price.
Answer
SELECT DISTINCT price
FROM (SELECT price, DENSE_RANK() OVER (ORDER BY price DESC) AS dr
FROM products) AS ranked
WHERE dr = 2;
It returns 249.99. DISTINCT returns one row even if several products share the second price. With RANK, a tie for the top price would leave no row with rank 2.
Write a query that returns each customer's first order (by date), with the order ID, using a window function. Make it deterministic.
Answer
SELECT customer_id, order_id, placed_on
FROM (SELECT customer_id, order_id, placed_on,
ROW_NUMBER() OVER (PARTITION BY customer_id
ORDER BY placed_on, order_id) AS rn
FROM orders
WHERE customer_id IS NOT NULL) AS t
WHERE rn = 1
ORDER BY customer_id;
order_id breaks ties between orders placed on the same day. The result is orders 101, 102, 104 and 105.
A query uses RANK() OVER (PARTITION BY category ORDER BY units DESC) and keeps rank <= 1 to list "the best-selling product per category". Why does it return two rows for some categories, and what are the options?
Answer
Products tied for the most units in a category share rank 1, so both are returned. If that's what you want ("all the best sellers"), keep RANK. If you need exactly one row per category, use ROW_NUMBER() and add a tie-breaker to the ORDER BY, such as units DESC, price DESC, product_id, so the choice is predictable.
What does NTILE(4) OVER (ORDER BY price) return for 10 products?
Answer
Bucket sizes of 3, 3, 2 and 2: 10 rows don't divide evenly by 4, so the first 10 mod 4 = 2 buckets get one extra row. The three cheapest products get 1, the next three 2, then two products get 3 and the two most expensive get 4.
Previous: SQL Window Functions: OVER, PARTITION BY and ORDER BY
Next: Window Frames: Running Totals and Moving Averages With ROWS, RANGE and GROUPS

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.