Thuta Learning
SQL
AdvancedData & DatabasesBeginner

MIN() & MAX()

SQLLesson 1520 min

What you'll walk away with

  • Use MIN() / MAX() on number, date and text columns and explain why the result is a single row
  • Predict that NULLs are skipped and that no matching rows gives NULL, and handle it with COALESCE
  • Explain why SELECT name, MAX(price) fails and fetch the extreme row with a subquery or ORDER BY ... LIMIT
  • Tell column-wise MAX() apart from row-wise GREATEST()

Explain it simply

Explain it simply

Imagine holding a sheet of exam scores. If someone asks "what is the lowest score and what is the highest?", you read the whole list from top to bottom and answer with one number each. MIN() and MAX() do exactly that inside the database: they read many rows and hand back a single value.

The cheapest product, the earliest order date, the most recent login time: all of these are MIN/MAX questions. They are not limited to numbers; dates and text work too, because any value that can be put in order has a smallest and a largest.

Problem → Why → Solution

The problem: you want the name of the priciest product

For a shop dashboard you want to show "which product is the most expensive". It feels natural to put name and MAX(price) side by side. PostgreSQL refuses to run the query below and reports an error instead.

There is a quieter cousin of this bug: ORDER BY price DESC LIMIT 1 runs without an error, but returns Pencil Case, whose price is still NULL. PostgreSQL sorts NULL as larger than every real value, so in DESC order it comes first.

priciest.sql
-- Attempt 1: mixing a plain column with an aggregate
SELECT name, MAX(price)
FROM products;
-- ERROR: column "products.name" must appear in the GROUP BY clause
--        or be used in an aggregate function

-- Attempt 2: runs, but returns the product whose price is NULL
SELECT name, price
FROM products
ORDER BY price DESC
LIMIT 1;

Why does this happen?

MAX(price) squeezes five rows into one. name has a different value on every row, so PostgreSQL cannot know which name belongs on that single squeezed row, and it raises an error rather than guess. The second query simply forgets where NULL sorts. The fix is to use MAX() to find the value and then look up the row separately, or to add NULLS LAST.

Core concept: an aggregate folds many rows into one value

MIN() and MAX() are aggregate functions. An aggregate takes every row that survives the WHERE clause as its input and produces a single value as its output. That is why an aggregate query without GROUP BY returns exactly one row, whether the table holds five rows or five million. The order is FROM, then WHERE, then the aggregate, so adding WHERE added_on >= '2024-01-01' finds the extremes among 2024 products only.

"Smallest" depends on the data type. Numbers compare by value; dates and timestamps compare by time, so MIN is the earliest and MAX the latest; text compares alphabetically according to the database's collation. Text comparison becomes a trap when numbers are stored as text: '10' is smaller than '9', because the first character '1' sorts before '9'.

Remember two NULL rules. First, MIN and MAX skip NULLs: the NULL price of Pencil Case does not turn the minimum into NULL. Second, when no rows survive the WHERE clause, or every remaining value is NULL, the result is not zero rows but one row containing NULL. If your application needs 0 or another default, write COALESCE(MAX(price), 0).

MAX() returns only the value, never the row that owns it. To get the whole row you have two options: WHERE price = (SELECT MAX(price) FROM products) returns every row tied for the top price, while ORDER BY price DESC NULLS LAST LIMIT 1 returns exactly one. Decide what should happen when two products share the top price, then pick the matching form.

Aggregates can also be combined in expressions. MAX(price) - MIN(price) gives the price spread, and MAX(added_on) - MIN(added_on) subtracts two dates, which in PostgreSQL yields a number of days. When one SELECT holds several aggregates, each reads the same set of rows and is computed independently of the others.

Mental model: scan, skip NULLs, keep one
  1. WHERE filters the rows
  2. Read the column value of each row
  3. Skip every NULL
  4. Keep only the smallest or largest
  5. No rows left: return NULL

MIN/MAX hand back a value, not a row; fetching the row is a separate step.

General pattern

sql
SELECT MIN(column_name) AS smallest,
       MAX(column_name) AS largest
FROM table_name
WHERE condition;

-- the whole row that holds the largest value
SELECT * FROM table_name
WHERE column_name = (SELECT MAX(column_name) FROM table_name);

Put MIN/MAX in the SELECT list and name each result column with AS. WHERE decides which rows take part. The second form finds the largest value first and then fetches the rows that hold it.

Example: the extremes of a product table

The products table holds five products, and Pencil Case has a NULL price because it has not been priced yet. One query finds the extremes of a number, a date and a text column at the same time.

min_max.sql
SELECT MIN(price)    AS cheapest,
       MAX(price)    AS priciest,
       MIN(added_on) AS first_added,
       MAX(added_on) AS last_added,
       MIN(name)     AS first_by_name
FROM products;

Code breakdown

  1. Line 1SELECT MIN(price) AS cheapest,

    Returns 3.50, the smallest of the four rows that have a price. Pencil Case's NULL is skipped, so the result is not NULL.

  2. Line 2MAX(price) AS priciest,

    Gives 39.00 from Backpack. Unlike ORDER BY price DESC, the NULL never wins as the largest value.

  3. Lines 3-4MIN(added_on) AS first_added,

    On a date column MIN is the earliest day (2023-11-05) and MAX the latest (2024-07-01).

  4. Line 5MIN(name) AS first_by_name

    On text, MIN returns the alphabetically first name, Backpack. Backpack also happens to be the priciest item: each aggregate is computed independently per column, and they do not describe the same row.

  5. Line 6FROM products;

    With no WHERE, all five rows take part, and with no GROUP BY the output is exactly one row.

