Skip to content

CTEs (WITH) and Subqueries

CTEs (Common Table Expressions) improve readability.

  • Break complex queries into steps
  • Reuse derived results

Example: revenue by country for paying users

Section titled “Example: revenue by country for paying users”
CTE example
WITH paying_users AS (
  SELECT user_id, country
  FROM users
  WHERE plan != 'free'
),
revenue_by_user AS (
  SELECT user_id, SUM(amount) AS revenue
  FROM orders
  GROUP BY user_id
)
SELECT
  u.country,
  SUM(r.revenue) AS revenue
FROM paying_users u
JOIN revenue_by_user r ON r.user_id = u.user_id
GROUP BY u.country
ORDER BY revenue DESC;

Subqueries are inline “nested” queries.

Subquery example
SELECT *
FROM (
  SELECT user_id, SUM(amount) AS revenue
  FROM orders
  GROUP BY user_id
) t
WHERE t.revenue >= 1000;
  • Prefer CTEs for multi-step analytics.
  • Keep each CTE small and well-named.

Think of each WITH name AS (...) block as a labeled step in a pipeline. Later steps (and the final SELECT) can reference any earlier CTE by name, the same way a variable in a script holds a value you compute once and reuse.

diagram CTE pipeline mermaid
Each WITH block is a named, reusable step; later steps and the final SELECT can reference any earlier CTE by name.

Exercise 3 – Filter with a subquery in WHERE

Section titled “Exercise 3 – Filter with a subquery in WHERE”

Date and Time Analytics in SQL applies these same aggregation and window patterns to the most common analytics dimension of all: time.

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading