The Wayback Machine - https://web.archive.org/web/20240728075912/https://www.geeksforgeeks.org/sql-with-clause/
Open In App

SQL | WITH Clause

Last Updated : 05 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

The SQL WITH clause, also known as Common Table Expressions (CTEs), was introduced by Oracle in the Oracle 9i release 2 database. The SQL WITH clause allows you to give a sub-query block a name (a process also called sub-query refactoring), which can be referenced in several places within the main SQL query. 

What is the SQL WITH Clause?

  • The clause is used for defining a temporary relation such that the output of this temporary relation is available and is used by the query that is associated with the WITH clause.
  • Queries that have an associated WITH clause can also be written using nested sub-queries but doing so adds more complexity to read/debug the SQL query.
  • WITH clause is not supported by all database systems.
  • The name assigned to the sub-query is treated as though it were an inline view or table
  • The SQL WITH clause was introduced by Oracle in the Oracle 9i release 2 database.

Note: Not all database systems support the WITH clause.

Syntax: 

WITH temporaryTable (averageValue) AS (
SELECT AVG (Attr1)
FROM Table
)
SELECT Attr1
FROM Table, temporaryTable
WHERE Table.Attr1 > temporaryTable.averageValue;

SQL WITH Clause

In this query, WITH clause is used to define a temporary relation temporaryTable that has only 1 attribute averageValue. averageValue holds the average value of column Attr1 described in relation Table. The SELECT statement that follows the WITH clause will produce only those tuples where the value of Attr1 in relation Table is greater than the average value obtained from the WITH clause statement. 

Note: When a query with a WITH clause is executed, first the query mentioned within the  clause is evaluated and the output of this evaluation is stored in a temporary relation. Following this, the main query associated with the WITH clause is finally executed that would use the temporary relation produced. 

SQL WITH Clause Examples

Let us look at some of the examples of WITH Clause in SQL:

Example 1: Finding Employees with Above-Average Salary

Find all the employee whose salary is more than the average salary of all employees. 
Name of the relation: Employee 

EmployeeID Name Salary
100011 Smith 50000
100022 Bill 94000
100027 Sam 70550
100845 Walden 80000
115585 Erik 60000
1100070 Kate 69000

SQL Query: 

WITH temporaryTable (averageValue) AS (
SELECT AVG(Salary)
FROM Employee
)
SELECT EmployeeID,Name, Salary
FROM Employee, temporaryTable
WHERE Employee.Salary > temporaryTable.averageValue;

Output:

EmployeeID Name Salary
100022 Bill 94000
100845 Walden 80000

Explanation: The average salary of all employees is 70591. Therefore, all employees whose salary is more than the obtained average lies in the output relation. 

Example 2: Finding Airlines with High Pilot Salaries

Find all the airlines where the total salary of all pilots in that airline is more than the average of total salary of all pilots in the database. 
Name of the relation: Pilot 

EmployeeID Airline Name Salary
70007 Airbus 380 Kim 60000
70002 Boeing Laura 20000
10027 Airbus 380 Will 80050
10778 Airbus 380 Warren 80780
115585 Boeing Smith 25000
114070 Airbus 380 Katy 78000

SQL Query: 

WITH totalSalary(Airline, total) AS (
SELECT Airline, SUM(Salary)
FROM Pilot
GROUP BY Airline
),
airlineAverage (avgSalary) AS (
SELECT avg(Salary)
FROM Pilot
)
SELECT Airline
FROM totalSalary, airlineAverage
WHERE totalSalary.total > airlineAverage.avgSalary;

Output:

Airline
Airbus 380

Explanation: The total salary of all pilots of Airbus 380 = 298,830 and that of Boeing = 45000. Average salary of all pilots in the table Pilot = 57305. Since only the total salary of all pilots of Airbus 380 is greater than the average salary obtained, so Airbus 380 lies in the output relation.

