SQL exercises with solutions: CTEs (WITH)

SQL exercises with solutions: CTEs (WITH)

Updated on

WITH names an intermediate query, which you then reuse like a table. These 15 exercises range from level 5 to level 8; they use the syntax of SQLite, SpeedQL’s SQL engine.

Tip: Several CTEs can follow each other, separated by commas, before the final SELECT.

Read the “CTEs (WITH)” card in the cheat sheet

Exercise 1 · level 5

Using a CTE (WITH), compute the average salary of each department, then show the departments whose average is above 45000.

Table staff (10 rows)
idnamedepartmentsalarymanager_idhired
1AliceFinance52000NULL2015-03-01
2BobIT4100012018-06-15
3ClaireFinance3800012019-01-10
4DavidHR2900012020-09-01
5EmmaIT5000022017-11-20
6FaridIT4700022021-02-14
7GaelleHR3300042022-05-30
8HugoFinance4400032016-08-08
9IrisIT4700052023-01-09
10JulesFinance4400032024-03-18
Show the hint

Topics to use: WHERE (filters), COUNT, SUM, AVG, MIN, MAX, GROUP BY, CTEs (WITH).

Query structure:

WITH  AS (
  SELECT , AVG() AS 
  FROM 
  GROUP BY )
SELECT 
FROM 
WHERE  > 
Show the solution
WITH avg_dept AS (
  SELECT department, AVG(salary) AS a
  FROM staff
  GROUP BY department)
SELECT department
FROM avg_dept
WHERE a > 45000;

Expected result (1 row):

department
IT

Exercise 2 · level 5

Using a CTE (WITH), compute the total salaries per department, then show the department with the highest total.

Table staff (10 rows)
idnamedepartmentsalarymanager_idhired
1AliceFinance52000NULL2015-03-01
2BobIT4100012018-06-15
3ClaireFinance3800012019-01-10
4DavidHR2900012020-09-01
5EmmaIT5000022017-11-20
6FaridIT4700022021-02-14
7GaelleHR3300042022-05-30
8HugoFinance4400032016-08-08
9IrisIT4700052023-01-09
10JulesFinance4400032024-03-18
Show the hint

Topics to use: ORDER BY, LIMIT, COUNT, SUM, AVG, MIN, MAX, GROUP BY, CTEs (WITH).

Query structure:

WITH  AS (
  SELECT , SUM() AS 
  FROM 
  GROUP BY )
SELECT 
FROM 
ORDER BY  DESC
LIMIT 
Show the solution
WITH t AS (
  SELECT department, SUM(salary) AS s
  FROM staff
  GROUP BY department)
SELECT department
FROM t
ORDER BY s DESC
LIMIT 1;

Expected result (1 row):

department
IT

Exercise 3 · level 5

Using a CTE (WITH), count the loans of each member, then show the name of the members who borrowed more than the average (average computed over the members who have at least one loan).

Table members (6 rows)
idnamecityjoined
1LenaLyon2022-01-15
2MarcParis2021-06-03
3NadiaLyon2023-03-20
4OscarLille2020-11-11
5PaulaParis2024-02-01
6QuentinNantes2023-09-09
Table loans (12 rows)
idbook_idmember_idloan_datereturn_date
1112025-01-052025-01-19
2322025-01-102025-02-02
3512025-02-012025-02-10
4732025-02-03NULL
5342025-02-152025-03-01
6222025-03-022025-03-30
7852025-03-05NULL
8132025-03-102025-03-18
9612025-03-202025-04-15
10352025-04-01NULL
11942025-04-052025-04-12
121022025-04-082025-04-20
Show the hint

Topics to use: WHERE (filters), COUNT, SUM, AVG, MIN, MAX, GROUP BY, JOIN, Subqueries, CTEs (WITH).

Query structure:

WITH  AS (
  SELECT , COUNT(*) AS 
  FROM 
  GROUP BY )
SELECT 
FROM 
JOIN   ON  = 
WHERE  > (SELECT AVG() FROM )
Show the solution
WITH c AS (
  SELECT member_id, COUNT(*) AS n
  FROM loans
  GROUP BY member_id)
SELECT m.name
FROM c
JOIN members m ON m.id = c.member_id
WHERE c.n > (SELECT AVG(n) FROM c);

