SQLite WITH Clause
What is a CTE?
A CTE (Common Table Expression) is a temporary result with a name. You make it with WITH, and then use it in the query that follows, like a table.
A CTE makes long queries easier to read, because you can build them in small steps.
Example
WITH Expensive AS (
SELECT * FROM Products
WHERE Price > 50
)
SELECT ProductName, Price
FROM Expensive
ORDER BY Price DESC;
Try it Yourself »
More Than One CTE
Separate the CTEs with commas. A CTE can use the CTEs before it. This example finds the customers with 5 or more orders:
Example
WITH OrderCounts AS (
SELECT CustomerID, COUNT(*) AS Orders
FROM Orders
GROUP BY CustomerID
),
GoodCustomers AS (
SELECT * FROM OrderCounts
WHERE Orders >= 5
)
SELECT CustomerName, Orders
FROM GoodCustomers
JOIN Customers USING (CustomerID);
Try it Yourself »
Recursive CTE
A recursive CTE uses itself. It starts with one SELECT, and repeats a second SELECT until it returns no more rows. This example counts from 1 to 10:
Example
WITH RECURSIVE Numbers(n) AS (
SELECT 1
UNION ALL
SELECT n + 1 FROM Numbers
WHERE n < 10
)
SELECT n FROM Numbers;
Try it Yourself »
Warning: A recursive CTE needs a condition that stops it, like WHERE n < 10. Without it, the query never ends. Our editor stops a query after a few seconds.
A List of Dates
A recursive CTE can make a list of all the dates in a period. This example counts the orders on each day in the first week of July 1996, also the days without orders:
Example
WITH RECURSIVE Days(Day) AS (
SELECT '1996-07-01'
UNION ALL
SELECT date(Day, '+1 day') FROM Days
WHERE Day < '1996-07-07'
)
SELECT Day, COUNT(Orders.OrderID) AS Orders
FROM Days
LEFT JOIN Orders ON Orders.OrderDate = Day
GROUP BY Day;
Try it Yourself »