TutreNews Learn

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.idnamecity
1AdaBerlin
2BenHamburg
3CleoBerlin
4DanMunich
5EvaHamburg
products.idnamecategoryprice
1Laptopelectronics900
2Mouseelectronics25
3Deskfurniture300
4Chairfurniture150
5Lampfurniture40
6Headphoneselectronics80
orders.idcustomer_idorder_date
112024-01-10
222024-01-15
312024-02-03
432024-02-20
552024-03-05
order_items.order_idproduct_idqty
111
122
242
361
431
452
521

In "predict" exercises, write each result row on its own line and separate columns with " | " (for example Ada | Berlin).

Worked example: Distinct cities

  1. customers has 5 rows but only 3 different cities.
  2. DISTINCT removes duplicates.
  3. ORDER BY makes the order predictable.
SELECT DISTINCT city FROM customers ORDER BY city;

Output:

Berlin
Hamburg
Munich