MIN returns the smallest value of a column. MAX returns the largest.
sql
SELECT MIN(price), MAX(price) FROM products;text
min | max
------+-------
3.50 | 49.95They work on every type that you can compare with < and > (Chapter 2):
| Type | MIN gives | MAX gives |
|---|---|---|
| number | the smallest | the largest |
| text | the first in alphabetical order | the last in alphabetical order |
| date | the earliest | the latest |
Like the other aggregates, MIN and MAX skip NULL.
MIN gives a value, not a row
MAX(price) is 49.95. It does not tell you which product costs that. A plain column next to an aggregate fails:
text
SELECT name, MAX(price) FROM products;
ERROR: column "products.name" must appear in the GROUP BY clause
or be used in an aggregate functionThe result of MAX is one row; name has 12 values. PostgreSQL does not choose one for you. The next lesson explains GROUP BY. To get the most expensive product's row, sort and keep the first row (Chapter 3):
sql
SELECT name, price FROM products ORDER BY price DESC LIMIT 1;