$ settings --editor

$ settings --general

$ save --settings

SQL for beginners

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_price column matching the smallest price in products.
  • The result has a max_price column matching the largest price in products.
Solution
SELECT
    MIN(price) AS min_price,
    MAX(price) AS max_price
FROM
    products;
Output will be displayed here