Reading Data: The Core Operation
Before joins, aggregations, or window functions, you need to understand the building blocks of every SQL query. The SELECT statement is the workhorse of SQL — it retrieves data from one or more tables.
SELECT column1, column2
FROM table_name
WHERE condition
ORDER BY column1 ASC
LIMIT 10;
Each clause has a specific role:
- SELECT — Which columns to return. Use
*to return all columns (convenient but expensive in production — always prefer named columns). - FROM — Which table to read from.
- WHERE — Filter rows before any grouping. Only rows matching the condition are processed further.
- ORDER BY — Sort the result set.
ASC(ascending, default) orDESC(descending). - LIMIT — Cap the number of rows returned. Critical for exploratory queries on large tables — never run
SELECT * FROM orderson a 500-million-row table without aLIMIT.
The Logical Execution Order
SQL is written in one order but executed in a different order. This is one of the most common sources of confusion for new SQL writers:
1. FROM / JOIN — Identify and assemble the source data
2. WHERE — Filter individual rows
3. GROUP BY — Collapse rows into groups
4. HAVING — Filter groups
5. SELECT — Compute the output columns
6. ORDER BY — Sort the result
7. LIMIT / OFFSET — Truncate the result
This explains why you cannot reference a SELECT alias in a WHERE clause — the WHERE runs before SELECT computes the alias. It also explains why aggregate functions belong in HAVING, not WHERE.