Skip to the workspace
Pebellslearn by building
Aggregate Queries  ›  Lesson

MIN and MAX — Smallest and Largest

MIN 12 minMIN and MAX return the smallest and largest value in a column of numbers, text or dates, but they return a value rather than the row it belongs to.

sql / MIN and MAX — Smallest and Largest

Explore each scene at your own pace.

01 · The rule

The rule

MIN and MAX — Smallest and Largest

MIN and MAX return the smallest and largest value in a column of numbers, text or dates, but they return a value rather than the row it belongs to.

Separate an extreme value from the full row or rows that contain it.

"What is our cheapest product?" "When was the most recent order?" "Which customer name comes first alphabetically?" These are all the same question in disguise — find the extreme value in a column — and SQL answers them with MIN and MAX.

The rule

MIN and MAX return one extreme value — of numbers, text or dates.

Our products table:

product_id name category price
1 Notebook stationery 60.00
2 Gel pen stationery 25.00
3 Desk lamp home 899.00
4 Stapler stationery 150.00
SELECT MIN(price), MAX(price) FROM products;   -- 25.00, 899.00
SELECT MIN(name) FROM products;                -- 'Desk lamp' (first alphabetically)
SELECT MAX(order_date) FROM orders;            -- the most recent date

Unlike SUM and AVG, MIN and MAX work on anything that can be put in order: numbers by size, text alphabetically, dates by time. Like the other aggregates, they ignore NULLs, and over zero rows they return NULL.

The important limit: MIN and MAX give you the value, not the row it came from. This query looks natural but is wrong:

SELECT name, MAX(price) FROM products;   -- rejected by most databases

MAX collapses four rows into one, so there is no single name to show next to it. PostgreSQL and SQL Server reject it; some settings of MySQL and SQLite accept it and pick a name for you — do not rely on that. To get the whole row, sort and take the first, or compare against the extreme:

SELECT name, price FROM products ORDER BY price DESC LIMIT 1;
SELECT name, price FROM products WHERE price = (SELECT MAX(price) FROM products);

The second form also returns every product tied for the top price.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.