Watching a SELECT Query Run, Step by Step
We write SELECT first, but the database does not start there. Understanding the order in which the parts of a query are applied clears up many confusing errors. This tutorial draws each stage as a picture.
The query we will follow
SELECT city, COUNT(*) AS members
FROM members
WHERE active = 1
GROUP BY city
ORDER BY members DESC
LIMIT 2;
It asks: "Which two cities have the most active members?"
Picture 1: FROM, start with the whole table
Draw the members table with eight rows. Each row has a name, a city and an active flag of 1 or 0.
Caption: the database begins with every row of the table named in FROM.
Picture 2: WHERE, cross out rows
Cross out every row where active is 0. Suppose three rows are crossed out, leaving five.
Caption: WHERE removes rows before anything else happens. Removed rows take no further part in the query.
Picture 3: GROUP BY, make piles
Sort the five remaining rows into piles by city: perhaps three in "Leeds", one in "Cork", one in "Porto".
Caption: GROUP BY turns rows into groups. From now on, the query works with piles, not individual rows.
Picture 4: SELECT, write one line per pile
For each pile, write the city and how many rows it holds: Leeds 3, Cork 1, Porto 1.
Caption: this is where the columns in SELECT are worked out, including COUNT(*) and the new name members. Each pile becomes one output row.
Picture 5: ORDER BY, rearrange the lines
Reorder the lines from biggest count to smallest: Leeds 3 first. Cork and Porto tie at 1, so their order is not guaranteed unless you add a second sort column such as city.
Caption: sorting happens after SELECT, which is why ORDER BY can use the name members defined there.
Picture 6: LIMIT, keep the first two
Draw a line under the second row and cross out the rest.
Caption: LIMIT simply keeps the first few rows of the sorted result.
The order, in one table
| Stage | Written position | Applied |
|---|---|---|
| FROM | 2nd | 1st |
| WHERE | 3rd | 2nd |
| GROUP BY | 4th | 3rd |
| SELECT | 1st | 4th |
| ORDER BY | 5th | 5th |
| LIMIT | 6th | 6th |
Why it matters: two classic errors
"Column does not exist" in WHERE. WHERE members > 1 fails because WHERE runs before SELECT has created members. To filter groups, use HAVING, which runs after grouping: HAVING COUNT(*) > 1.
"Must appear in the GROUP BY clause". After grouping, each pile becomes one line. A column like name has several different values per pile, so the database cannot choose one. Either group by it too, or summarise it with a function such as MIN or COUNT.
Try it
Make a members table with ten rows of your own and run the query. Then change one stage at a time (remove WHERE, change LIMIT) and predict the result before you run it. For a gentler start, see SELECT queries in five short modules.
A free learning page for beginners. Practise on a test database, never on real customer data, and check the official documentation for your database version.