The WITH clause in SQL

Anil R
1 min readNov 21, 2024

The WITH clause in SQL, also known as a Common Table Expression (CTE), is often used to define a temporary result set that can be referred to within the main query. This is particularly useful for making complex queries more readable and reusable.

Here’s the general syntax of a query using a CTE:

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

Example 1: Simple Usage

WITH records AS (
SELECT id, name, salary
FROM employees
WHERE salary > 50000
)
SELECT *
FROM records
WHERE name LIKE 'A%';

Example 2: Multiple CTEs

WITH high_earners AS (
SELECT id, name, salary
FROM employees
WHERE salary > 70000
),
low_earners AS (
SELECT id, name, salary
FROM employees
WHERE salary <= 70000
)
SELECT *
FROM high_earners
UNION ALL
SELECT *
FROM low_earners;

Example 3: Recursive CTE

A recursive CTE is useful for hierarchical data or iterative queries.

WITH RECURSIVE employee_hierarchy AS (
SELECT employee_id, manager_id, name
FROM employees
WHERE manager_id IS NULL -- Start with the top-level manager
UNION ALL
SELECT e.employee_id, e.manager_id, e.name
FROM employees e
INNER JOIN employee_hierarchy eh ON e.manager_id = eh.employee_id
)
SELECT *
FROM employee_hierarchy;

When to Use WITH:

  • Simplify and organize complex queries.
  • Avoid repeating subqueries.
  • Improve query readability and maintainability.

--

--

Anil R
Anil R

Written by Anil R

Full Stack Developer with 15 years experience.

No responses yet