Advanced Searching in SQL: Top-N, Extremes, Skipping Rows and Previous Values
Search patterns in SQL: the row holding a maximum per group four ways and how they treat ties, the nth highest value, the cheapest and dearest in one row, GREATEST and LEAST, as-of lookups in a history table, nearest values, and skipping rows.
kvi5hnuCode Sprout team member10 min readOn this page
Many questions ask for particular rows rather than totals: the most expensive product in each category, the second-highest price, the price that was in force on the day of an order, the product closest to a budget. They look simple, but each has several solutions that behave differently with ties, NULLs and missing data.
Article 27 introduced ranking and top-N per group with window functions. This article builds on it with the other classic search problems, and compares the approaches. The examples add a second lighting product, a Camp lantern at 34.50, the same price as the Glow head torch, so that the ties are visible.
The row with the maximum, per group
"The most expensive product in each category" is the most common search problem in SQL, and there are four standard ways to write it:
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);
-- A second lighting product at the same price as the head torch, to create a tie
INSERT INTO products VALUES (8, 'Camp lantern', 'lighting', 'Lumen', 34.50, 9, 300);
-- The most expensive product in each category: four ways, compared on a tie
-- 1. Window function: RANK keeps ties
SELECT category, name, price
FROM (SELECT category, name, price,
RANK() OVER (PARTITION BY category ORDER BY price DESC) AS rnk
FROM products) AS ranked
WHERE rnk = 1
ORDER BY category, name;
-- 2. Correlated subquery: equal to the category's maximum
SELECT category, name, price
FROM products p
WHERE price = (SELECT MAX(price) FROM products WHERE category = p.category)
ORDER BY category, name;
-- 3. NOT EXISTS: no product in the same category costs more
SELECT category, name, price
FROM products p
WHERE NOT EXISTS (SELECT 1 FROM products q
WHERE q.category = p.category AND q.price > p.price)
ORDER BY category, name;
-- 4. DISTINCT ON: exactly one row per category; the tie is broken by name
SELECT DISTINCT ON (category) category, name, price
FROM products
ORDER BY category, price DESC, name;
category | name | price
----------+-------------------+--------
clothing | Merino socks | 16.00
lighting | Camp lantern | 34.50
lighting | Glow head torch | 34.50
packs | Trail 30 backpack | 89.95
tents | Summit 4 tent | 489.00
(5 rows)
category | name | price
----------+-------------------+--------
clothing | Merino socks | 16.00
lighting | Camp lantern | 34.50
lighting | Glow head torch | 34.50
packs | Trail 30 backpack | 89.95
tents | Summit 4 tent | 489.00
(5 rows)
category | name | price
----------+-------------------+--------
clothing | Merino socks | 16.00
lighting | Camp lantern | 34.50
lighting | Glow head torch | 34.50
packs | Trail 30 backpack | 89.95
tents | Summit 4 tent | 489.00
(5 rows)
category | name | price
----------+-------------------+--------
clothing | Merino socks | 16.00
lighting | Camp lantern | 34.50
packs | Trail 30 backpack | 89.95
tents | Summit 4 tent | 489.00
(4 rows)
- Window function: rank each product within its category, then keep rank 1.
RANKgives tied rows the same rank, so both lighting products are returned. - Correlated subquery: keep products whose price equals their category's maximum. Ties are kept.
NOT EXISTS: keep products for which no product in the same category costs more. This "no better row exists" form is the oldest pattern and works everywhere. Ties are kept.DISTINCT ON(article 10): sort each category by price and keep its first row. Exactly one row per category is returned, and thenamein theORDER BYdecides which of the tied products wins.
The first three return the same 5 rows. The fourth returns 4. Neither answer is wrong. Decide whether the question means "every product sharing the top price" or "one product per category", then pick the method that matches. With ROW_NUMBER instead of RANK in method 1, it also returns exactly one row, with a tiebreaker in its ORDER BY.
A mistake to avoid: SELECT category, name, MAX(price) FROM products GROUP BY category isn't valid, because name isn't grouped (article 19). MySQL with ONLY_FULL_GROUP_BY turned off accepts it and returns the name of an arbitrary row of the group, not necessarily the most expensive.
For performance, the window and DISTINCT ON forms read the table once. The correlated forms run a lookup per row, which is fast with an index on (category, price) and slow without one.
The nth highest value
"What's the second-highest price?" is an interview classic:
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);
-- A second lighting product at the same price as the head torch, to create a tie
INSERT INTO products VALUES (8, 'Camp lantern', 'lighting', 'Lumen', 34.50, 9, 300);
\pset null '(null)'
-- The second-highest price: three ways
SELECT (SELECT DISTINCT price FROM products
ORDER BY price DESC OFFSET 1 ROWS FETCH FIRST 1 ROW ONLY) AS with_offset,
(SELECT MAX(price) FROM products
WHERE price < (SELECT MAX(price) FROM products)) AS with_max_below_max,
(SELECT DISTINCT price
FROM (SELECT price, DENSE_RANK() OVER (ORDER BY price DESC) AS dr FROM products) AS r
WHERE dr = 2) AS with_dense_rank;
-- The second-highest price in each category; NULL where there's only one product
SELECT c.category,
(SELECT DISTINCT price FROM products p
WHERE p.category = c.category
ORDER BY price DESC OFFSET 1 ROWS FETCH FIRST 1 ROW ONLY) AS second_price
FROM (SELECT DISTINCT category FROM products) AS c
ORDER BY c.category;
with_offset | with_max_below_max | with_dense_rank
-------------+--------------------+-----------------
249.99 | 249.99 | 249.99
(1 row)
category | second_price
----------+--------------
clothing | (null)
lighting | 27.00
packs | 54.00
tents | 249.99
(4 rows)
DISTINCT+OFFSET: sort the distinct prices, skip one, take one.DISTINCTmatters: without it, a tie for the highest price would make the "second" row the same value.MAXbelow theMAX: the largest price smaller than the largest. It only works for the second value.DENSE_RANK: gives equal prices the same rank, with no gaps (article 27), so rank 2 is the second-highest distinct price.DISTINCTreturns it once, even if several products share it. This generalises to any n.
As a scalar subquery, each form returns NULL when there's no such value, rather than no row, which is usually what a report wants. The per-category query shows this: clothing has one product, so it has no second price. The lighting category's prices are 34.50, 34.50 and 27.00, and the second distinct price is 27.00.
Cheapest and dearest in one row
To show each category's cheapest and dearest products side by side, the row-picking methods above need two passes. Two other methods do it in one:
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);
-- A second lighting product at the same price as the head torch, to create a tie
INSERT INTO products VALUES (8, 'Camp lantern', 'lighting', 'Lumen', 34.50, 9, 300);
\pset null '(null)'
-- The cheapest and the dearest product of each category, side by side in one row
SELECT DISTINCT category,
FIRST_VALUE(name) OVER w AS cheapest,
MIN(price) OVER (PARTITION BY category) AS min_price,
FIRST_VALUE(name) OVER (PARTITION BY category ORDER BY price DESC, name) AS dearest,
MAX(price) OVER (PARTITION BY category) AS max_price
FROM products
WINDOW w AS (PARTITION BY category ORDER BY price, name)
ORDER BY category;
-- The same with ordered array aggregates: take element [1] of a sorted array
SELECT category,
(array_agg(name ORDER BY price, name))[1] AS cheapest,
(array_agg(name ORDER BY price DESC, name))[1] AS dearest
FROM products
GROUP BY category
ORDER BY category;
-- GREATEST and LEAST compare values across columns within one row
SELECT name, stock, weight_g,
GREATEST(stock, weight_g) AS greatest_value,
LEAST(stock, weight_g) AS least_value
FROM products
WHERE product_id IN (3, 4, 7);
category | cheapest | min_price | dearest | max_price
----------+------------------+-----------+-------------------+-----------
clothing | Merino socks | 16.00 | Merino socks | 16.00
lighting | Basecamp lantern | 27.00 | Camp lantern | 34.50
packs | Day 18 backpack | 54.00 | Trail 30 backpack | 89.95
tents | Ridge 2 tent | 249.99 | Summit 4 tent | 489.00
(4 rows)
category | cheapest | dearest
----------+------------------+-------------------
clothing | Merino socks | Merino socks
lighting | Basecamp lantern | Camp lantern
packs | Day 18 backpack | Trail 30 backpack
tents | Ridge 2 tent | Summit 4 tent
(4 rows)
name | stock | weight_g | greatest_value | least_value
------------------+-------+----------+----------------+-------------
Glow head torch | 40 | 90 | 90 | 40
Basecamp lantern | 15 | (null) | 15 | 15
Merino socks | 75 | 80 | 80 | 75
(3 rows)
FIRST_VALUE(article 29) over each category, once sorted ascending and once descending, gives the names, and theDISTINCTcollapses the identical rows of each category into one. TheWINDOWclause names a window definition for reuse.array_agg(name ORDER BY price)collects the names in price order, and[1]takes the first. This is a compact PostgreSQL idiom for "the value of one column from the row with the smallest value of another". DuckDB and ClickHouse have this directly asarg_min(name, price)andarg_max. In Oracle, it'sMIN(name) KEEP (DENSE_RANK FIRST ORDER BY price).
GREATEST and LEAST are different: they compare several values in one row, not values across rows. GREATEST(stock, weight_g) is the larger of the two columns. They handle NULLs differently between databases: PostgreSQL ignores NULL arguments, so the lantern's result is its stock, 15, but MySQL and Oracle return NULL if any argument is NULL. Use COALESCE on the arguments for portable results. SQL Server added GREATEST and LEAST in 2022, ignoring NULLs like PostgreSQL. SQLite uses multi-argument max() and min(), which return NULL if any argument is NULL.
As-of lookups: the value in force at a time
Many tables store history: prices, exchange rates, tax rates, addresses, each with the date it became valid. "What was the price on the day of the order?" means: the latest history row on or before that date.
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);
-- Price history: each row is valid from its date until the next row for the same product
CREATE TABLE price_history (
product_id INTEGER,
valid_from DATE,
price DECIMAL(8, 2),
PRIMARY KEY (product_id, valid_from)
);
INSERT INTO price_history VALUES
(7, DATE '2026-01-01', 16.00),
(7, DATE '2026-03-08', 15.00), -- a sale
(7, DATE '2026-03-20', 16.00),
(3, DATE '2026-01-01', 34.50),
(1, DATE '2026-01-01', 239.99),
(1, DATE '2026-03-01', 249.99);
-- The price in force on each order date: the latest history row on or before it
SELECT oi.order_id, o.placed_on, p.name, oi.unit_price,
ph.price AS list_price_then,
oi.unit_price = ph.price AS matches
FROM order_items oi
JOIN orders o ON o.order_id = oi.order_id
JOIN products p ON p.product_id = oi.product_id
CROSS JOIN LATERAL (SELECT h.price
FROM price_history h
WHERE h.product_id = oi.product_id
AND h.valid_from <= o.placed_on
ORDER BY h.valid_from DESC
FETCH FIRST 1 ROW ONLY) AS ph
ORDER BY o.placed_on, p.name;
-- Turning the history into explicit ranges with LEAD
SELECT product_id, valid_from,
LEAD(valid_from) OVER (PARTITION BY product_id ORDER BY valid_from) AS valid_to,
price
FROM price_history
WHERE product_id = 7
ORDER BY valid_from;
order_id | placed_on | name | unit_price | list_price_then | matches
----------+------------+-----------------+------------+-----------------+---------
101 | 2026-03-02 | Merino socks | 16.00 | 16.00 | t
101 | 2026-03-02 | Ridge 2 tent | 249.99 | 249.99 | t
102 | 2026-03-05 | Glow head torch | 34.50 | 34.50 | t
103 | 2026-03-09 | Glow head torch | 34.50 | 34.50 | t
103 | 2026-03-09 | Merino socks | 15.00 | 15.00 | t
106 | 2026-03-22 | Merino socks | 16.00 | 16.00 | t
(6 rows)
product_id | valid_from | valid_to | price
------------+------------+------------+-------
7 | 2026-01-01 | 2026-03-08 | 16.00
7 | 2026-03-08 | 2026-03-20 | 15.00
7 | 2026-03-20 | | 16.00
(3 rows)

