Full answer
sql
WITH RECURSIVE m(month) AS (
SELECT '2026-01-01'
UNION ALL
SELECT date(month, '+1 month') FROM m WHERE month < '2026-06-01'
)
SELECT substr(month, 1, 7) AS month FROM m;| month |
|---|
| 2026-01 |
| 2026-02 |
| 2026-03 |
| 2026-04 |
| 2026-05 |
| 2026-06 |
Each step adds one month to the previous row, and the WHERE in the recursive part stops after June. Because every value is the first of a month, there is no month-end normalization problem.
PostgreSQL:
sql
SELECT to_char(d, 'YYYY-MM') AS month
FROM generate_series(DATE '2026-01-01', DATE '2026-06-01', INTERVAL '1 month') AS d;| month |
|---|
| 2026-01 |
| 2026-02 |
| 2026-03 |
| 2026-04 |
| 2026-05 |
| 2026-06 |
A month list like this is the left side of a LEFT JOIN for reports that must show months with no data.
sql
WITH RECURSIVE m(month) AS (
SELECT '2026-01-01'
UNION ALL
SELECT date(month, '+1 month') FROM m WHERE month < '2026-06-01'
)
SELECT substr(month, 1, 7) AS month FROM m;Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
- Seed with the first month and add +1 month per step
- Stop with a condition in the recursive part
- Use first-of-month dates to avoid normalization
- PostgreSQL generate_series works with intervals
Common mistakes
- Starting from the 31st and drifting
- Forgetting the stop condition
Follow-ups
- How would you count orders per month with zeros?
- How would you generate weeks instead?
Tips
- Use it as a calendar for LEFT JOINs