SQL•CTEs
SQL Common Table Expressions (WITH Clause / CTEs)
CTEs define named temporary result sets, replacing hard-to-read nested subqueries.
Syntax
WITH regional_sales AS (SELECT ...) SELECT * FROM regional_sales;
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| WITH name AS () | CTE Definition | Creates temporary named view accessible in main query. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing SQL locally:
CREATE TABLE transactions (
id INTEGER PRIMARY KEY,
region TEXT,
amount REAL
);
INSERT INTO transactions VALUES
(1, 'NA', 500.00),
(2, 'EU', 300.00),
(3, 'NA', 700.00),
(4, 'EU', 450.00),
(5, 'AP', 200.00);
-- Using CTE to compute regional totals and filter top regions
WITH RegionalTotals AS (
SELECT
region,
SUM(amount) AS total_revenue
FROM transactions
GROUP BY region
)
SELECT region, total_revenue
FROM RegionalTotals
WHERE total_revenue >= 500.00
ORDER BY total_revenue DESC;Expected Output:
region total_revenue ------ ------------- NA 1200.0 EU 750.0
How It Works: Step-by-Step
- Lines 7-13: Populates regional transactions.
- Lines 16-22: WITH RegionalTotals builds intermediate aggregated table.
- Lines 23-26: Outer query filters and sorts CTE output cleanly.
Key Concepts
- CTEs dramatically improve SQL readability compared to nested FROM (SELECT ...) derived tables.
- Multiple CTEs can be defined in a single WITH statement separated by commas.
Common Mistake: Repeating the WITH keyword when chaining multiple CTEs
Only write WITH once; separate subsequent CTEs with commas.
❌ Incorrect
WITH cte1 AS (...) WITH cte2 AS (...) // Syntax Error!
✅ Correct
WITH cte1 AS (...), cte2 AS (...)
Related SQL Tutorials & Compiler
SQL INNER JOIN and LEFT JOIN: Combining Relational Tables
Combine related data across tables using INNER JOIN and LEFT OUTER JOIN with ON keys.
SQL Subqueries: Correlated and Non-Correlated Subqueries
Nest queries within queries in WHERE, FROM, and SELECT clauses.
SQL Dynamic Transactional CASE WHEN Metrics Query Logic
Implement dynamic transactional business logic and classification metrics in SQL using CASE WHEN expressions.
SQL Online Compiler
Open in Compilra IDE
Run and test SQL on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.