WITH
WITH in SQL is a clause used for creating subquery block that can be referenced within the main SQL query. It essentially allows you to give a name to a subquery block, thereby increasing readability and making complex queries more manageable. This construct is also known as a Common Table Expression (CTE).
Example
WITH sample AS (SELECT 'Hello, SQL!' AS Column1)SELECT * FROM sample;Output
Column1----------- Hello, SQL!(1 row)Explanation
In the provided example, the SQL statement consists of a WITH clause, often referred to as a “Common Table Expression” (CTE). The WITH clause creates a temporary table ‘sample’ which contains a single data row with the value ‘Hello, SQL!’. The SELECT statement that follows fetches all the data (in this case, a single data row) from this temporary table.
Example
WITH Sales_CTE (SalesPersonID, NumberOfOrders)AS( SELECT SalesPersonID, COUNT(SalesOrderID) FROM Sales.SalesOrderHeader GROUP BY SalesPersonID)SELECT E.EmployeeID, E.FirstName, E.LastName, SC.NumberOfOrdersFROM HumanResources.Employee AS EJOIN Sales_CTE AS SCON E.EmployeeID = SC.SalesPersonIDORDER BY SC.NumberOfOrders DESC;Output
EmployeeID | FirstName | LastName | NumberOfOrders-----------|-----------|----------|---------------275 | Michael | Blythe | 31276 | Linda | Mitchell | 29277 | Jillian | Carson | 25278 | Garrett | Vargas | 23Explanation
The code above is using a Common Table Expression (CTE) named Sales_CTE to calculate the number of orders each salesperson has closed. First, we define our CTE, and after that, we join it with the Employee table to fetch the first name and last name of the employees. The resulting set displays the number of sales orders along with the corresponding employee details. It is ordered by the number of sales orders in descending order, showing the salespersons with the highest number of orders first.
Example
WITH temp AS ( SELECT department_id, COUNT(*) total_employees FROM employees GROUP BY department_id)SELECT e.first_name, e.last_name, t.total_employeesFROM employees eJOIN temp t ON e.department_id = t.department_idWHERE e.department_id = 20;Output
FIRST_NAME | LAST_NAME | TOTAL_EMPLOYEES-----------|-----------|-----------------Matthew | Weiss | 3Adam | Fripp | 3Payam | Kaufling | 3Explanation
The WITH keyword is used to create a temporary result set, temp in this case, which is used in the main SELECT query. This result set is defined by the SELECT statement within the parentheses following the WITH keyword.
This temp result set consists of the department IDs and the total number of employees in each department. This temp result is then joined with the employees table, and the query returns the first name, last name, and the total number of employees in the same department for each employee in department ‘20’.