You should see
 cheapest | priciest | first_added | last_added | first_by_name
----------+----------+-------------+------------+---------------
     3.50 |    39.00 | 2023-11-05  | 2024-07-01 | Backpack
(1 row)

Fetching the row that holds the extreme value

Here is a correct answer to the problem section's question. The subquery computes the top price first, and the outer query keeps the rows whose price equals it. In the second form, NULLS LAST pushes NULL prices to the end. Both return Backpack | 39.00.

priciest_row.sql
-- every product tied for the top price
SELECT name, price
FROM products
WHERE price = (SELECT MAX(price) FROM products);

-- exactly one product; NULL prices pushed to the end
SELECT name, price
FROM products
ORDER BY price DESC NULLS LAST
LIMIT 1;

How other databases differ

MySQL, SQLite and SQL Server sort NULL as the smallest value, so it lands last in DESC order; PostgreSQL and Oracle treat it as the largest. SQL Server also writes LIMIT as TOP 1. With MySQL's ONLY_FULL_GROUP_BY mode switched off, SELECT name, MAX(price) runs and returns an unpredictable name; PostgreSQL's error protects you from that.

MAX() versus GREATEST()

MAX() looks down one column, across all rows. GREATEST(a, b, c) and LEAST() compare several values across one row and give a result for every row. For example, with a minimum charge of 10.00, GREATEST(price, 10.00) gives each product's billed price. In PostgreSQL, GREATEST and LEAST ignore NULL arguments, so Pencil Case gets 10.00; in MySQL and Oracle a single NULL argument makes the result NULL.

greatest.sql
SELECT name, GREATEST(price, 10.00) AS billed
FROM products
ORDER BY product_id;

In real projects

Where this shows up in real projects

An e-commerce price-filter slider takes its two ends from MIN(price) and MAX(price), so adding a new product never requires a code change to the slider. Reports compute "first order date" and "last login" with MIN(order_date) and MAX(last_login_at). Sync jobs remember MAX(updated_at) and, on the next run, fetch only the rows changed after that moment.

Performance is worth knowing about too. With a B-tree index on the column, PostgreSQL can read MIN/MAX straight from one end of the index, which stays fast even on huge tables. Without an index it must scan every row. If a dashboard runs such a query constantly, check the plan with EXPLAIN and add an index where needed; a later lesson covers indexes in detail.

Common mistakes

Common mistakes

1. Mixing an aggregate with a plain column

SELECT name, MAX(price) FROM products; fails with "must appear in the GROUP BY clause". If you want a maximum per group, that is GROUP BY, covered in a later lesson; if you want the single top row, use a subquery or ORDER BY ... LIMIT.

2. Expecting 0 when no rows match

If no product satisfies WHERE added_on >= '2025-01-01', MAX(price) is NULL, not 0. Application code that treats it as a number can crash. Supply a default with COALESCE(MAX(price), 0), or show "no data" explicitly in the UI.

3. Storing numbers as text

With invoice numbers '9', '10' and '100' in a text column, MAX returns '9' and MIN returns '10', because text compares character by character. Store numbers as integer or numeric; if you cannot change the column, cast it, as in MAX(code::integer).

Mini challenge

Mini challenge: greenhouse temperature summary

The readings table holds temperature readings from two sensors, and one reading has a NULL temp_c because the sensor failed. Produce a one-row daily summary for the 'greenhouse' sensor.

  • Only rows from the 'greenhouse' sensor take part
  • Show the lowest and highest temperature
  • Compute temp_range = highest minus lowest
  • Show the first_reading and last_reading times
greenhouse.sql
SELECT
  -- TODO: lowest temp_c
  -- TODO: highest temp_c
  -- TODO: temp_range (highest minus lowest)
  -- TODO: first_reading and last_reading from recorded_at
FROM readings
-- TODO: keep only the greenhouse sensor
;

Expected: You get exactly one row: lowest | highest | temp_range | first_reading | last_reading --------+---------+------------+---------------------+--------------------- 18.5 | 27.0 | 8.5 | 2024-06-01 06:00:00 | 2024-06-01 18:00:00 (1 row)

Show hint

You can subtract one aggregate from another: MAX(temp_c) - MIN(temp_c). The NULL reading needs no special handling, because MIN and MAX skip it.

Show solution
greenhouse.sql
SELECT MIN(temp_c)               AS lowest,
       MAX(temp_c)               AS highest,
       MAX(temp_c) - MIN(temp_c) AS temp_range,
       MIN(recorded_at)          AS first_reading,
       MAX(recorded_at)          AS last_reading
FROM readings
WHERE sensor = 'greenhouse';

Quick quiz 1 / 3

A price column holds 5.00, NULL and 12.00. What does SELECT MIN(price) FROM items; return?

Quick quiz 2 / 3

In PostgreSQL, what does SELECT name, price FROM products ORDER BY price DESC LIMIT 1; return when some prices are NULL?

Quick quiz 3 / 3

You want, for every product, the larger of its price and 10.00. What should you use?

What to remember

  • MIN/MAX fold the rows left after WHERE into one value and work on numbers, dates and text.
  • They skip NULLs and return NULL when no rows remain, so reach for COALESCE when you need a default.
  • MAX() gives only the value; fetch the row with a subquery or ORDER BY ... NULLS LAST LIMIT 1.
  • Use GREATEST/LEAST to compare values within a single row.

PostgreSQL SQL Tutorial — PostgreSQL Global Development Group

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

MIN() & MAX() | Thuta Learning