DevPath · Learn to code ESPTEN

Aggregations: GROUP BY and HAVING

Aggregate functions

From many rows to a single value

Until now every query returned one row per record. Aggregate functions do the opposite: they take a set of rows and summarize it into a single value.

Function What it computes
COUNT(*) number of rows
COUNT(col) number of non-null values of col
SUM(col) sum of the values
AVG(col) average (mean) of the values
MIN(col) minimum value
MAX(col) maximum value

For example, over the products table:

SELECT COUNT(*) FROM products;        -- how many products are there?
SELECT AVG(price) FROM products;      -- average price of all of them
SELECT MIN(price), MAX(price) FROM products;

Without GROUP BY, the aggregate function acts on all the rows in the table (or those that survive the WHERE) and produces a single result row.

Aliases with AS

An aggregated column would literally be called AVG(price). To give it a readable name you use AS:

SELECT AVG(price) AS average_price, COUNT(*) AS total
FROM products;

COUNT(*) counts rows (including those with nulls); COUNT(col) counts only the rows where col is not NULL. That difference matters when there is incomplete data.

Put this into practice

DevPath is a hands-on course: you read the theory here; in the app you put it into practice with exercises that really run, offline.

Start free in the app →
Grouping with GROUP BY →