Expected result (2 rows):

name
Lena
Marc

Exercise 4 · level 5

Using a CTE (WITH), compute the total number of goals of each match, then show the date of the matches whose total is above the average total.

Table matches (10 rows)
idplayed_onhome_idaway_idhome_goalsaway_goals
12025-08-021221
22025-08-033400
32025-08-095113
42025-08-102322
52025-08-164531
62025-08-171310
72025-08-232401
82025-08-243523
92025-08-304111
102025-08-315202
Show the hint

Topics to use: WHERE (filters), COUNT, SUM, AVG, MIN, MAX, Subqueries, CTEs (WITH).

Query structure:

WITH  AS (
  SELECT ,  +  AS 
  FROM )
SELECT 
FROM 
WHERE  > (SELECT AVG() FROM )
Show the solution
WITH t AS (
  SELECT played_on, home_goals + away_goals AS g
  FROM matches)
SELECT played_on
FROM t
WHERE g > (SELECT AVG(g) FROM t);

Expected result (5 rows):

played_on
2025-08-02
2025-08-09
2025-08-10
2025-08-16
2025-08-24

Exercise 5 · level 5

Using a CTE (WITH), compute the mean temperature of each reading ((max + min) / 2), then show the city, day and that mean for the readings where it is above 22.

Table readings (15 rows)
idcitydaytemp_maxtemp_minrain_mm
1Paris2025-07-0124150
2Paris2025-07-0227170
3Paris2025-07-0322164.5
4Paris2025-07-04191412
5Paris2025-07-0523130
6Lyon2025-07-0126160
7Lyon2025-07-0229180
8Lyon2025-07-0331190
9Lyon2025-07-0424178.5
10Lyon2025-07-0522153
11Marseille2025-07-0130210
12Marseille2025-07-0232220
13Marseille2025-07-0333230
14Marseille2025-07-0429210
15Marseille2025-07-0528200
Show the hint

Topics to use: WHERE (filters), CTEs (WITH).

Query structure:

WITH  AS (
  SELECT , , ( + ) /  AS 
  FROM )
SELECT , , 
FROM 
WHERE  > 
Show the solution
WITH m AS (
  SELECT city, day, (temp_max + temp_min) / 2.0 AS t
  FROM readings)
SELECT city, day, t
FROM m
WHERE t > 22;

Expected result (7 rows):

citydayt
Lyon2025-07-0223.5
Lyon2025-07-0325
Marseille2025-07-0125.5
Marseille2025-07-0227
Marseille2025-07-0328
Marseille2025-07-0425
Marseille2025-07-0524

Exercise 6 · level 5

Using a CTE (WITH), compute the amount of each booking (number of nights × room price), then show the id and amount of the bookings above 500.

Table rooms (10 rows)
idhotel_idtypeprice
11single70
21double95
32double130
42suite210
53single110
63double150
74double65
85double260
95suite480
105single190
Table bookings (11 rows)
idroom_idguest_idcheck_incheck_out
1212025-07-012025-07-04
2522025-07-022025-07-05
3832025-07-032025-07-06
4342025-07-052025-07-12
5652025-07-062025-07-08
6122025-07-082025-07-10
7932025-07-102025-07-11
8752025-07-112025-07-15
9412025-07-142025-07-16
10642025-07-152025-07-19
11652025-07-162025-07-18
Show the hint

Topics to use: WHERE (filters), JOIN, Text and dates, CTEs (WITH).

Query structure:

WITH  AS (
  SELECT , (JULIANDAY() - JULIANDAY()) *  AS 
  FROM  
  JOIN   ON  = )
SELECT , CAST( AS INTEGER)
FROM 
WHERE  > 
Show the solution
WITH a AS (
  SELECT b.id, (julianday(b.check_out) - julianday(b.check_in)) * r.price AS amount
  FROM bookings b
  JOIN rooms r ON r.id = b.room_id)
SELECT id, CAST(amount AS INTEGER)
FROM a
WHERE amount > 500;

Expected result (3 rows):

idCAST(amount AS INTEGER)
3780
4910
10600

Exercise 7 · level 5

