Overview
This lesson will teach about Common Table Expression(CTE), also named a temporary result set. We will also see the WITH keyword used to define CTE in detail.
What is Common Table Expression?
A Common Table Expression (CTE) is a named temporary result set that can be referenced within a SELECT, INSERT, UPDATE, or DELETE statement. It is similar to a derived table or subquery but can be referenced multiple times within a single query.
CTEs are defined using the WITH keyword, followed by a comma-separated list of named queries. Each named query consists of a name, followed by the SELECT statement defining the result set.
Why is Common Table Expression Used?
Some common scenarios where you might want to use a CTE:
Overall, CTEs are a useful tool in SQL for simplifying queries, improving performance, and making code more maintainable.
Syntax of CTE
The syntax of a Common Table Expression (CTE) in SQL is as follows:
WITH cte_name (column1, column2, column3, ...) AS (
SELECT column1, column2, column3, ...
FROM table_name
WHERE condition
)
SELECT ...
FROM cte_name
WHERE condition;
Here, cte_name is the CTE's name, followed by a list of column names (optional). The SELECT statement inside the parentheses defines the CTE's result set. It can use any valid SQL statement, including joins and subqueries. Finally, the CTE is referenced in the main query using its name.
It's important to note that the CTE can only be referenced in the query that immediately follows its definition. Additionally, the CTE is only visible within the scope of the SELECT, INSERT, UPDATE, or DELETE statement in which it is defined. Once the statement is executed, the CTE is discarded.
CTEs can be used to simplify complex queries and improve query performance by reducing the need for subqueries and temporary tables.
Example:
We can take the example of an employee's table that includes the employee ID, first name, last name, and salary of all employees.
Employee id | First Name | Last Name | Salary |
---|---|---|---|
1 | John | Doe | 55000.00 |
2 | Jane | Smith | 60000.00 |
3 | Bob | Johnson | 45000.00 |
4 | Alice | Lee | 70000.00 |
5 | Mike | Brown | 80000.00 |
For example, the following CTE defines a result set that includes the employee ID, first name, last name, and salary of all employees who earn more than $50,000 per year:
WITH high_earners AS (
SELECT employee_id, first_name, last_name, salary
FROM employees
WHERE salary > 50000
)
SELECT *
FROM high_earners;
In this example, the CTE is named "high_earners" and is defined using a SELECT statement that filters the "employees" table based on the salary column. The CTE is then referenced in the main query using its name, which allows the result set to be used in further operations.
CTEs are particularly useful when a query requires multiple steps or when the same subquery needs to be referenced multiple times within a single query. They can also make complex queries easier to read and understand by breaking them down into smaller, more manageable parts.
It is important to note that CTEs are only visible within the query that defines them and are discarded as soon as the query is executed. They are not stored in the database or persisted in any way.
Types of CTE:
WITH RECURSIVE cte_employee AS (
SELECT employee_id, name, manager_id, 1 AS level
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT e.employee_id, e.name, e.manager_id, c.level + 1
FROM employees e
JOIN cte_employee c ON c.employee_id = e.manager_id
)
SELECT employee_id, name, manager_id, level
FROM cte_employee;
SELECT department_id, AVG(salary) AS avg_salary
FROM (
SELECT employee_id, salary, department_id
FROM employees
) AS subquery
GROUP BY department_id;
WITH pivot_cte AS (
SELECT product, year, quarter, SUM(amount) AS total
FROM sales
GROUP BY product, year, quarter
)
SELECT product,
MAX(CASE WHEN year = 2020 AND quarter = 'Q1' THEN total END) AS q1_2020,
MAX(CASE WHEN year = 2020 AND quarter = 'Q2' THEN total END) AS q2_2020,
MAX(CASE WHEN year = 2020 AND quarter = 'Q3' THEN total END) AS q3_2020,
MAX(CASE WHEN year = 2020 AND quarter = 'Q4' THEN total END) AS q4_2020,
MAX(CASE WHEN year = 2021 AND quarter = 'Q1' THEN total END) AS q1_2021,
MAX(CASE WHEN year = 2021 AND quarter = 'Q2' THEN total END) AS q2_2021
FROM pivot_cte
GROUP BY product;
Best Practices:
Conclusion
A Common Table Expression (CTE) is a named temporary result set that can be referenced within a SELECT, INSERT, UPDATE, or DELETE statement. It is defined using the WITH keyword and is useful for recursive queries, subquery replacement, and code reusability.
Key Takeaways
Quiz
Answer:b. A named temporary result set that can be referenced within a SELECT, INSERT, UPDATE, or DELETE statement.
Answer: b. To simplify queries, improve performance, and make code more maintainable.
Answer: d. WITH.
Answer: b. No. A CTE can only be referenced within the query that immediately follows its definition.
Answer:a. Recursive queries, subquery replacement, and code reusability.
Answer: b. No. A CTE is only visible within the query that defines it, and it is discarded as soon as the query is executed.
Top Tutorials
Related Articles