How to write a SQL query
Short answer
Start with SELECT to choose columns, FROM to pick the table, then add WHERE to filter, ORDER BY to sort, and GROUP BY to aggregate. Build it up one clause at a time and test against real data.
The clauses, in order
A SQL SELECT reads as a sentence: which columns, from which table, matching which conditions, in which order. You write the clauses in a fixed order, though the database evaluates them differently.
SELECT name, COUNT(*) AS orders
FROM users
JOIN orders ON orders.user_id = users.id
WHERE users.active = 1
GROUP BY name
ORDER BY orders DESC;Build it up step by step
- SELECT + FROMChoose the columns and the table: SELECT name FROM users.
- Filter with WHEREKeep only the rows you want: WHERE active = 1.
- Join related tablesPull in other data with JOIN ... ON a matching key.
- Group and sortAggregate with GROUP BY, then order with ORDER BY.
Keep queries readable
- Uppercase keywords (SELECT, FROM, WHERE) so structure stands out
- One clause per line; indent joins and conditions
- Alias tables so joins are easy to follow
- Format messy queries before sharing or reviewing them