SELECT
SELECT lists the columns you want and FROM names the table: SELECT name, email FROM customers. Use SELECT * to return every column, and put expressions such as price * qty in the list to compute new columns. It is the first clause of nearly every query.
Syntax
SELECT column1, column2, expression AS alias FROM table_name;| Part | What it is |
|---|---|
column list | Comma-separated column names or expressions; * means all columns |
FROM table_name | The table (or join) the rows come from |
AS alias | Optional name for a column or expression in the result |
Examples
SELECT name, country FROM customers;Result: Two columns, one row per customer
Columns come back in the order you list them, not the table order.
SELECT * FROM orders;Result: Every column of orders
Fine while exploring; in reports and application code name the columns you need.
SELECT id, price, price * 1.21 AS price_with_vat FROM products;Result: id | price | price_with_vat 1 | 10.00 | 12.1
An expression without AS gets a generated name like price * 1.21, so alias it.
Common mistakes
- A column name that does not exist raises no such column (SQLite) or column does not exist (PostgreSQL); check spelling and that you are selecting from the right table.
- Forgetting the comma between two columns makes the second one an alias of the first (SELECT name email returns one column called email).
- Using SELECT * in a join returns duplicate column names such as two id columns; list the columns with their table prefix instead.
Practice SELECT
These drills check your answer on live data, free, no account needed.
- Pick two columnsReturn the name and country of every customer.
Questions
What is the order of clauses in a SELECT statement?
SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT. The database evaluates FROM and WHERE first and SELECT near the end, which is why a column alias cannot be used in WHERE.
Is SQL case sensitive?
Keywords are not: select and SELECT are the same. Unquoted table and column names are case insensitive in SQLite and are folded to lowercase in PostgreSQL. String values inside quotes are compared exactly in PostgreSQL.
Related
- WHEREUse WHERE to keep only the rows that match a condition: equals, greater than, text matches, NULL checks, and combinations with AND, OR and NOT.
- ORDER BYORDER BY sorts the rows of a query result. Learn ASC and DESC, sorting on multiple columns, sorting by an expression or alias, and where NULLs end up.
- LIMIT and OFFSETLIMIT returns only the first N rows of a query and OFFSET skips rows before that. Get the top 10, page through results and find the second highest value.
- Aliases (AS)An alias gives a column or table a temporary name: SELECT price * qty AS total, FROM orders o. Where aliases are allowed (ORDER BY yes, WHERE no) and quoting.