Masting Common Table Expressions in SQL Server

Masting Common Table Expressions in SQL Server

As per my experience ,we describes the SQL Common Table Expressions (CTEs). It includes their syntax, benefits, and various applications. It presents a variety of types of CTEs, and illustrates with practical examples their strength. A CTE is a temporary table defined in an SQL statement. CTEs can be presented in the FROM clause and provide the query with an easy name. That name can be used again in the query. 

What are CTEs?

A Common Table Expression ( CTE ) is a named result set that functions as a temporary named result set that you may refer to within a single query.


SQL-statement, such as SELECT, INSERT, UPDATE, or DELETE statement. CTEs are not storage
They are all objects; they exist in the course of the query running. The WITH clause defines them.
and they are capable of simplifying complex queries and simplifying the maintenance of queries. 

Syntax of a CTE

The basic syntax of a CTE is as follows:
 
  1. WITH CTE_Name AS (  
  2. - CTE Definition  
  3. (SELECT statement) )  
  4. - Main Query (using the CTE)  
  1. WITH CTE_Name AS: This introduces the CTE and assigns it a name (CTE_Name).
  2.  (-- CTE Definition): This is the SELECT statement that defines the result set of the CTE.
  3. -- Main Query: This is the main query that uses the CTE as if it were a regular table or view. 

What is the advantage of CTEs?



  • CTEs ( Common Table Expressions ) shorten and simplify the long queries.
  • A CTE may be used multiple times and thus reduces copy-and-paste programming.
  • The CTEs can be used in recursive queries, which is a handy option to deal with hierarchical data.
  • CTEs also serve as a place to store intermediate results, and that makes the main logic easier.

Examples 

Here are the SQL Server queries to create the Employees and Departments tables and insert the sample data you provided: 
  1. -- Create Departments table  
  2. CREATE TABLE Departments (  
  3.     DepartmentID INT PRIMARY KEY,  
  4.     DepartmentName VARCHAR(50),  
  5.     Location VARCHAR(50)  
  6. );  
  7.   
  8. -- Create Employees table  
  9. CREATE TABLE Employees (  
  10.     EmployeeID INT PRIMARY KEY,  
  11.     FirstName VARCHAR(50),  
  12.     LastName VARCHAR(50),  
  13.     DepartmentID INT,  
  14.     Salary INT,  
  15.     FOREIGN KEY (DepartmentID) REFERENCES Departments(DepartmentID)  
  16. );   
  1. -- Insert into Departments  
  2. INSERT INTO Departments (DepartmentID, DepartmentName, Location) VALUES  
  3. (10, 'Sales''New York'),  
  4. (20, 'Marketing''London'),  
  5. (30, 'Engineering''San Francisco');  
  6.   
  7. -- Insert into Employees  
  8. INSERT INTO Employees (EmployeeID, FirstName, LastName, DepartmentID, Salary) VALUES  
  9. (1, 'John''Doe', 10, 60000),  
  10. (2, 'Jane''Smith', 20, 75000),  
  11. (3, 'Michael''Johnson', 10, 55000),  
  12. (4, 'Emily''Brown', 30, 80000),  
  13. (5, 'David''Wilson', 20, 70000),  
  14. (6, 'Sarah''Garcia', 10, 62000),  
  15. (7, 'Robert''Martinez', 30, 85000);  
 
  1. ------Departments Rable OutPut  
  2. DepartmentID DepartmentName                                     Location  
  3. ------------ -------------------------------------------------- --------------------------------------------------  
  4. 10           Sales                                              New York  
  5. 20           Marketing                                          London  
  6. 30           Engineering                                        San Francisco  
 
  1. ------Employees Rable OutPut  
  2. EmployeeID  FirstName                                          LastName                                           DepartmentID Salary  
  3. ----------- -------------------------------------------------- -------------------------------------------------- ------------ -----------  
  4. 1           John                                               Doe                                                10           60000  
  5. 2           Jane                                               Smith                                              20           75000  
  6. 3           Michael                                            Johnson                                            10           55000  
  7. 4           Emily                                              Brown                                              30           80000  
  8. 5           David                                              Wilson                                             20           70000  
  9. 6           Sarah                                              Garcia                                             10           62000  
  10. 7           Robert                                             Martinez                                           30           85000  
  Simple CTE
A basic result set can be defined in a simple CTE that can be utilized in the initial query.
 
