WITH: named queries
168 min
Complex queries quickly become a tangle: a subquery inside a subquery… WITH (a CTE — Common Table Expression) splits them into clear, named steps.
The pattern
WITH name AS (
SELECT …
)
SELECT … FROM name;name is a temporary table that exists only for this one query.
Example: students with a high average
First we work out each student’s average score, then we use it:
university
You could write the same with a subquery, but WITH is much easier to read: every step has a name.
Several CTEs
They are separated by commas, and each one can use the ones before it:
shop
Recursive CTEs
WITH RECURSIVE calls itself — for data shaped like a tree (manager → report → their report…):
company
The first part is the starting point (the CEO); the second goes one level down each time.
1Exercise
Use WITH to count each driver’s completed trips, and show driver_id and the trip count for drivers with more than 40.
Remember
WITH name AS (…)splits a query into named steps.- Several CTEs are separated by commas; a later one can use an earlier one.
WITH RECURSIVEhandles trees and chains.