SUM, AVG, MIN, and MAX

Basic SQL
≈ 1 min read

SUM and AVG work with numeric values

SUM adds values together, while AVG calculates their average.

SELECT
    SUM(amount) AS total_amount,
    AVG(amount) AS average_amount
FROM orders
WHERE status = 'PAID';

Both functions work only with rows that passed WHERE. NULL values in the aggregated expression are normally ignored.

MIN and MAX find the boundaries of a set

SELECT
    MIN(price) AS cheapest,
    MAX(price) AS most_expensive
FROM products;

MIN returns the smallest value, while MAX returns the largest. These functions are not limited to numbers: database systems can also compare dates and other ordered types.

AVG does not divide by the total number of rows. If the aggregated column contains NULL, those values are normally excluded both from the sum and from the number of values used to calculate the average.