1 Understanding the SELECT Query
TopThe SELECT statement is the backbone of SQL. It's how you ask the database a question and get an answer back. Every report, dashboard, search result, and data export starts with a SELECT query.
The Anatomy of a SELECT Statement
A full SELECT query has a specific clause order. Not all clauses are required, but when present they must follow this sequence:
SELECT columns -- 1. What columns do you want?
FROM table -- 2. From which table?
WHERE condition -- 3. Which rows? (filter)
GROUP BY column -- 4. Group rows together?
HAVING group_condition -- 5. Filter groups?
ORDER BY column -- 6. Sort the results?
LIMIT n -- 7. How many rows?Let's see a real example that uses several of these clauses:
-- "Show me the top 3 customers by total spending"
SELECT customer,
COUNT(*) AS total_orders,
SUM(amount * quantity) AS total_spent
FROM orders
GROUP BY customer
ORDER BY total_spent DESC
LIMIT 3;customer | total_orders | total_spent --------------|--------------|------------ Sara Ahmed | 3 | 172.47 David Chen | 1 | 119.98 Priya Sharma | 2 | 154.96
Don't worry if GROUP BY and SUM look unfamiliar - we'll cover them in detail in Topic 4. The point here is to see how the clauses work together.
Execution Order: Not What You'd Expect
You write SELECT first, but the database executes in a different order:
| Step | Clause | What Happens |
|---|---|---|
| 1 | FROM | Pick the table(s) |
| 2 | WHERE | Filter individual rows |
| 3 | GROUP BY | Group remaining rows |
| 4 | HAVING | Filter groups |
| 5 | SELECT | Choose columns & calculate |
| 6 | ORDER BY | Sort results |
| 7 | LIMIT | Cut to N rows |
Why does execution order matter? Because you can't use a column alias defined in SELECT inside the WHERE clause - WHERE runs before SELECT. For example, WHERE total_spent > 100 won't work if total_spent is an alias. Use HAVING instead (it runs after SELECT).
Key Takeaways
- SELECT is the core query command - it retrieves data from one or more tables
- Clause order:
SELECT → FROM → WHERE → GROUP BY → HAVING → ORDER BY → LIMIT - The database executes FROM first, then WHERE, then GROUP BY - not top-to-bottom
- You can't reference SELECT aliases in WHERE - use HAVING for filtered aggregates