SELECT-FROM-WHERE: The SQL Foundation
Concept. A basic query has three clauses. FROM chooses the table. WHERE keeps rows that make its predicate TRUE. SELECT chooses the output columns.
Intuition. You write SELECT-FROM-WHERE, but it runs FROM, then WHERE, then SELECT: load all of Listens, drop the rows that fail the rating test, then keep just the columns you asked for.
Figure 1. FROM produces nine Listens rows. WHERE keeps the five rows where rating > 4.0 evaluates to TRUE and drops rows where it evaluates to FALSE or UNKNOWN, including the NULL rating. SELECT returns only user_id, song_id, and rating and drops listen_id.
Basic Query Structure: The FloWS Order
-- Get listens with high ratings (above 4.0)
SELECT user_id, song_id, rating -- choose only 3 columns for output
FROM Listens -- picks the table (9 rows)
WHERE rating > 4.0 -- keeps rows where the test is TRUE
-
Execution Order: FROM → WHERE → SELECT. Read it as FWS (FloWS mnemonic). That is the reverse of the SFW you write.
-
Row Filtering: WHERE evaluates each row individually
-
Column Selection: SELECT determines output columns
You write SELECT first, but the database runs it last: it needs the table (FROM) and the surviving rows (WHERE) before it can decide what to return (SELECT).
WHERE with AND and OR
-- AND: both conditions must hold
SELECT user_id, song_id, rating
FROM Listens
WHERE user_id = 1 AND rating > 4.0
-- OR: either condition is enough
SELECT user_id, song_id, rating
FROM Listens
WHERE user_id = 1 OR rating > 4.0
Figure 2. AND keeps a row when both predicates evaluate to TRUE, so two rows survive. OR keeps a row when either predicate evaluates to TRUE, so six rows survive. The NULL rating makes rating > 4.0 evaluate to UNKNOWN, and UNKNOWN does not satisfy WHERE.
Understanding Aliases (AS Keyword)
An alias gives a column a new name in the output with AS. But because WHERE runs before SELECT, the alias does not exist yet when WHERE is evaluated, so WHERE cannot use it.
Figure 3. AS names an expression in the result produced by SELECT. WHERE runs earlier, so WHERE double_rating > 8 fails. WHERE can evaluate WHERE rating * 2 > 8 because it uses the underlying expression.
Why It Matters:
| Clause | Execution Order | Can Reference | Cannot Reference |
|---|---|---|---|
| FROM | 1st | Table names | SELECT aliases |
| WHERE | 2nd | Table columns | SELECT aliases |
| SELECT | 3rd | Table columns, expressions | Future aliases |
SELECT with Calculations
SELECT can also compute new columns. rating * 2 AS double_rating doubles a value; CASE ... WHEN is SQL's if-then-else.
SELECT
user_id,
rating,
rating * 2 AS double_rating,
CASE
WHEN rating >= 4.5 THEN 'Excellent'
WHEN rating >= 4.0 THEN 'Good'
ELSE 'Average'
END AS category
FROM Listens
WHERE rating IS NOT NULL
| user_id | rating | double_rating | category | |
|---|---|---|---|---|
| 1 | 4.5 | 9.0 | Excellent | |
| 1 | 4.2 | 8.4 | Good | |
| 1 | 3.9 | 7.8 | Average | |
| 2 | 4.7 | 9.4 | Excellent | |
| 3 | 4.9 | 9.8 | Excellent |