SELECT Basics
SELECT statement is the most frequently used piece of SQL. Every time you read data out of a relational database — a single row, a whole table, or a computed summary — you are writing a SELECT query. Everything else in this tutorial series builds on top of it.Selecting everything
* to ask for every column in a table:Select all columns
SELECT * FROM employees;
This returns every column, for every row, in whatever order the database happens to store or return them. It is convenient, but as you will see below, it is not something you generally want in production code.
Selecting specific columns
SELECT:Select specific columns
SELECT first_name, last_name FROM employees;
The order of the columns in the output matches the order you list them in — not the order they exist in the underlying table.
SELECT * is great for quickly poking around a table while you are exploring a schema, but it causes real problems once code depends on it:Fragile to schema changes — if a new column is added to the table later, every application that blindly consumed {*} suddenly gets an extra field it wasn't expecting, which can break serialization, APIs, or downstream processing
Wastes bandwidth and memory — you pull columns across the network (and load them into memory) that your code never actually uses, especially painful for wide tables or large text/blob columns
Unclear intent — a reader has to go check the table definition to know what a query actually returns; explicit column names document exactly what the query depends on
Breaks index-only scans — some databases can answer a narrow query using only an index, without touching the full table row; asking for every column usually rules that optimization out
The order clauses run in
One of the most important — and most confusing at first — things about SQL is that the order you write a query is not the order the database actually executes it. The database conceptually works through a pipeline of logical steps before it hands you a result.
Step | Written order | Logical execution order |
|---|---|---|
1 | SELECT | FROM |
2 | FROM | WHERE |
3 | WHERE | GROUP BY |
4 | GROUP BY | HAVING |
5 | HAVING | SELECT |
6 | ORDER BY | ORDER BY |
FROM), then filters individual rows (WHERE), then groups the remaining rows (GROUP BY), then filters those groups (HAVING), then computes the actual output columns (SELECT), and only at the very end sorts the result (ORDER BY).SELECT-defined column alias in ORDER BY (it runs after SELECT), but generally not in WHERE (it runs before SELECT). We will come back to this repeatedly as the series introduces each clause.