SQL CTE (WITH Clause) Explained with Examples

A CTE names a result with WITH so the main query can read it like a table. Examples, chaining several CTEs, and CTE vs subquery vs temporary table.

In this chapter

WITH names a table that lives for one query

CTEs (WITH clause): common questions

What is the difference between a CTE and a subquery?

Both describe a temporary result. A CTE has a name, can be referenced several times and can be recursive, which usually makes long queries easier to read.

Is a CTE stored in the database?

No. It exists only while that one statement runs.

More on WITH and CTEs

Keep learning

Overview

chapters · subqueries and ctes WITH names a table that lives for one query A CTE is that named result. MySQL builds it, the rest of the query reads it, and then it is gone. The name is a variable for SQL.

1. Click through a query that has a named step

Goal: the priciest product in each category. The query has two parts: the WITH part builds a temporary table called ranked, and the final SELECT reads from it. Press Next to run them one at a time, then switch to RANK() to see what happens when two products cost the same.

2. Same answer as a subquery, easier to read

Subquery: start in the middle WITH: read top to bottom The result is identical. A name can also be used twice in one query (a subquery would have to be pasted twice), and one name can build on an earlier one.

4. What a CTE is not

Not storedIt is not a table or a view. Nothing is saved after the statement ends. Not always built firstThe database may merge it into the main query or build it once as a temporary result. Do not count on either for speed. One statement onlyThe name vanishes after the semicolon. To reuse it later, make a view. VersionMySQL 8.0+ and MariaDB 10.2+. MySQL 5.7 has no WITH, so use a derived table there. ! Real-life check

More courses

  • Jobs, linked to lessons — Browse jobs where every requirement links to the chapter that teaches it. See how ready you are, how long the gap takes to close, and which listings look stale.
  • Match a job post to courses — Paste a job post. Each skill is matched to a track here and put in learning order, foundations first.
  • React patterns from open source — Patterns extracted from Material UI, Radix, React Aria, React Hook Form, Redux Toolkit, TanStack, and Next.js — not slides about hooks.
  • System Design — Core concepts first (SQL vs NoSQL, CAP, indexing, replication, sharding), then designs grouped by what carries them: the database, Redis, Kafka, or many services.
  • NestJS: build a real API — One ticket-booking API, built in order: a plain Node server first, then NestJS modules, validation, a real database, and the features real clients lean on.
  • Microservices — Microservice patterns one diagram at a time: how to split a monolith, how services talk, and how data stays consistent without distributed transactions.
  • Kafka — A beginner-to-senior path through event logs, reliable delivery, production operations, and disaster recovery.
  • AI engineering for software engineers — Eight free reads, in order, for software engineers moving into AI: when to build an agent, how to build one, how to test it, and how the model works underneath.
  • Frontend system design — How a UI is sliced when it is a product, not a page: ownership of state, cache, routes, and what happens when the network lies.
  • TypeScript in depth — The type system as a design tool. Inference, narrowing, generics, and the errors that mean the model is wrong — not a catalog of utility types.
  • CSS in depth — See the box, then the page. Visual chapters from the box model through Flexbox surprises, Grid, selectors, and units, then backgrounds, shapes, and visual effects, each with a playground.
  • Accessibility — Foundations first (WCAG in plain words, semantic HTML, lists, alt text), then hands-on HTML labs, a full pass of WAI-ARIA 1.3, and a final fix-the-page challenge.
  • Docker — What an image is, why layers cache, and how containers find each other on a network.
  • Redis — Fifteen Redis patterns, one picture each: cache, session, lock, counter, rate limiter, queue, and when Redis is the wrong tool.
  • Kubernetes — Kubernetes from zero to operators: why it exists, Pods, Deployments and Services, then configuration, networking, storage, scheduling, scaling and security.
  • AWS — AWS networking in plain English. A VPC is a gated housing society: streets are subnets, the Internet Gateway is the main gate, and a route table is the signboard.
  • Networking: the NetRoute game — NetRoute is a packet logistics game. You wire up computers, switches, routers, firewalls and gateways, set each device, and watch glowing packets travel. If a packet gets dropped, the game shows you which header field was wrong.