SQL WITH Clause (original) (raw)

Last Updated : 14 Apr, 2026

The SQL WITH clause (Common Table Expression or CTE) defines a temporary result set that can be used within a query. It simplifies complex SQL statements, making them easier to read, manage and reuse.

SQL-WITH-clause

**Syntax:

WITH cte_name (column1, column2, ...)
AS (
SELECT column1, column2, ...
FROM table_name
WHERE condition
)
SELECT *
FROM cte_name;

**Examples of SQL WITH Clause

First, we will create a demo SQL database and table, on which we will use the WITH Clause command.

New_emp

**Example 1: Finding Employees with Above-Average Salary

This example demonstrates how to find all employees whose salary is higher than the average salary of all employees in the database. The query calculates the average salary using the WITH clause and compares each employee's salary against this average to return those with above-average salaries.

**Query:

WITH AvgSalaryCTE (averageValue) AS (
SELECT AVG(Salary)
FROM Employees
)
SELECT
EmployeeID,
Name,
Salary
FROM
Employees
WHERE
Salary > (SELECT averageValue FROM AvgSalaryCTE);

**Output:

Average-salary

Example 2: Finding Employees with the Lowest Salary

In this example, we find the employee or employees who earn the lowest salary in the company. The WITH clause is used to first calculate the minimum salary from the Employees table and then the main query retrieves the details of employees whose salary matches this minimum value.

**Query:

WITH MinSalaryCTE (min_salary) AS (
-- 1. Calculate the single lowest salary value
SELECT MIN(Salary)
FROM Employees
)
SELECT
e.EmployeeID,
e.Name,
e.Salary
FROM
Employees e
WHERE
e.Salary = (SELECT min_salary FROM MinSalaryCTE);

**Output

Lowest-salary

Nested (Chained) WITH Clauses

A Nested or Chained WITH Clause defines multiple Common Table Expressions (CTEs) within a single query, where a later CTE references the result of a previous CTE. This allows you to break down a complex, multi-step calculation into logical, readable parts.

WITH DeptAvg AS (
SELECT Department, AVG(Salary) AS AvgSalary
FROM Employees
GROUP BY Department
),
RankedEmployees AS (
SELECT e.EmployeeID, e.Name, e.Department, e.Salary,
RANK() OVER (PARTITION BY e.Department ORDER BY e.Salary DESC) AS SalaryRank
FROM Employees e
JOIN DeptAvg d ON e.Department = d.Department
)
SELECT *
FROM RankedEmployees
WHERE SalaryRank = 1;

**Output:

Screenshot-2026-02-09-113801

**Note: When a query with a WITH clause runs, the subquery inside it is executed first to create a temporary result set, which is then used by the main query.