SQL
CTE
Common Table Expressions.
By EZ4Code Team
ctewith
Code
-- Basic CTE
WITH active_users AS (
SELECT id, name FROM users WHERE active = true
),
recent_orders AS (
SELECT user_id, COUNT(*) AS order_count
FROM orders
WHERE order_date >= '2024-01-01'
GROUP BY user_id
)
SELECT au.name, COALESCE(ro.order_count, 0) AS orders
FROM active_users au
LEFT JOIN recent_orders ro ON au.id = ro.user_id
ORDER BY orders DESC;
-- Multiple CTE references
WITH base AS (
SELECT dept, salary FROM employees
),
stats AS (
SELECT dept, AVG(salary) AS avg_sal FROM base GROUP BY dept
)
SELECT * FROM stats WHERE avg_sal > 50000;Explanation
CTE defines temporary result sets with WITH, improving readability and maintainability of complex queries.
More SQL Snippets
SELECT with WHERE and ORDER BY
Filter, sort, and limit rows with SELECT, WHERE, and ORDER BY in SQL.
JOIN Queries
Multi-table join queries.
Subqueries
Nested queries.
Window Functions
Ranking and aggregate window functions.
Aggregate Functions
GROUP BY and HAVING.
Recursive Queries
Query hierarchical data with recursive CTE.