Common Table Expressions (CTEs) are a powerful feature in SQL that allow you to define named subqueries within a larger query. They provide a way to simplify complex queries, improve readability, and enhance query performance.
CTEs act as temporary named result sets that you can reference within a SELECT, INSERT, UPDATE, DELETE, or MERGE statement. They are particularly useful for breaking down complex queries into more manageable parts.
The basic syntax for a CTE is as follows:
WITH cte_name AS (
SELECT column1, column2
FROM table
WHERE condition
)
SELECT *
FROM cte_name;
Let's look at a simple example that uses a CTE to calculate the average salary for each department:
WITH dept_avg_salary AS (
SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id
)
SELECT e.employee_name, e.salary, d.avg_salary
FROM employees e
JOIN dept_avg_salary d ON e.department_id = d.department_id;
CTEs are particularly useful for handling hierarchical or tree-structured data. Here's an example of a recursive CTE that traverses an employee hierarchy:
WITH RECURSIVE employee_hierarchy AS (
SELECT employee_id, manager_id, name, 1 AS level
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT e.employee_id, e.manager_id, e.name, eh.level + 1
FROM employees e
JOIN employee_hierarchy eh ON e.manager_id = eh.employee_id
)
SELECT *
FROM employee_hierarchy
ORDER BY level, employee_id;
To further enhance your understanding of SQL and query optimization, consider exploring these related topics:
By mastering Common Table Expressions, you'll be able to write more efficient and readable SQL queries, especially when dealing with complex data relationships or hierarchical structures.