Database Management
- How to Create a Table
- How to Drop a Table
- How to Rename a Table
- How to Truncate a Table
- How to Duplicate a Table
- How to Add a Column
- How to Drop a Column
- How to Rename a Column
- How to Add a Default Value to a Column
- How to Remove a Default Value to a Column
- How to Add a NOT NULL Constraint
- How to Remove a NOT NULL Constraint
- How to Drop an Index
- How to Create a View
- How to Drop a View
- How to Alter Sequence
- How to Create an Index
Dates and Times
Analysis
- How to use SQL Pivot
- How to Query JSON Object
- How to Calculate Cumulative Sum/Running Total
- How to Have Multiple Counts
- How to Write a Case Statement
- How to Use Coalesce
- How to Avoid Gaps in Data
- How to Import a CSV
- How to Get First Row Per Group
- How to Compare Two Values When One is NULL
- How to Write a Common Table Expression
- How to Calculate Percentiles
- How to Do Type Casting
How to Write a Common Table Expression in SQL Server
Common Table Expressions (CTEs) are a powerful SQL Server feature that allows you to simplify complex queries. A CTE provides a temporary result set that can be referenced within a SELECT, INSERT, UPDATE, or DELETE statement. It makes your queries more readable and modular.
Syntax of a Common Table Expression
The basic syntax for a CTE in SQL Server is as follows:
WITH CTE_Name (Column1, Column2, ...) AS ( SELECT Column1, Column2, ... FROM TableName WHERE condition ) SELECT * FROM CTE_Name;
Example of Using a CTE
Let’s say you have a table of employees and their managers, and you want to find all employees who report directly to a specific manager. Here’s how you can write this query using a CTE:
WITH EmployeeCTE AS ( SELECT EmployeeID, Name, ManagerID FROM Employees WHERE ManagerID = 1 ) SELECT EmployeeID, Name FROM EmployeeCTE;
This CTE selects all employees that report to the manager with ID 1, and then the final SELECT statement retrieves those employees' IDs and names.
Advantages of Using CTEs
- Improved Readability: CTEs break down complex queries into simpler parts.
- Reusable: You can refer to a CTE multiple times within the same query.
- Recursion Support: CTEs can be recursive, making them ideal for hierarchical data such as organizational charts.
Recursive CTE Example
Here’s an example of how to use a recursive CTE to find all subordinates of a manager:
WITH RecursiveCTE AS ( SELECT EmployeeID, Name, ManagerID FROM Employees WHERE ManagerID = 1 UNION ALL SELECT e.EmployeeID, e.Name, e.ManagerID FROM Employees e INNER JOIN RecursiveCTE r ON e.ManagerID = r.EmployeeID ) SELECT EmployeeID, Name FROM RecursiveCTE;
This recursive CTE will retrieve all employees who report to manager 1, as well as all employees under those employees, in a hierarchical manner.
Conclusion
Common Table Expressions (CTEs) are an excellent tool for simplifying your SQL queries, improving readability, and enhancing performance. By using them for complex subqueries or recursive queries, you can write more modular and maintainable SQL code.