SELECT
SELECT retrieves rows from a table (or from a join, a view, a subquery — anything that produces rows). It is the statement you will write more often than every other SQL statement combined, and mastering its clauses is the foundation for everything from simple lookups to complex analytical queries.
Selecting everything
Every column, every row
SELECT * FROM products;
The asterisk is shorthand for "every column, in table definition order." It is convenient while exploring data interactively at a psql prompt.
Selecting specific columns
In real application code and reports, naming the columns you actually need is almost always the better choice.
Only the columns needed
SELECT sku, name, unit_price FROM products WHERE stock_qty > 0;
Computed columns
A SELECT list is not limited to raw columns — any expression is allowed, and AS gives the resulting computed column a readable name (an alias).
Computing a line total
SELECT sku, name, unit_price, stock_qty, unit_price * stock_qty AS inventory_value FROM products;
sku | name | unit_price | stock_qty | inventory_value ----------+----------------+------------+-----------+------------------ SKU-1001 | Wireless Mouse | 24.99 | 150 | 3748.50
Logical execution order
SQL is written in one order but conceptually executed in another. Knowing the real order explains a lot of otherwise-confusing rules — for instance, why a computed alias defined in SELECT usually cannot be referenced in that same query's WHERE clause: WHERE runs before SELECT does.
Step | Clause | What happens |
|---|---|---|
1 | FROM | Identify the source table(s) and evaluate joins |
2 | WHERE | Filter individual rows before any grouping |
3 | GROUP BY | Collapse rows into groups, if grouping is used |
4 | HAVING | Filter entire groups, after grouping |
5 | SELECT | Compute the final output columns and aliases |
6 | ORDER BY | Sort the result set |
SELECT * returns every column; naming columns explicitly is safer for production code.
AS gives a computed expression a readable alias in the result set.
PostgreSQL evaluates FROM, then WHERE, then GROUP BY, then HAVING, then SELECT, then ORDER BY — not the order the clauses are written in.