What is a CTE?
- SQL course
- Advanced
- Lesson 1/81
- 4 min
Write a named subquery with WITH.
What is a CTE?
A CTE (Common Table Expression) is a temporary result set. Defined with WITH.
WITH active AS (
SELECT * FROM customers WHERE status = 'active'
)
SELECT * FROM active;This query makes active customers a temporary table.
WITH defines a temporary result set (CTE) named active; the query after it uses it like a table. All columns are selected from active.
What is a CTE? — details
A CTE makes a query readable. It replaces subqueries and can be referenced multiple times.
For example, if you need the same active-customer list in both an orders and an invoices report, you define it once as a CTE and refer to it by name twice.
Practice What is a CTE?
Define a CTE named active and SELECT from it.
Starter code
-- write CTE
WITHSample solution
WITH active AS (
SELECT * FROM customers WHERE status = 'active'
)
SELECT * FROM active;Expected output
id name status 1 Ayşe active
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which keyword starts a CTE?
- WITH Correct answer
- AS
- FROM
- SELECT
Explanation: A CTE starts with WITH.
2 Add WITH
____ active AS (SELECT * FROM customers WHERE status = 'active')
SELECT * FROM active;
WITH active AS (SELECT * FROM customers WHERE status = 'active')
SELECT * FROM active;
Explanation: A CTE definition starts with the WITH keyword, followed by the CTE name and AS.
3 What is a CTE: match the terms
| Term | Meaning |
|---|---|
CTE |
temporary table |
WITH |
definition |
AS |
name |
readable |
clean |