Subqueries and CTEs
Scalar Subquery
Compare to an Average
A scalar subquery returns one value that the outer query can use.
Program
Play the query to keep scores above the overall average.
scalar_subquery.sql
Replay: real traced execution (multi-file project)
CREATE TABLE scores (name TEXT, points INTEGER);
INSERT INTO scores VALUES ('Ada', 9), ('Lin', 12), ('Mia', 6);
SELECT name, points FROM scores WHERE points > (SELECT AVG(points) FROM scores) ORDER BY points DESC;
scores ← 0 rows
1CREATE TABLE scores (name TEXT, points INTEGER);2INSERT INTO scores VALUES ('Ada', 9), ('Lin', 12), ('Mia', 6);values this step0 rowsscoresscores ← 3 rows
1CREATE TABLE scores (name TEXT, points INTEGER);2INSERT INTO scores VALUES ('Ada', 9), ('Lin', 12), ('Mia', 6);3SELECT name, points FROM scores WHERE points > (SELECT AVG(points) FROM scores) ORDER BY points DESC;values this step3 rowsscoresresult ← 1 row
2INSERT INTO scores VALUES ('Ada', 9), ('Lin', 12), ('Mia', 6);3SELECT name, points FROM scores WHERE points > (SELECT AVG(points) FROM scores) ORDER BY points DESC;values this step1 rowresult
Follow the Average
- The scores are Ada
9, Lin12, and Mia6. - The scalar subquery computes the average points:
9. - The outer query checks each row with
points > 9. - Ada is equal to the average, so she is not kept.
- Only Lin has more than
9, so the final row is Lin12. | name | points | compared to average 9 | result | | --- | --- | --- | --- | | Ada | 9 | equal | filtered out | | Lin | 12 | greater | kept | | Mia | 6 | lower | filtered out |
subquery
A subquery is a query nested inside another query.
scalar
`AVG(points)` returns one value here.
outer query
The outer query compares each row to the subquery value.
Exercise: scalar_subquery.sql
Reproduce the final row Lin 12, then predict whether a score equal to the average would pass the filter.