Step by step with WITH
Build a query in two steps that are easy to read.
WITH names the first step, then the main query uses it like a table.
In a WITH step called times, count the loans per book_id. Then show the title and loans of the books borrowed more than once.
Run your query to see the result table.
Press the green Run button or Ctrl+Enter.
How WITH works
1. WITH works out a step and names it
WITH loan_counts AS ( SELECT member_id, COUNT(*) AS loans FROM loans GROUP BY member_id )known as loan_counts
member_id loans 101 2 102 1 103 3 2. The main query reads it like a table
SELECT members.name, loan_counts.loans FROM members JOIN loan_counts ON members.member_id = loan_counts.member_id;
name loans Ava 2 Ben 1 Cara 3
Each step is short and can be run on its own, so a long query reads top to bottom.
What does
WITHdo?WITH loan_counts AS (SELECT ...) SELECT ... FROM loan_countsIt names a query, so the main query can use it like a table. The name only lasts for this one query.
Why use it?
To build a long query in short steps that read top to bottom. Each step can be run and checked on its own, a bit like helper columns in Excel.
Can I have more than one step?
Yes, separated by commas:
WITH a AS (...), b AS (SELECT ... FROM a) SELECT ... FROM b. Later steps can use earlier ones.Is it the same as a subquery?
It does the same job as a subquery in
FROM, but with a name, at the top. Many people find it easier to read.How is this like Excel?
Like a helper column or a LET formula:
=LET(total, SUM(B2:B11), B2/total)names a step and reuses it.
How other databases do it
The lessons run on SQLite. Most of SQL is the same everywhere; these are the places where this lesson's SQL differs.
| Database | How | Note |
|---|---|---|
| SQLite (these lessons) | WITH name AS (...) | Since SQLite 3.8.3 (2014). |
| PostgreSQL | WITH name AS (...) | |
| MySQL / MariaDB | WITH name AS (...) | Since MySQL 8.0. In 5.7, use a subquery in FROM. |
| SQL Server | ;WITH name AS (...) | The statement before it must end with ;, so people often start WITH with one. |
| Oracle | WITH name AS (...) | Oracle calls it subquery factoring. |
| Sybase ASE | Not available | Use a subquery in FROM, or a temporary #table. |
Know someone fighting with a spreadsheet? Send them this page.