CTE Introduction
Learn about Common Table Expressions (CTE) in SQL Server, their syntax, uses, advantages, and practical examples.
What is a CTE?
CTE stands for Common Table Expression. It is a temporary named result set that can be referenced within a single SQL statement.
A CTE is defined using the WITH keyword and makes complex SQL queries easier to read and maintain.
CTEs are commonly used with SELECT, INSERT, UPDATE and DELETE statements.
Why Use CTE?
CTEs are useful when a SQL query becomes complex and needs to be divided into smaller logical parts.
- Makes complex queries easier to understand.
- Improves query readability.
- Helps organize query logic.
- Useful for recursive queries.
- Can simplify queries involving joins and aggregations.
CTE Syntax
WITH CTE_Name AS
(
SELECT column1, column2
FROM TableName
WHERE condition
)
SELECT *
FROM CTE_Name;
Syntax Explanation
| Part | Explanation |
|---|---|
| WITH | Starts the Common Table Expression. |
| CTE_Name | Name given to the CTE. |
| AS | Defines the query that produces the CTE result. |
| SELECT | Retrieves the required data for the CTE. |
| FROM | Specifies the source table. |
Simple CTE Example
Consider an Employees table containing employee information.
WITH HighSalaryEmployees AS
(
SELECT EmployeeId,
EmployeeName,
Department,
Salary
FROM Employees
WHERE Salary > 50000
)
SELECT *
FROM HighSalaryEmployees;
How Does a CTE Work?
- The WITH keyword starts the CTE.
- A name is assigned to the CTE.
- The query inside the parentheses creates the result set.
- The main query references the CTE using its name.
- The CTE is available only for the statement that follows it.
CTE with WHERE Clause
A CTE can contain filtering conditions using the WHERE clause.
WITH PuneEmployees AS
(
SELECT EmployeeId,
EmployeeName,
City
FROM Employees
WHERE City = 'Pune'
)
SELECT *
FROM PuneEmployees;
CTE with Query Operations
The CTE result can be used by the main query for further filtering, sorting, joining, or aggregation.
WITH EmployeeData AS
(
SELECT EmployeeId,
EmployeeName,
Salary
FROM Employees
)
SELECT *
FROM EmployeeData
WHERE Salary > 60000
ORDER BY Salary DESC;
Advantages of CTE
- Improves SQL query readability.
- Makes complex queries easier to maintain.
- Helps divide complex query logic into logical sections.
- Supports recursive queries.
- Can be used with multiple SQL statement types.
Important Points
- CTE starts with the WITH keyword.
- A CTE has a name.
- The CTE definition is enclosed inside parentheses.
- The statement following the CTE uses the CTE result.
- CTEs are temporary and are not permanent database objects.
Summary
A Common Table Expression (CTE) is a temporary named result set created using the WITH keyword.
CTEs are useful for making complex SQL queries more readable and maintainable. They are also useful for joins, filtering, aggregation and recursive operations.