SQLMIN & MAX

MIN & MAX

MIN and MAX return the smallest and largest value in a column. They work on more than just numbers — dates and even text columns can be compared, which makes MIN/MAX one of the most versatile aggregate functions in SQL.

Basic usage

SQL
SELECT
  MIN(total) AS cheapest_order,
  MAX(total) AS most_expensive_order
FROM orders;
MIN/MAX work on text too

For text (string) columns, MIN and MAX compare values lexicographically — essentially alphabetical order, based on the underlying character encoding and collation. MIN returns the value that would sort first, MAX the one that would sort last.

SQL
SELECT
  MIN(last_name) AS first_alphabetically,
  MAX(last_name) AS last_alphabetically
FROM customers;
-- e.g. MIN = 'Adams', MAX = 'Zimmerman'
Note
Lexicographic comparison depends on your database's collation settings. Case sensitivity, accented characters, and locale-specific sorting rules can all affect which value counts as "smallest" or "largest" for text. Numbers and dates do not have this ambiguity.
A very common pattern: earliest and latest dates

One of the most frequent real-world uses of MIN/MAX is finding the earliest or latest date in a dataset — a customer's first order, the most recent login, the oldest open support ticket, and so on.

orders

SQL
SELECT
  customer_id,
  MIN(created_at) AS first_order_date,
  MAX(created_at) AS most_recent_order_date
FROM orders
GROUP BY customer_id;
customer_id | first_order_date | most_recent_order_date
------------+-------------------+-------------------------
          1 | 2023-02-14        | 2026-06-30
          2 | 2024-08-01        | 2024-08-01
          3 | 2022-11-05        | 2026-05-19
Tip
`MIN(created_at)` and `MAX(created_at)` combined with GROUP BY customer_id is a fast, idiomatic way to build a "customer lifetime" report — first order date paired with most recent order date — without writing a subquery.
MIN/MAX ignore NULLs

SQL
-- Rows with a NULL shipped_at are ignored when computing MIN/MAX
SELECT
  MIN(shipped_at) AS earliest_shipment,
  MAX(shipped_at) AS latest_shipment
FROM orders;
-- Orders that have not shipped yet (shipped_at IS NULL) do not affect the result

Like every other aggregate function covered in this section, MIN and MAX silently skip NULL values. If every row in a group has a NULL in the target column, MIN/MAX for that group returns NULL rather than an error.

  • MIN and MAX find the smallest and largest values in a column.

  • They work on numbers, dates, and text (lexicographic comparison).

  • A very common pattern: pair with GROUP BY to get earliest/latest dates per group.

  • NULL values are ignored; a group of all-NULLs returns NULL.