FROM example
SELECT c.name,
c.city,
c.registered_at
FROM customers AS c
WHERE c.active = 1
ORDER BY c.registered_at, c.id
LIMIT 4;customers AS c defines the source and its alias. The references c.name and c.active make it clear where each column comes from.
What to look for: You can read the query from left to right: pick the columns with SELECT, take the rows from customers, keep the active ones and sort them by date. The alias c saves you repeating the table name.
Check the result with small data
This test has two tables, but the query only reads customers.
WITH customers(id, name) AS (VALUES (1, 'Amy'), (2, 'Liam')),
orders(id, customer_id) AS (VALUES (101, 1))
SELECT name FROM customers ORDER BY id;| name |
|---|
| Amy |
| Liam |
FROM names the source of the rows. Even though an orders table exists, its records are neither queried nor combined here.
Check your understanding: Which table would you change in FROM if you wanted to read orders?
Show answer
orders: FROM orders. FROM decides which table the rows come from; you would then need to choose columns that exist in that table.
How FROM is used
An alias shortens names and lets you tell columns apart when several tables are involved. Once you assign it, use it consistently throughout that query.
What changes from case to case
- Base table: stored data, such as
customers. - View: a saved query used as a source.
- Subquery: a result in parentheses with an alias.
- JOIN: a source built by relating tables.
- CTE: a named result defined with
WITH.
You do not need to master all of these forms at first. The key thing is to recognise that FROM does not “show” columns: it prepares the rows that are available.
Common mix-ups with FROM
SELECT customers.name
FROM customers AS c;On many engines, once you assign c you must refer to the source by that alias: SELECT c.name FROM customers AS c.