Example: Get all the employees in the Sales department. 
  1. ;WITH SalesEmployees AS 
  2. (  
  3. SELECT  
  4. EmployeeID, FirstName, LastName, Salary  FROM  Employees  
  5. WHERE  DepartmentID = (SELECT DepartmentID FROM Departments WHERE DepartmentName = 'Sales')  
  6. )  
  7. SELECT  EmployeeID, FirstName, LastName, Salary  FROM  SalesEmployees  
  8. ORDER  BY  Salary DESC  
 
  1. ------OutPut  
  2. EmployeeID  FirstName                                          LastName                                           Salary  
  3. ----------- -------------------------------------------------- -------------------------------------------------- -----------  
  4. 6           Sarah                                              Garcia                                             62000  
  5. 1           John                                               Doe                                                60000  
  6. 3           Michael                                            Johnson                                            55000  
 Explanation:
The SalesEmployees CTE retrieves the employeeID, first name, last name and salary of an employee in the SalesEmployees table. The join that links the tables to the correct employees should be where the DepartmentID in the table employees is equated to the DepartmentID of the table Sales department. The primary query will retrieve all the fields of the SalesEmployees CTE and sort them order by salaries in an ascending order. 

Several Other with CTE
A CTE may be referred to more than once in the same query
Find average salary of all employees and then find out employees whose salary is above the average. 
  1. ;WITH EmployeeSalaries AS  
  2. (  
  3. SELECT  AVG(Salary)AS AverageSalary  
  4. FROM  Employees  
  5. )  
  6.   
  7. SELECT  EmployeeID,FirstName,LastName,Salary FROM  Employees e,EmployeeSalaries es  
  8. WHERE  Salary>es.AverageSalary  
 
  1. ------ OutPut  
  2. EmployeeID  FirstName                                          LastName                                           Salary  
  3. ----------- -------------------------------------------------- -------------------------------------------------- -----------  
  4. 2           Jane                                               Smith                                              75000  
  5. 4           Emily                                              Brown                                              80000  
  6. 5           David                                              Wilson                                             70000  
  7. 7           Robert                                             Martinez                                           85000  
 Explanation:
• TheEmployeeSalaries CTE calculates the average salary of all employees.
• Themainqueryselectsemployeeswhosesalaryisgreaterthantheaveragesalary.

which is calculated at the EmployeeSalaries CTE. 
CTE WITH JOINS
CTE scan incorporate joins in the merging of data in tables.
Example: Get the names of employees and the corresponding names of departments. 
  1. ;WITH EmployeeDepartments AS  
  2. (  
  3.  SELECT  
  4.  e.EmployeeID,e.FirstName, e.LastName,d.DepartmentName  
  5.  FROM  Employees e  
  6.  JOIN  Departments d ON e.DepartmentID=d.DepartmentID  
  7.  )  
  8.  SELECT  EmployeeID, FirstName, LastName, DepartmentName  FROM  EmployeeDepartments  
  9.  ORDER BY  DepartmentName, LastName  
 
  1. ------ OutPut  
  2. EmployeeID  FirstName                                          LastName                                           DepartmentName  
  3. ----------- -------------------------------------------------- -------------------------------------------------- --------------------------------------------------  
  4. 4           Emily                                              Brown                                              Engineering  
  5. 7           Robert                                             Martinez                                           Engineering  
  6. 2           Jane                                               Smith                                              Marketing  
  7. 5           David                                              Wilson                                             Marketing  
  8. 1           John                                               Doe                                                Sales  
  9. 6           Sarah                                              Garcia                                             Sales  
  10. 3           Michael                                            Johnson                                            Sales  
  Explanation:
• EmployeeDepartments CTE is an action on combining Employees and Departments tables DepartmentID column.
• The primary question plucks out the EmployeeID, FirstName, LastName and DepartmentName the EmployeeDepartments CTE and sorts the output by department name and last name. 
RECURSIVE CTE
Hierarchical data are queried through recursive CTE. They are done in two steps:
 Anchor Member: The first SELECT statement that forms the base case.
