SQL - Select With

The WITH clause, also known as a Common Table Expression (CTE), is used to define temporary result sets that can be referenced within a query. It allows you to create named temporary tables or subqueries that can be used as building blocks in your SQL statements. The WITH clause enhances query readability and reusability by breaking down complex queries into smaller, more manageable parts.


WITH cte_name (column1, column2, ...)
AS (
  -- CTE query definition
  SELECT ...
  FROM ...
  WHERE ...
-- SQL statement using the CTE
FROM ...
JOIN cte_name ON ...


Let's assume we have a "Products" table with the following columns:

ProductID (unique identifier for each product)

ProductName (name of the product)

CategoryID (category identifier for the product)

Price (price of the product)

We want to retrieve a list of products along with their corresponding category names. We can use the WITH clause to define a temporary result set that retrieves category names based on the CategoryID and then join it with the "Products" table:

WITH CategoryNames (CategoryID, CategoryName)
AS (
  SELECT CategoryID, CategoryName
  FROM Categories
SELECT p.ProductID, p.ProductName, c.CategoryName, p.Price
FROM Products p
JOIN CategoryNames c ON p.CategoryID = c.CategoryID;


The WITH clause is used to define the CTE. In this example, we name the CTE as "CategoryNames" and specify the columns CategoryID and CategoryName that will be selected.

Within the CTE definition, we provide the query that retrieves the desired data. In this case, we select the CategoryID and CategoryName from the "Categories" table.

After defining the CTE, we can refer to it in the subsequent SQL statement. In this example, we join the "Products" table (p) with the "CategoryNames" CTE (c) based on the CategoryID column.

By executing this query, you will retrieve the ProductID, ProductName, CategoryName, and Price of each product, with the corresponding category name included. The CTE allows us to create a temporary result set that simplifies the query logic by separating the retrieval of category names from the main query.