The lateral subquery (article 23) does exactly that for each order line: filter the product's history rows to those valid on or before the order date, sort the newest first, and take one. Every order paid the list price of its day: order 103 got the socks at the sale price of 15.00.
CROSS JOIN LATERAL drops order lines without a matching history row: the Trail 30 backpack in order 103, the tent in order 104 and the backpack in order 105 have no history here, so those three lines are missing. To keep them with a NULL price, write LEFT JOIN LATERAL (...) AS ph ON true.
The second query converts the history into explicit ranges, from valid_from to the next row's valid_from, using LEAD (article 29). The last range has no end, NULL, meaning "still valid". With ranges, the lookup becomes a plain join, placed_on >= valid_from AND (placed_on < valid_to OR valid_to IS NULL), which is how many data warehouses store history (as slowly changing dimensions).
An index on (product_id, valid_from) makes the lateral lookup a quick index probe. The primary key here provides it.
The nearest value
"Which product's price is closest to a budget of 50?" sorts by the distance:
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);
-- A second lighting product at the same price as the head torch, to create a tie
INSERT INTO products VALUES (8, 'Camp lantern', 'lighting', 'Lumen', 34.50, 9, 300);
-- The product whose price is closest to a budget of 50
SELECT name, price, ABS(price - 50) AS distance
FROM products
ORDER BY ABS(price - 50), name
FETCH FIRST 1 ROW ONLY;
-- Every product's nearest neighbour in price within its category
SELECT p.name, p.price, n.name AS nearest, n.price AS nearest_price
FROM products p
CROSS JOIN LATERAL (SELECT q.name, q.price
FROM products q
WHERE q.category = p.category AND q.product_id <> p.product_id
ORDER BY ABS(q.price - p.price), q.name
FETCH FIRST 1 ROW ONLY) AS n
ORDER BY p.category, p.price;
name | price | distance
-----------------+-------+----------
Day 18 backpack | 54.00 | 4.00
(1 row)
name | price | nearest | nearest_price
-------------------+--------+-------------------+---------------
Basecamp lantern | 27.00 | Camp lantern | 34.50
Glow head torch | 34.50 | Camp lantern | 34.50
Camp lantern | 34.50 | Glow head torch | 34.50
Day 18 backpack | 54.00 | Trail 30 backpack | 89.95
Trail 30 backpack | 89.95 | Day 18 backpack | 54.00
Ridge 2 tent | 249.99 | Summit 4 tent | 489.00
Summit 4 tent | 489.00 | Ridge 2 tent | 249.99
(7 rows)
ORDER BY ABS(price - 50) puts the smallest distance first: the Day 18 backpack, 4.00 away. The second query finds each product's nearest neighbour within its category with a lateral subquery, excluding the product itself. The tiebreaker on name matters again: the Basecamp lantern is 7.50 away from both other lighting products.
Sorting by a calculation reads every candidate row. For large tables, find the nearest value above and the nearest below separately, each with an indexed ORDER BY price and FETCH FIRST 1 ROW ONLY, and take the closer one. PostgreSQL's GiST indexes, as used by the btree_gist extension and PostGIS, can also find nearest neighbours directly with the <-> distance operator.
Skipping 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);
-- A second lighting product at the same price as the head torch, to create a tie
INSERT INTO products VALUES (8, 'Camp lantern', 'lighting', 'Lumen', 34.50, 9, 300);
-- Every second row, and skipping the first row of each group
SELECT name, price
FROM (SELECT name, price, ROW_NUMBER() OVER (ORDER BY price, name) AS rn FROM products) AS t
WHERE rn % 2 = 1
ORDER BY price, name;
-- Each category without its single most expensive product
SELECT category, name, price
FROM (SELECT category, name, price,
ROW_NUMBER() OVER (PARTITION BY category ORDER BY price DESC, name) AS rn
FROM products) AS t
WHERE rn > 1
ORDER BY category, price DESC;
name | price
-----------------+--------
Merino socks | 16.00
Camp lantern | 34.50
Day 18 backpack | 54.00
Ridge 2 tent | 249.99
(4 rows)
category | name | price
----------+------------------+--------
lighting | Glow head torch | 34.50
lighting | Basecamp lantern | 27.00
packs | Day 18 backpack | 54.00
tents | Ridge 2 tent | 249.99
(4 rows)
Numbering rows with ROW_NUMBER makes position-based selection easy:
- Every nth row:
WHERE rn % n = 1keeps rows 1, n + 1, 2n + 1, and so on, for example to thin out a large time series for a chart. A unique tiebreaker in the window'sORDER BY, herename, makes the result repeatable. - All but the first row per group:
WHERE rn > 1drops each category's most expensive product. The same pattern removes duplicates (article 33), keeping one row per key.
What's current
- SQL Server 2022 added
GREATESTandLEAST, which PostgreSQL has long had. DuckDB hasarg_minandarg_maxfor "the value from the row with the smallest or largest". PostgreSQL 17 has no equivalent, wherearray_agg(... ORDER BY ...)[1]andDISTINCT ONfill the gap. - PostgreSQL 13 added
FETCH FIRST ... WITH TIES, which returns a top-N list including rows tied with the last one (article 10). - SQL added temporal tables (
PERIOD FOR,FOR SYSTEM_TIME AS OF), which make as-of queries part of the language. SQL Server, MariaDB and Oracle support system-versioned tables. PostgreSQL 18 added temporalPRIMARY KEYandUNIQUEconstraints withWITHOUT OVERLAPS.
Common questions
How do I get the whole row with the maximum value in each group?
Rank within each group and keep rank 1, use a correlated subquery comparing with MAX, or use NOT EXISTS for a greater row. DISTINCT ON in PostgreSQL returns exactly one row per group.
Why does my query return two rows for one category?
Two rows tie for the maximum. Methods based on RANK, MAX and NOT EXISTS keep ties. Use ROW_NUMBER or DISTINCT ON with a tiebreaker to get exactly one.
How do I find the second-highest value?
SELECT DISTINCT value ... ORDER BY value DESC OFFSET 1 ROWS FETCH FIRST 1 ROW ONLY, or DENSE_RANK() = 2.
How do I find the value valid on a given date?
Take the latest history row with a start date on or before it: WHERE valid_from <= d ORDER BY valid_from DESC FETCH FIRST 1 ROW ONLY, as a lateral subquery for many dates.
Does GREATEST ignore NULLs?
In PostgreSQL and SQL Server, yes. In MySQL and Oracle, any NULL argument makes the result NULL.
Summary
- The row holding a group's maximum can be found with
RANK, a correlatedMAX,NOT EXISTSorDISTINCT ON. The first three keep ties, andDISTINCT ONandROW_NUMBERreturn one row. - The nth highest value comes from
DISTINCTwithOFFSET, orDENSE_RANK. Scalar subqueries return NULL when there's none. FIRST_VALUEandarray_agg(... ORDER BY ...)[1]put the cheapest and dearest in one row.GREATESTandLEASTcompare columns within a row, and their NULL handling differs between databases.- As-of lookups take the latest history row on or before a date, with
LATERALandFETCH FIRST 1 ROW ONLY, or join to ranges built withLEAD. - Sort by
ABS(value - target)to find the nearest value. ROW_NUMBERwith%or>selects every nth row or skips the first rows of each group.
Practice questions
Using NOT EXISTS, write a query that returns the cheapest product in each category, keeping ties.
Answer
SELECT category, name, price
FROM products p
WHERE NOT EXISTS (SELECT 1 FROM products q
WHERE q.category = p.category AND q.price < p.price)
ORDER BY category;
Merino socks, Basecamp lantern, Day 18 backpack and Ridge 2 tent.
What does this return, and why is DISTINCT needed?
SELECT DISTINCT price FROM products
WHERE category = 'lighting'
ORDER BY price DESC
OFFSET 1 ROWS FETCH FIRST 1 ROW ONLY;
Answer
27.00. The lighting prices are 34.50, 34.50 and 27.00. Without DISTINCT, skipping one row would land on the second 34.50, and the query would return the highest price again instead of the second-highest.
What do GREATEST(5, NULL, 3) in PostgreSQL and GREATEST(5, NULL, 3) in MySQL return?
Answer
5 in PostgreSQL, which ignores NULL arguments, and NULL in MySQL, where any NULL argument makes the result NULL.
Write a query that returns the price of the Ridge 2 tent (product 1) on 15 February 2026 from price_history.
Answer
SELECT price
FROM price_history
WHERE product_id = 1 AND valid_from <= DATE '2026-02-15'
ORDER BY valid_from DESC
FETCH FIRST 1 ROW ONLY;
239.99, from the row valid from 1 January. The 249.99 price only starts on 1 March.
In the as-of query, why do orders 104 and 105 disappear, and how do you keep them?
Answer
Their products have no rows in price_history, so the lateral subquery returns no row, and CROSS JOIN LATERAL drops the order line, like an inner join. LEFT JOIN LATERAL (...) AS ph ON true keeps them, with a NULL price.
Previous: SQL Reporting Techniques: Buckets, Histograms, Shares and Running Percentages

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.