Using a CTE (WITH), compute the cost of each project (sum of hours × the developer's rate), then show the name and cost of the projects whose cost exceeds 15% of the budget.

Table projects (4 rows)
idnameclientbudgetdeadline
1AtlasAcme200002025-06-30
2BeaconBolt120002025-05-15
3CometAcme80002025-04-30
4DeltaCyan150002025-07-31
Table tasks (10 rows)
idproject_iddev_idtitlehoursstatusdone_on
111Landing page12done2025-03-10
213Data model20done2025-03-20
312Login8doingNULL
424ETL job16done2025-04-02
525CI pipeline6done2025-03-15
631Dashboard14todoNULL
733Report10done2025-04-25
842API18doingNULL
945Monitoring9todoNULL
1044Forecast22done2025-05-05
Table devs (6 rows)
idnameteamrate
1AnaWeb55
2BoWeb48
3CleoData62
4DanData58
5EveOps50
6FinnOps45
Show the hint

Topics to use: WHERE (filters), COUNT, SUM, AVG, MIN, MAX, GROUP BY, JOIN, CTEs (WITH).

Query structure:

WITH  AS (
  SELECT , SUM( * ) AS 
  FROM  
  JOIN   ON  = 
  GROUP BY )
SELECT , 
FROM  
JOIN  ON  = 
WHERE  >  * 
Show the solution
WITH c AS (
  SELECT t.project_id, SUM(t.hours * d.rate) AS cost
  FROM tasks t
  JOIN devs d ON d.id = t.dev_id
  GROUP BY t.project_id)
SELECT p.name, c.cost
FROM projects p
JOIN c ON c.project_id = p.id
WHERE c.cost > 0.15 * p.budget;

Expected result (2 rows):

namecost
Comet1390
Delta2590

Exercise 8 · level 5

Using a CTE (WITH), compute for each owner the salary received in January and in February 2025, then show the name and both amounts of the owners whose February salary is higher than the January one.

Table accounts (6 rows)
idownercityopenedkind
1AliceParis2021-03-01current
2AliceParis2022-06-15savings
3BrunoLyon2020-09-10current
4ChloeLyon2023-01-20current
5DavidNice2019-11-05savings
6EmmaNice2024-04-01current
Table transactions (14 rows)
idaccount_idmade_onamountlabel
112025-01-022500salary
212025-01-05-60groceries
312025-01-12-800rent
422025-01-15500transfer
532025-01-031900salary
632025-01-20-120groceries
732025-02-01-950rent
842025-01-252100salary
942025-02-03-45restaurant
1012025-02-022600salary
1112025-02-06-75groceries
1252025-02-1030interest
1322025-02-15500transfer
1442025-02-18-600rent
Show the hint

Topics to use: WHERE (filters), COUNT, SUM, AVG, MIN, MAX, GROUP BY, JOIN, CASE, Text and dates, CTEs (WITH).

Query structure:

WITH  AS (
  SELECT , SUM(CASE WHEN  LIKE  THEN  ELSE  END) AS , SUM(CASE WHEN  LIKE  THEN  ELSE  END) AS 
  FROM  
  JOIN   ON  = 
  WHERE  = 
  GROUP BY )
SELECT , , 
FROM 
WHERE  > 
Show the solution
WITH s AS (
  SELECT a.owner, SUM(CASE WHEN t.made_on LIKE '2025-01%' THEN t.amount ELSE 0 END) AS jan, SUM(CASE WHEN t.made_on LIKE '2025-02%' THEN t.amount ELSE 0 END) AS feb
  FROM accounts a
  JOIN transactions t ON t.account_id = a.id
  WHERE t.label = 'salary'
  GROUP BY a.owner)
SELECT owner, jan, feb
FROM s
WHERE feb > jan;

Expected result (1 row):

ownerjanfeb
Alice25002600

Exercise 9 · level 7

For each category, show the category, the name of the best-selling product by quantity and that quantity (on ties, all the tied products).

Table products (7 rows)
idnamecategoryprice
1Desk LampHome35
2Coffee MugKitchen12
3NotebookOffice6
4Office ChairOffice149
5KettleKitchen45
6CushionHome22
7StaplerOffice9
Table order_items (14 rows)
order_idproduct_idqty
111
122
241
335
321
451
562
511
624
633
741
761
852
821
Show the hint

Topics to use: WHERE (filters), COUNT, SUM, AVG, MIN, MAX, GROUP BY, JOIN, Subqueries, CTEs (WITH).

Query structure:

WITH  AS (
  SELECT , , SUM() AS 
  FROM  
  JOIN   ON  = 
  GROUP BY )
SELECT , , 
FROM 
WHERE  = (SELECT MAX() FROM   WHERE  = )
Show the solution
WITH q AS (
  SELECT p.category, p.name, SUM(oi.qty) AS s
  FROM products p
  JOIN order_items oi ON oi.product_id = p.id
  GROUP BY p.id)
SELECT category, name, s
FROM q
WHERE s = (SELECT MAX(s) FROM q q2 WHERE q2.category = q.category);

Expected result (3 rows):

categorynames
KitchenCoffee Mug8
OfficeNotebook8
HomeCushion3

Exercise 10 · level 8

Using a CTE (WITH), compute the total invoiced per client, then show client, that total and a column called size that is 'big' if the total is at least 1500, otherwise 'small'. Use CASE.

Table invoices (6 rows)
idclientissueddueamountpaid_on
1Acme2025-01-152025-02-1412002025-02-10
2Acme2025-03-012025-03-16800NULL
3Bolt2025-01-202025-03-064502025-03-01
4Bolt2025-02-252025-03-279502025-04-02
5Cyan2025-03-052025-05-04300NULL
6Cyan2024-12-102024-12-306002025-01-05
Show the hint

Topics to use: COUNT, SUM, AVG, MIN, MAX, GROUP BY, CASE, CTEs (WITH).

Query structure:

WITH  AS (
  SELECT , SUM() AS 
  FROM 
  GROUP BY )
SELECT , , CASE WHEN  >=  THEN  ELSE  END AS 
FROM 
Show the solution
WITH t AS (
  SELECT client, SUM(amount) AS total
  FROM invoices
  GROUP BY client)
SELECT client, total, CASE WHEN total >= 1500 THEN 'big' ELSE 'small' END AS size
FROM t;

Expected result (3 rows):

clienttotalsize
Acme2000big
Bolt1400small
Cyan900small

Exercise 11 · level 8

Using a CTE (WITH), compute the points of each team over all its matches, home and away (win 3 points, draw 1 point, loss 0), then show the team name and its total points, from the highest total to the lowest (on ties, alphabetical order of the name).

Table teams (5 rows)
idnamecityfounded
1Red FoxesLyon1950
2Blue OwlsParis1962
3Green BullsLille1971
4Gold HawksNantes1988
5Grey WolvesParis1990
Table matches (10 rows)
idplayed_onhome_idaway_idhome_goalsaway_goals
12025-08-021221
22025-08-033400
32025-08-095113
42025-08-102322
52025-08-164531
62025-08-171310
72025-08-232401
82025-08-243523
92025-08-304111
102025-08-315202
Show the hint

Topics to use: ORDER BY, LIMIT, COUNT, SUM, AVG, MIN, MAX, GROUP BY, JOIN, CASE, UNION, INTERSECT, EXCEPT, CTEs (WITH).

Query structure:

WITH  AS (
  SELECT  AS , CASE WHEN  >  THEN  WHEN  =  THEN  ELSE  END AS 
  FROM 
  UNION ALL SELECT , CASE WHEN  >  THEN  WHEN  =  THEN  ELSE  END
  FROM )
SELECT , SUM()
FROM 
JOIN   ON  = 
GROUP BY 
ORDER BY SUM() DESC, 
Show the solution
WITH r AS (
  SELECT home_id AS team, CASE WHEN home_goals > away_goals THEN 3 WHEN home_goals = away_goals THEN 1 ELSE 0 END AS pts
  FROM matches
  UNION ALL SELECT away_id, CASE WHEN away_goals > home_goals THEN 3 WHEN away_goals = home_goals THEN 1 ELSE 0 END
  FROM matches)
SELECT t.name, SUM(r.pts)
FROM r
JOIN teams t ON t.id = r.team
GROUP BY t.id
ORDER BY SUM(r.pts) DESC, t.name;

Expected result (5 rows, in this order):

nameSUM(r.pts)
Red Foxes10
Gold Hawks8
Blue Owls4
Grey Wolves3
Green Bulls2

Exercise 12 · level 8

Using a CTE (WITH), compute the fill rate of each flight (seats sold / capacity, in %), then show for each airline its average rate rounded to 1 decimal and the number of its flights more than 80% full.

Table flights (12 rows)
idairlineorigindestdepartsduration_minpriceseats_soldcapacity
1SkyJetCDGMAD2025-06-01 08:1012589150180
2AirNovaCDGLIS2025-06-01 11:40155120160170
3BlueWingLYSFCO2025-06-02 07:309575110150
4SkyJetMADCDG2025-06-02 18:2012095170180
5AirNovaBERCDG2025-06-03 09:05110105140160
6BlueWingNCEBER2025-06-03 13:5013014090150
7SkyJetCDGFCO2025-06-04 06:4513599175180
8AirNovaLISMAD2025-06-04 16:15756560120
9BlueWingFCOLYS2025-06-05 20:3010082130150
10SkyJetCDGBER2025-06-05 10:00105110120180
11AirNovaMADLIS2025-06-06 12:25807095120
12BlueWingLYSMAD2025-06-06 15:4011579100150
Show the hint

Topics to use: COUNT, SUM, AVG, MIN, MAX, GROUP BY, CASE, CTEs (WITH).

Query structure:

WITH  AS (
  SELECT ,  *  /  AS 
  FROM )
SELECT , ROUND(AVG(), ), SUM(CASE WHEN  >  THEN  ELSE  END)
FROM 
GROUP BY 
Show the solution
WITH r AS (
  SELECT airline, 100.0 * seats_sold / capacity AS t
  FROM flights)
SELECT airline, ROUND(AVG(t), 1), SUM(CASE WHEN t > 80 THEN 1 ELSE 0 END)
FROM r
GROUP BY airline;

Expected result (3 rows):

airlineROUND(AVG(t), 1)SUM(CASE WHEN t > 80 THEN 1 ELSE 0 END)
AirNova77.72
BlueWing71.71
SkyJet85.43

Exercise 13 · level 8

Using a CTE (WITH), compute for each day the average maximum temperature of all the cities, then show the day, the city and the gap (rounded to 1 decimal) of the readings that exceed that average by more than 3 degrees.

Table readings (15 rows)
idcitydaytemp_maxtemp_minrain_mm
1Paris2025-07-0124150
2Paris2025-07-0227170
3Paris2025-07-0322164.5
4Paris2025-07-04191412
5Paris2025-07-0523130
6Lyon2025-07-0126160
7Lyon2025-07-0229180
8Lyon2025-07-0331190
9Lyon2025-07-0424178.5
10Lyon2025-07-0522153
11Marseille2025-07-0130210
12Marseille2025-07-0232220
13Marseille2025-07-0333230
14Marseille2025-07-0429210
15Marseille2025-07-0528200
Show the hint

Topics to use: WHERE (filters), COUNT, SUM, AVG, MIN, MAX, GROUP BY, JOIN, CTEs (WITH).

Query structure:

WITH  AS (
  SELECT , AVG() AS 
  FROM 
  GROUP BY )
SELECT , , ROUND( - , )
FROM  
JOIN  ON  = 
WHERE  -  > 
Show the solution
WITH a AS (
  SELECT day, AVG(temp_max) AS m
  FROM readings
  GROUP BY day)
SELECT r.day, r.city, ROUND(r.temp_max - a.m, 1)
FROM readings r
JOIN a ON a.day = r.day
WHERE r.temp_max - a.m > 3;

Expected result (4 rows):

daycityROUND(r.temp_max - a.m, 1)
2025-07-01Marseille3.3
2025-07-03Marseille4.3
2025-07-04Marseille5
2025-07-05Marseille3.7

Exercise 14 · level 8

For each project, show its name, its budget, its cost (hours × rate, 0 without tasks), the remaining budget and the share of the budget used in % rounded to 1 decimal, from the largest share to the smallest (on ties, by name).

Table projects (4 rows)
idnameclientbudgetdeadline
1AtlasAcme200002025-06-30
2BeaconBolt120002025-05-15
3CometAcme80002025-04-30
4DeltaCyan150002025-07-31
Table tasks (10 rows)
idproject_iddev_idtitlehoursstatusdone_on
111Landing page12done2025-03-10
213Data model20done2025-03-20
312Login8doingNULL
424ETL job16done2025-04-02
525CI pipeline6done2025-03-15
631Dashboard14todoNULL
733Report10done2025-04-25
842API18doingNULL
945Monitoring9todoNULL
1044Forecast22done2025-05-05
Table devs (6 rows)
idnameteamrate
1AnaWeb55
2BoWeb48
3CleoData62
4DanData58
5EveOps50
6FinnOps45
Show the hint

Topics to use: ORDER BY, LIMIT, COUNT, SUM, AVG, MIN, MAX, GROUP BY, JOIN, NULL, COALESCE, CTEs (WITH).

Query structure:

WITH  AS (
  SELECT , , , COALESCE(SUM( * ), ) AS 
  FROM  
  LEFT JOIN   ON  = 
  LEFT JOIN   ON  = 
  GROUP BY )
SELECT , , ,  - , ROUND( *  / , )
FROM 
ORDER BY  *  /  DESC, 
Show the solution
WITH c AS (
  SELECT p.id, p.name, p.budget, COALESCE(SUM(t.hours * d.rate), 0) AS cost
  FROM projects p
  LEFT JOIN tasks t ON t.project_id = p.id
  LEFT JOIN devs d ON d.id = t.dev_id
  GROUP BY p.id)
SELECT name, budget, cost, budget - cost, ROUND(100.0 * cost / budget, 1)
FROM c
ORDER BY 1.0 * cost / budget DESC, name;

Expected result (4 rows, in this order):

namebudgetcostbudget - costROUND(100.0 * cost / budget, 1)
Comet80001390661017.4
Delta1500025901241017.3
Atlas2000022841771611.4
Beacon1200012281077210.2

Exercise 15 · level 8

Show the name of the owners whose expenses exceed 30% of their income (all accounts together), with that ratio in % rounded to 1 decimal.

Table accounts (6 rows)
idownercityopenedkind
1AliceParis2021-03-01current
2AliceParis2022-06-15savings
3BrunoLyon2020-09-10current
4ChloeLyon2023-01-20current
5DavidNice2019-11-05savings
6EmmaNice2024-04-01current
Table transactions (14 rows)
idaccount_idmade_onamountlabel
112025-01-022500salary
212025-01-05-60groceries
312025-01-12-800rent
422025-01-15500transfer
532025-01-031900salary
632025-01-20-120groceries
732025-02-01-950rent
842025-01-252100salary
942025-02-03-45restaurant
1012025-02-022600salary
1112025-02-06-75groceries
1252025-02-1030interest
1322025-02-15500transfer
1442025-02-18-600rent
Show the hint

Topics to use: WHERE (filters), COUNT, SUM, AVG, MIN, MAX, GROUP BY, JOIN, CASE, CTEs (WITH).

Query structure:

WITH  AS (
  SELECT , SUM(CASE WHEN  >  THEN  ELSE  END) AS , -SUM(CASE WHEN  <  THEN  ELSE  END) AS 
  FROM  
  JOIN   ON  = 
  GROUP BY )
SELECT , ROUND( *  / , )
FROM 
WHERE  >  AND  >  * 
Show the solution
WITH s AS (
  SELECT a.owner, SUM(CASE WHEN t.amount > 0 THEN t.amount ELSE 0 END) AS income, -SUM(CASE WHEN t.amount < 0 THEN t.amount ELSE 0 END) AS spent
  FROM accounts a
  JOIN transactions t ON t.account_id = a.id
  GROUP BY a.owner)
SELECT owner, ROUND(100.0 * spent / income, 1)
FROM s
WHERE income > 0 AND spent > 0.3 * income;

Expected result (2 rows):

ownerROUND(100.0 * spent / income, 1)
Bruno56.3
Chloe30.7

Practice with automatic checking

In SpeedQL, you write your query and it is checked straight away, on these tables and then on a hidden dataset.

Practice on the 31 “CTEs (WITH)” questions