Subquery & CTE vocabulary

  • WITH name AS (...) — CTE: names a subquery; readable and reusable within the query
  • EXISTS (subquery) — true if subquery returns any row; stops at first match
  • IN (subquery) — matches if value equals any row returned; watch out for NULLs with NOT IN
  • WITH RECURSIVE — for hierarchical data: org charts, trees, graphs
  • CTE vs subquery: same result; CTE wins on readability for complex logic

Question 0 of 5

Read this CTE and describe what it does:

WITH recent_orders AS (
  SELECT user_id, COUNT(*) AS cnt
  FROM orders
  WHERE created_at >= NOW() - INTERVAL '7 days'
  GROUP BY user_id
)
SELECT u.email, ro.cnt
FROM users u
JOIN recent_orders ro ON u.id = ro.user_id
WHERE ro.cnt >= 3;