Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

SQL
SQL
0/12 completed
Beginner
What is a database?SELECT: reading dataFiltering with WHERESorting and limiting results
Intermediate
Aggregates and GROUP BYJOINs: combining tablesINSERT, UPDATE and DELETECreating tables and constraints
Advanced
Subqueries and CTEsWindow functions
Pro
Indexes and transactionsDatabase design and normalization
Tracks / SQL / Intermediate

Aggregates and GROUP BY

Aggregate functions turn many rows into one summary value. They answer business questions like "How many orders did we get?" or "What's our average price?"

Function Returns
COUNT(*) number of rows
COUNT(col) number of non-NULL values
SUM(col) total
AVG(col) average
MIN(col) / MAX(col) smallest / largest
SQL · editable

GROUP BY: one summary per group

GROUP BY splits rows into groups and runs the aggregate once per group.

SQL · editable
SQL · editable

The golden rule: every column in SELECT must either be in the GROUP BY or be inside an aggregate function. Otherwise, which row's value should the database show? (SQLite and MySQL may allow it silently and give you a random row. PostgreSQL refuses.)

HAVING: filtering groups

WHERE filters rows before grouping. HAVING filters groups after aggregating.

SQL · editable
SQL · editable

Logical order of execution

SQL is written in one order but executed in another. This explains why you can't use a SELECT alias inside WHERE:

  1. FROM: pick the table(s)
  2. WHERE: filter rows
  3. GROUP BY: form groups
  4. HAVING: filter groups
  5. SELECT: compute the output columns
  6. ORDER BY: sort
  7. LIMIT: cut

Grouping by dates

SQL · editable

(strftime is SQLite. PostgreSQL uses date_trunc('month', order_date), MySQL uses DATE_FORMAT.)

Practice

  1. Find the total units ordered per product_id, highest first.
  2. Find the categories whose average price is above 20.
SQL · editable
✎ Check your understanding

1.What's the difference between WHERE and HAVING?

2.What does COUNT(email) count?

← Sorting and limiting results