Finding extremes with MIN and MAX #
MIN and MAX are aggregate functions that find the smallest and largest value in a column. You can use them together in the same query, since a query can compute more than one aggregate at once.
SELECT
MIN(column_name) AS smallest,
MAX(column_name) AS largest
FROM
table_name;
Example #
SELECT
MIN(age) AS youngest,
MAX(age) AS oldest
FROM
customers;
Result:
+----------+--------+
| youngest | oldest |
+----------+--------+
| 21 | 100 |
+----------+--------+
This gives us the smallest and the largest age in customers, both in a single query.
Exercise #
Write a single command that finds the cheapest and the most expensive product in the products table.
- The result has a
min_pricecolumn matching the smallestpriceinproducts. - The result has a
max_pricecolumn matching the largestpriceinproducts.
Solution
SELECT
MIN(price) AS min_price,
MAX(price) AS max_price
FROM
products;
Basic Data Retrieval
Filtering Data
Aggregating Data
Joining Tables
Creating and Managing Tables
Transactions and Data Integrity