Important Points About SQL | WITH Clause

  • The SQL WITH clause is good when used with complex SQL statements rather than simple ones
  • It also allows you to break down complex SQL queries into smaller ones which make it easy for debugging and processing the complex queries.
  • The SQL WITH clause is basically a drop-in replacement to the normal sub-query.
  • The SQL WITH clause can significantly improve query performance by allowing the query optimizer to reuse the temporary result set, reducing the need to re-evaluate complex sub-queries multiple times.

Previous Article
Next Article

Similar Reads

Difference between Having clause and Group by clause
1. Having Clause : Having Clause is basically like the aggregate function with the GROUP BY clause. The HAVING clause is used instead of WHERE with aggregate functions. While the GROUP BY Clause groups rows that have the same values into summary rows. The having clause is used with the where clause in order to find rows with certain conditions. The
3 min read
SQL | Intersect & Except clause
1. INTERSECT clause : As the name suggests, the intersect clause is used to provide the result of the intersection of two select statements. This implies the result contains all the rows which are common to both the SELECT statements. Syntax : SELECT column-1, column-2 …… FROM table 1 WHERE….. INTERSECT SELECT column-1, column-2 …… FROM table 2 WHE
1 min read
SQL | USING Clause
If several columns have the same names but the datatypes do not match, the NATURAL JOIN clause can be modified with the USING clause to specify the columns that should be used for an EQUIJOIN. USING Clause is used to match only one column when more than one column matches. NATURAL JOIN and USING Clause are mutually exclusive. It should not have a q
2 min read
SQL | With Ties Clause
This post is a continuation of SQL Offset-Fetch Clause Now, we understand that how to use the Fetch Clause in Oracle Database, along with the Specified Offset and we also understand that Fetch clause is the newly added clause in the Oracle Database 12c or it is the new feature added in the Oracle database 12c. Now consider the below example: Suppos
4 min read
SQL | Sub queries in From Clause
From clause can be used to specify a sub-query expression in SQL. The relation produced by the sub-query is then used as a new relation on which the outer query is applied. Sub queries in the from clause are supported by most of the SQL implementations.The correlation variables from the relations in from clause cannot be used in the sub-queries in
2 min read
SQL | ON Clause
The join condition for the natural join is basically an EQUIJOIN of all columns with same name. To specify arbitrary conditions or specify columns to join, the ON Clause is used. The join condition is separated from other search conditions. The ON Clause makes code easy to understand. ON Clause can be used to join columns that have different names.
2 min read
Combining aggregate and non-aggregate values in SQL using Joins and Over clause
Prerequisite - Aggregate functions in SQL, Joins in SQLAggregate functions perform a calculation on a set of values and return a single value. Now, consider an employee table EMP and a department table DEPT with following structure:Table - EMPLOYEE TABLE NameNullTypeEMPNONOT NULLNUMBER(4)ENAME VARCHAR2(10)JOB VARCHAR2(9)MGR NUMBER(4)HIREDATE DATESA
2 min read
SQL Full Outer Join Using Left and Right Outer Join and Union Clause
An SQL join statement is used to combine rows or information from two or more than two tables on the basis of a common attribute or field. There are basically four types of JOINS in SQL. In this article, we will discuss FULL OUTER JOIN using LEFT OUTER Join, RIGHT OUTER JOIN, and UNION clause. Consider the two tables below: Sample Input Table 1: Pu
3 min read
Difference between From and Where Clause in SQL
1. FROM Clause: It is used to select the dataset which will be manipulated using Select, Update or Delete command.It is used in conjunction with SQL statements to manipulate dataset from source table.We can use subqueries in FROM clause to retrieve dataset from table. Syntax of FROM clause: SELECT * FROM TABLE_NAME; 2. WHERE Clause: It is used to a
2 min read
Distinct clause in MS SQL Server
The SELECT DISTINCT statement is used to return only distinct (different) values. Inside a table, a column often contains many duplicate values and sometimes we only want to list the different (distinct) values. Consider a simple database and we will be discussing distinct clauses in MS SQL Server. Suppose a table has a maximum of 1000 rows constit
3 min read
Article Tags :
three90RightbarBannerImg