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
Output
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
Output
Explanation
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
Output
Explanation
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’.