Common Table Expression or CTE specifies a temporary named result set which is derived from a query and can be used in the same execution scope of a single SELECT, INSERT, UPDATE, or DELETE statement. This is quite useful if you need temporary results from a sub query within your main query. An example below uses Northwind 2011 database:
1 2 3 4 5 6 7 8 9 10 11 12 |
WITH Duplicates AS ( select OrderID from OrderDetails where Quantity >= 20 group by OrderID, Quantity Having Count(*) > 1 ) SELECT OrderID,ProductID, UnitPrice,Quantity,Discount FROM OrderDetails Where OrderID in (select OrderID from Duplicates) order by OrderID, Quantity |
Let’s break down the SQL code above:
- CTE Duplicates is defined and run. It returns a list of OrderID, grouped by OrderID and Quantity, where count of orders in a group is bigger then 1:
12345678WITH DuplicatesAS(select OrderID from OrderDetailswhere Quantity >= 20group by OrderID, QuantityHaving Count(*) > 1) - The main query uses the results from Duplicates query in the Where clause:
1234SELECT OrderID,ProductID, UnitPrice,Quantity,DiscountFROM OrderDetailsWhere OrderID in (select OrderID from Duplicates)order by OrderID, Quantity - The result of the whole script is:
You can also use multiple CTE expressions in a single SQL statment. Check the example below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
With LateOrders AS ( Select EmployeeID , Count(*) as TotalOrders From Orders Where RequiredDate <= ShippedDate Group By EmployeeID ) , AllOrders AS ( Select EmployeeID, Count(*) as TotalOrders From Orders Group By EmployeeID ) Select Employees.EmployeeID, LastName, AllOrders.TotalOrders as AllOrders, LateOrders = IsNull(LateOrders.TotalOrders, 0) From Employees Join AllOrders on AllOrders.EmployeeID = Employees.EmployeeID Left Join LateOrders on LateOrders.EmployeeID = Employees.EmployeeID |
You can also read more about CTE on Microsoft website.