#1 India's Top IT Training Institute

On Demand Courses

9 programs

×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →

SQL CTE Guide
PDF Downloads

Download the SQL CTE guide PDF from Uncodemy: WITH clause syntax, multiple and recursive CTEs, readability tips and tested examples.

Prepared by: Uncodemy trainer team Reviewed by: Uncodemy Last reviewed: 27 Oct 2026
Writing a CTE Query
1
Define the grainWrite down what one row of the final result means.
2
One CTE per stepEach logical step gets its own clearly named CTE.
3
Run each CTE aloneCheck its row count before moving on.
4
Join in the final selectBring the CTEs together in the main query.
5
Cross-check totalsCompare with a simple independent query.

Quick Answer

This page offers Uncodemy's SQL CTE guide as a PDF download. A common table expression, or CTE, is a named temporary result defined with WITH that you can use in the query that follows. CTEs make complex queries readable by breaking them into steps. The guide covers syntax, chaining, recursive CTEs, comparisons with subqueries and common mistakes.

Download

SQL CTE Guide PDF

Download the guide below. Each download is its own file, and everything in it is also explained on this page.

1 PDF Available
PDF 01 Main Guide

SQL CTE Guide

WITH clause syntax, chaining several CTEs, recursive CTEs, CTE vs subquery vs view vs temporary table, common mistakes and practice tasks, with examples on a customers and orders dataset.

PDF Free Oct 2026
Download PDF

A short form asks for your details before the download starts. Your details are used only to share study material and course information.

01

What is a CTE?

A common table expression is a named result set that exists only for the duration of one statement. You define it with the WITH keyword before the main query, give it a name and a query, and then refer to it as if it were a table. The main benefit is clarity. Instead of nesting a subquery inside a subquery, you write each step as a named block and read the query from top to bottom like a recipe.

CTEs do not store data permanently and, in most databases, they do not by themselves make a query faster; their value is in readability and in enabling recursion.

The examples use these tables: customers(customer_id, name, city, signup_date), orders(order_id, customer_id, order_date, status, order_total), order_items(order_id, product_id, quantity, unit_price) and products(product_id, product_name, category). Dates are text in YYYY-MM-DD form, so the examples run in SQLite and need small changes in other databases.

02

Basic syntax

Revenue per customer calculated in a CTE, then filtered in the main query.

WITH customer_revenue AS (
  SELECT customer_id, SUM(order_total) AS revenue
  FROM orders
  WHERE status <> 'cancelled'
  GROUP BY customer_id
)
SELECT customer_id, revenue
FROM customer_revenue
WHERE revenue > 500
ORDER BY revenue DESC;
03

Chaining several CTEs

You can define several CTEs one after another, separated by commas, and later ones can use earlier ones. This is where CTEs shine: each step does one thing, has a clear name and can be checked on its own by running the query up to that point. Name steps by what they contain, such as monthly_revenue or first_orders, rather than by number, so the query documents itself. If a step is wrong, you can select from that CTE alone to inspect it before moving on.

Two chained CTEs

Monthly revenue first, then the change from the previous month using a window function in the second step.

WITH monthly AS (
  SELECT strftime('%Y-%m', order_date) AS month,
         SUM(order_total) AS revenue
  FROM orders
  WHERE status <> 'cancelled'
  GROUP BY strftime('%Y-%m', order_date)
),
with_change AS (
  SELECT month,
         revenue,
         LAG(revenue) OVER (ORDER BY month) AS prev_revenue
  FROM monthly
)
SELECT month,
       revenue,
       prev_revenue,
       ROUND((revenue - prev_revenue) * 100.0 / prev_revenue, 1) AS pct_change
FROM with_change
ORDER BY month;
04

Recursive CTEs

A recursive CTE refers to itself. It has two parts joined by UNION ALL: an anchor query that returns the starting rows and a recursive query that uses the CTE's own previous result to produce the next rows. The recursion stops when the recursive part returns no new rows. Typical uses are generating a series of dates or numbers and walking hierarchies such as an organisation chart or a category tree.

Always make sure the recursion terminates, for example by moving toward an end condition, because a mistake can create an endless loop; many databases enforce a maximum recursion depth.

A recursive CTE that generates dates

Produces every date in a range so you can show days with zero orders. Syntax for generating dates differs a little between databases.

WITH RECURSIVE days AS (
  SELECT DATE('2026-09-01') AS d
  UNION ALL
  SELECT DATE(d, '+1 day') FROM days WHERE d < '2026-09-07'
)
SELECT days.d AS day,
       COALESCE(COUNT(o.order_id), 0) AS orders
FROM days
LEFT JOIN orders o ON o.order_date = days.d AND o.status <> 'cancelled'
GROUP BY days.d
ORDER BY days.d;
05

CTE, subquery, view and temporary table

All four hold an intermediate result, but they differ in how long it lives and what each one is best used for.

Option Lifetime Best for
CTE One statement Readable multi-step queries and recursion
Subquery One statement Short, single-use logic
View Stored in the database Reusable logic shared by many queries
Temporary table Session or until dropped Large intermediate results reused several times
06

When to use a CTE — and what to avoid

When to use a CTE

  • The query has more than one logical step.
  • The same intermediate result is referred to more than once.
  • You need recursion for dates or hierarchies.
  • A teammate will have to read and maintain the query.

Common CTE mistakes

  • Assuming CTEs are always faster: in many databases they behave like inline subqueries, and behaviour differs by engine and version.
  • Giving vague names like a, b and c.
  • Forgetting the comma between several CTEs, or placing it after the last one.
  • Using a CTE where a simple join is clearer.
  • Infinite recursion from a missing end condition.
07

A checklist for writing a CTE query

  1. Write down the grain of the final result.
  2. Create one CTE per logical step and name it clearly.
  3. Run each CTE separately and check its row count.
  4. Join the CTEs in the final select.
  5. Compare the final totals with a simple independent query.
08

Practice tasks

Try these three tasks on your own data.

  1. Write a CTE that returns the top five customers by revenue and join it to their cities.
  2. Chain two CTEs to compute each customer's first order date and then count customers by first order month.
  3. Write a recursive CTE that lists every date in a month and use it to report days with zero orders.

Explain each query aloud in plain words; if you can, you have understood it.

Learn with a trainer

Want to write SQL the way analysts do at work? Explore Uncodemy's Data Analytics course and learn from industry trainers.

View Course
About these PDFs: These PDFs are study material for learning and revision. They are not a certificate, a degree or a promise of a job, and technology changes, so check official documentation for the latest details. Spot an error? Write to info@uncodemy.com and the trainer team will review it.
FAQ

Frequently Asked Questions

What is a CTE in SQL?
A common table expression is a named temporary result defined with WITH that you can reference in the following query, used to make complex queries readable.
What is the difference between a CTE and a subquery?
Both define intermediate results for one statement. A CTE is named, can be referenced several times and supports recursion, while a subquery is nested inline.
Is a CTE faster than a subquery?
Not necessarily. Performance depends on the database and its optimiser. CTEs mainly improve readability.
What is a recursive CTE?
A CTE that refers to itself, with an anchor query and a recursive part joined by UNION ALL, used for generating series or traversing hierarchies.
Can I use multiple CTEs in one query?
Yes. Define them one after another separated by commas, and later ones can use earlier ones.
Are these PDFs free to download?
Yes, the SQL CTE guide PDF is free. A short form asks for your details before the download starts.