Recursive Member: The SELECT string which uses the same CTE as the name of the CTE itself since it cannot be used to refer to itself directly run through the chain.
Example: (This example demands a table of self-reference, so, suppose we keep one) EmployeeHierarchy table). 
  1. -- Create EmployeeHierarchy  table    
  2.   
  3. CREATE TABLE EmployeeHierarchy 
  4. (  
  5.     EmployeeID INT PRIMARY KEY,  
  6.     EmployeeName NVARCHAR(100),  
  7.     ManagerID INT NULL  
  8. );  
 
  1. -- Insert into EmployeeHierarchy   
  2.   
  3. INSERT INTO EmployeeHierarchy (EmployeeID, EmployeeName, ManagerID)  
  4. VALUES  
  5.     (1, 'John Doe'NULL),        -- Top-level manager (no manager)  
  6.     (2, 'Jane Smith', 1),         -- Reports to John  
  7.     (3, 'Mike Brown', 1),         -- Reports to John  
  8.     (4, 'Emily White', 2),        -- Reports to Jane  
  9.     (5, 'David Black', 2);        -- Reports to Jane  
 
  1. ------Departments Rable OutPut  
  2. EmployeeID  EmployeeName                                                                                         ManagerID  
  3. ----------- ---------------------------------------------------------------------------------------------------- -----------  
  4. 1           John Doe                                                                                             NULL  
  5. 2           Jane Smith                                                                                           1  
  6. 3           Mike Brown                                                                                           1  
  7. 4           Emily White                                                                                          2  
  8. 5           David Black                                                                                          2  
 
  1. WITH  EmployeeHierarchyCTE AS   
  2. (-- Anchor member: Select the top-level employee (John Doe)  
  3.  SELECT EmployeeID, EmployeeName, ManagerID, 0 AS Level  
  4.  FROM EmployeeHierarchy  WHERE ManagerID IS NULL  
  5.  UNION ALL  
  6.  -- Recursive member: Select subordinates of the current level  
  7.  SELECT e.EmployeeID, e.EmployeeName, e.ManagerID, eh.Level + 1  
  8.  FROM EmployeeHierarchy e  
  9.  JOIN EmployeeHierarchyCTE eh ON e.ManagerID = eh.EmployeeID  
  10.  )  
  11.  SELECT EmployeeID, EmployeeName, Level FROM EmployeeHierarchyCTE  
  12.  WHERE EmployeeID <> 1-- Exclude John Doe himself  
  13.  ORDER BY Level, EmployeeName  
 
  1. ------ OutPut  
  2. EmployeeID  EmployeeName                                                                                         Level  
  3. ----------- ---------------------------------------------------------------------------------------------------- -----------  
  4. 2           Jane Smith                                                                                           1  
  5. 3           Mike Brown                                                                                           1  
  6. 5           David Black                                                                                          2  
  7. 4           Emily White                                                                                          2  
 Explanation:
  • The top-level employee (John Doe) having NULL ManagerID is chosen by anchor, which is the member.
  • The recursive member relates the EmployeeHierarchy table to EmployeeHierarchyCTE 
  • e.ManagerID = eh.EmployeeID, so doing the same as finding the subordinates of every employee. it is at its present level.
  • The UNION ALL aggregates both the anchor members and the recursive ones.
  • The primary query chosen is EmployeeID, EmployeeName, and Level out of the EmployeeHierarchyCTE and sorts results by level and name of employee.
CTE and Window Functions
 
CTEs may be applied together with window functions to make those calculations over a set
third person opinion in connection with row being spoken of.
Examples: Determine the wage per worker and his/her departmental ranking. 
  1. WITH RankedSalaries AS (  
  2. SELECT  
  3. EmployeeID, FirstName, LastName, DepartmentID, Salary  
  4. ,RANK() OVER (PARTITION BY DepartmentID ORDER BY Salary DESCAS  SalaryRank  
  5. FROM  Employees  
  6. )  
  7. SELECT  
  8. EmployeeID, FirstName, LastName, DepartmentID, Salary, SalaryRank  FROM  RankedSalaries  
  9. ORDER BY  DepartmentID, SalaryRank  
 
  1. ------ OutPut  
  2. EmployeeID  FirstName                                          LastName                                           DepartmentID Salary      SalaryRank  
  3. ----------- -------------------------------------------------- -------------------------------------------------- ------------ ----------- --------------------  
  4. 6           Sarah                                              Garcia                                             10           62000       1  
  5. 1           John                                               Doe                                                10           60000       2  
  6. 3           Michael                                            Johnson                                            10           55000       3  
  7. 2           Jane                                               Smith                                              20           75000       1  
  8. 5           David                                              Wilson                                             20           70000       2  
  9. 7           Robert                                             Martinez                                           30           85000       1  
  10. 4           Emily                                              Brown                                              30           80000       2  
  Conclusion:
The Common Table Expressions are an excellent method of making SQL more legible. They allow you to break long, difficult to read, steps into more easily understandable named results sets. Due to that, CTEs make your code more readable, correct, and maintainable. By considering the issue well, it is possible to enhance SQL knowledge by using CTEs. It is just important to keep in mind that CTEs are slower under very complex queries. That way, intelligently use them to keep your request quick. CTEs have the capability to significantly clean up and organize your SQL codes in the long term. 

0 Comments

Post Comment

Your email address will not be published. Required fields are marked *