SELECT: reading data
SELECT is the most-used SQL command. It reads data and returns a result table.
Choosing columns
* means "all columns". In real projects, list the columns you need: the query is clearer and faster.
SQL keywords aren't case-sensitive (select works too), but writing them in UPPERCASE is a common convention that makes queries easier to read. The ; ends a statement.
Calculated columns and aliases
You can compute new values. AS gives a column a friendly name (an alias).
Text functions
-- starts a comment in SQL.
Function names vary a little between databases. For example, PostgreSQL also has
CONCAT(), and MySQL usesCONCAT()instead of||. The concepts are identical.
Removing duplicates with DISTINCT
CASE: if/else in SQL
Practice
- Show every product's
name,categoryand its price in cents (price * 100) asprice_cents. - Show each customer's name and the domain of their email. Hint:
SUBSTR(email, INSTR(email, '@') + 1).
✎ Check your understanding
1.What does SELECT DISTINCT city FROM customers return?
2.What is AS used for?