Reading data
SELECT and FROM
Goal: Retrieve columns from a table · 8 min
A relational database stores data in tables: each row is a record, each column an attribute. SQL (Structured Query Language) is the standard language for asking questions about such data.
The simplest query names the columns and the table:
SELECT name, city FROM customers;
SELECT * returns all columns — handy for exploring, but in real applications name the columns you need. You can compute new columns and rename them with AS: SELECT name, price * 1.19 AS gross FROM products; SQL keywords are case-insensitive; writing them in capitals is a convention. DISTINCT removes duplicate rows.
The practice database (a small online shop) used in every exercise:
| customers.id | name | city |
|---|---|---|
| 1 | Ada | Berlin |
| 2 | Ben | Hamburg |
| 3 | Cleo | Berlin |
| 4 | Dan | Munich |
| 5 | Eva | Hamburg |
| products.id | name | category | price |
|---|---|---|---|
| 1 | Laptop | electronics | 900 |
| 2 | Mouse | electronics | 25 |
| 3 | Desk | furniture | 300 |
| 4 | Chair | furniture | 150 |
| 5 | Lamp | furniture | 40 |
| 6 | Headphones | electronics | 80 |
| orders.id | customer_id | order_date |
|---|---|---|
| 1 | 1 | 2024-01-10 |
| 2 | 2 | 2024-01-15 |
| 3 | 1 | 2024-02-03 |
| 4 | 3 | 2024-02-20 |
| 5 | 5 | 2024-03-05 |
| order_items.order_id | product_id | qty |
|---|---|---|
| 1 | 1 | 1 |
| 1 | 2 | 2 |
| 2 | 4 | 2 |
| 3 | 6 | 1 |
| 4 | 3 | 1 |
| 4 | 5 | 2 |
| 5 | 2 | 1 |
In "predict" exercises, write each result row on its own line and separate columns with " | " (for example Ada | Berlin).
Worked example: Distinct cities
- customers has 5 rows but only 3 different cities.
- DISTINCT removes duplicates.
- ORDER BY makes the order predictable.
SELECT DISTINCT city FROM customers ORDER BY city;Output:
Berlin
Hamburg
Munich