arrow_back All articles

SQL CTE - Power up your queries!

William Golovlev · 3 min read Data Engineering
SQL CTE - Power up your queries!

I’ll admit it: I used to write horrible nested subqueries. SELECT inside SELECT inside another SELECT. I’d come back to my own code a week later and have no idea what it did.

CTEs (Common Table Expressions) fixed that for me. A CTE is a named, temporary result set that only exists for the one query you’re running. You can give each step a name, chain steps together, and read the whole thing top to bottom.

The WITH clause

A CTE starts with WITH. Name it, define what goes in it, then use it like any other table.

WITH customer_sales AS (
    SELECT customer_id, SUM(amount) as total_sales
    FROM sales
    GROUP BY customer_id
)
SELECT * FROM customer_sales

Here’s where it pays off. Say you want customers who spent more than average. Without a CTE you’d nest a grouped subquery inside the WHERE clause. With one:

WITH customer_sales AS (
    SELECT customer_id, SUM(amount) as total_sales
    FROM sales 
    GROUP BY customer_id
),
average_sales AS (
    SELECT AVG(total_sales) as avg_amount FROM customer_sales
)
SELECT c.customer_id, c.total_sales
FROM customer_sales c, average_sales a
WHERE c.total_sales > a.avg_amount

Each step has a name, so you can tell what it does without tracing parentheses.

Chaining CTEs

You can define several CTEs in one WITH, separated by commas, and each one can use the ones above it. It works like a small pipeline: totals first, then averages of those totals, then the comparison.

For example, finding products that beat their regional average:

WITH product_totals AS (
    SELECT product, region, SUM(amount) as total_sales
    FROM sales
    GROUP BY product, region
),
regional_averages AS (
    SELECT region, AVG(total_sales) as avg_sales
    FROM product_totals
    GROUP BY region
)
SELECT p.product, p.total_sales, r.avg_sales
FROM product_totals p
JOIN regional_averages r ON p.region = r.region
WHERE p.total_sales > r.avg_sales

One job per CTE. No nesting.

A debugging tip: when the final result looks wrong, swap the last SELECT for SELECT * FROM product_totals and check each step on its own. That’s much harder to do with nested subqueries.

Recursive CTEs

A recursive CTE references itself. It’s the tool for hierarchical data like org charts or category trees.

It has two parts: the anchor (the starting row) and the recursive part, which keeps running until it stops finding new rows.

Here’s how to trace someone’s management chain:

WITH RECURSIVE management_chain AS (
    -- Start with the employee
    SELECT employee_id, manager_id, employee_name, 1 as level
    FROM employees 
    WHERE employee_name = 'Alice'
    
    UNION ALL
    
    -- Find their manager, then their manager's manager, etc.
    SELECT e.employee_id, e.manager_id, e.employee_name, level + 1
    FROM employees e
    JOIN management_chain m ON e.employee_id = m.manager_id
)
SELECT * FROM management_chain

This climbs the org chart until it hits someone with no manager (the big boss).

One gotcha: PostgreSQL, MySQL and SQLite want WITH RECURSIVE, but SQL Server just uses WITH. Same idea, different keyword.

Where to start

Replace one nested subquery with a CTE. Then try chaining two. I only reach for the recursive kind once or twice a year, but the basic patterns are the ones I use constantly, and they’re why I can still read my own queries six months later.

#SQL#Database#CTE#Data Analysis#Tutorial