Careeroza
MIN & MAX
The SQL MIN() and MAX() Functions
MIN() returns the smallest value and MAX() the largest. They work on numbers, text (alphabetical) and dates.
Example
Cheapest and most expensive product, and the first and last order date:
SELECT MIN(Price) AS Cheapest, MAX(Price) AS MostExpensive,
MIN(OrderDate) AS FirstOrder, MAX(OrderDate) AS LastOrder
FROM Products, Orders;Result: 1 row
| Cheapest | MostExpensive | FirstOrder | LastOrder |
|---|---|---|---|
| 3.49 | 18 | 2024-01-05 | 2024-04-02 |
Row with the Maximum Value
MAX() returns the value, not the row. To get the whole row, compare with a subquery or sort and limit:
Example
Return the whole row of the most expensive product with a subquery:
SELECT * FROM Products
WHERE Price = (SELECT MAX(Price) FROM Products);Result: 1 row
| ProductID | ProductName | Category | Price | Stock |
|---|---|---|---|---|
| 5 | Espresso Beans 1kg | Beverages | 18 | 45 |
Example (ORDER BY + LIMIT)
Or sort by price and keep only the first row:
SELECT * FROM Products
ORDER BY Price DESC
LIMIT 1;Result: 1 row
| ProductID | ProductName | Category | Price | Stock |
|---|---|---|---|---|
| 5 | Espresso Beans 1kg | Beverages | 18 | 45 |