Relational Algebra to SQL Workshop
Retrieval Prompts
- State, in one sentence each, what these operators do: selection
σ, projectionπ, natural join⋈, union∪, difference−, renameρ. - State the difference between a relation (Codd) and an SQL table (multiset with ordered columns).
- State the logical evaluation order of an SQL query with
FROM,WHERE,GROUP BY,HAVING,SELECT,ORDER BY. - State the semantic difference between putting a predicate in
ONversusWHEREfor aLEFT OUTER JOIN. - Explain in one sentence why
SELECTcannot reference an alias defined in the sameSELECTlist insideWHERE.
Compare and Distinguish
Separate these pairs clearly:
- superkey vs candidate key vs primary key vs alternate key
- natural join
⋈vs inner join withONvsCROSS JOIN+WHERE UNIONvsUNION ALL- correlated subquery vs derived table vs CTE
WHEREvsHAVINGINNER JOINvsLEFT JOIN ... IS NULL(anti-join)
Common Mistake Check
Identify the bug or incorrect claim in each:
SELECT name, AVG(salary) FROM employee GROUP BY dept_id;- "
LEFT JOINfollowed byWHERE b.col = 1returns the same rows as puttingb.col = 1in theONclause." SELECT dept, salary, RANK() OVER (PARTITION BY dept ORDER BY salary DESC) FROM employee WHERE rank = 1;- "
SELECT *from a natural join ofemployeeanddeptondept_idreturns every column from both tables, includingdept_idtwice." - "
UNIONis faster thanUNION ALLbecause it removes duplicates."
Mini Application
Translate each English description into (a) relational algebra in the σ / π / ⋈ / ∪ / − notation, then (b) equivalent PostgreSQL SQL.
Schema:
customer(id, name, region)
orders(id, customer_id, total_cents, placed_at)
order_item(order_id, product_id, qty, unit_cents)
product(id, name, category)
- Names of customers in
'EU'who have placed at least one order. - For each region, the total revenue (sum of
total_cents) in 2025. - Products (id, name) that have never been ordered.
- Customers who ordered every product in category
'books'(set-difference flavor -- hint: "there is no book such that the customer has not ordered it"). - The top-3 highest-spending customers per region (use window functions in SQL; describe in prose for algebra).
Schema Sketch
Write CREATE TABLE statements for the schema above with:
- appropriate
PRIMARY KEY,FOREIGN KEY,NOT NULL,UNIQUE, andCHECKconstraints ON DELETEactions that reflect reasonable business behavior for each FK
Evidence Check
This page is complete only if, for any English description of a query over this schema, you can:
- decompose it into relational algebra operators and justify each one
- write a PostgreSQL query that returns the same rows and columns
- explain the evaluation order the database will use
- defend the choice of inner vs outer vs semi vs anti join in one sentence