sql · level 2 · unit 1 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Every has its place, and the order never changes.
A query is built from clauses: parts that start with a keyword, like WHERE or GROUP BY. They always go in this order: SELECT, FROM, WHERE, GROUP BY, ORDER BY, then LIMIT.
WHERE sieves single rows before any grouping starts, so each group only holds rows that passed. Here only darts scores reach the groups.
ORDER BY works last, on the finished groups. That means it can sort by an aggregate's alias, like ORDER BY total DESC for a leaderboard. A second column after a comma settles ties: ORDER BY total DESC, player.
SELECT player, SUM(points) AS total
FROM scores
WHERE game = 'darts'
GROUP BY player
ORDER BY total DESC; Put a clause in the wrong place and you get a syntax error near the word that is out of order.
guess first
Cheap snacks, grouped. What comes back?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
SELECT kind, COUNT(*) AS cheap
FROM snacks
WHERE price < 100
GROUP BY kind
ORDER BY cheap DESC, kind;
your turn
Your turn. Build a leaderboard for one game.
Type darts or bowling between the quotes. The query adds up each player's points at that game and puts the best first.
result
Your answer appears here as a table.
fix it
The films report is in a muddle. Can you fix it?
result
Your answer appears here as a table.
- Read the error. Which word is it near?
WHEREsieves rows before they are grouped, so it must come beforeGROUP BY.- Move the WHERE line above the GROUP BY line, then press run.
nailed it
your groups came out sieved and sorted. :D
- Clauses go SELECT, FROM, WHERE, GROUP BY, ORDER BY, LIMIT.
WHEREsieves rows before the groups are made.ORDER BYcan sort by an aggregate's alias.
new words in your collection
- clause
This lesson isn’t saved. A free account remembers every lesson you finish.