Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 72/ 160
04. Subqueries & Common Table Expressions (CTEs)

Generating Calendars, Date Spines & Number Sequences with Recursive CTEs

Build date spines and sequences when GENERATE_SERIES is unavailable.

IntermediateDate Spine · Number Sequence3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

Start with one date and keep adding a day until you've made the whole list.

Think of it like…

Writing out the days of a diary by hand: write the first date, then keep writing "the day after the last one" until you reach the end of the year.

Where you’ve seen it

A MySQL dashboard shows daily signups for November including zero days: WITH RECURSIVE days AS (SELECT DATE('2026-11-01') AS d UNION ALL SELECT d + INTERVAL 1 DAY FROM days WHERE d < '2026-11-30') SELECT days.d, COUNT(u.id) AS signups FROM days LEFT JOIN users u ON u.created_at >= days.d AND u.created_at < days.d + INTERVAL 1 DAY GROUP BY days.d ORDER BY days.d;

Words you’ll hear

Date spine
One row for every period in a range, to join data onto.
Recursive step
Adds one interval to the previous row until the end condition fails.
Recursion limit
MySQL stops at 1,000 iterations by default; SQL Server at 100.
Calendar table
A permanent table of dates with attributes like weekday, week and holiday.

Visual diagram

Loading interactive diagram

Theory & example queries

The pattern in each engine

The anchor selects the start date; the recursive member adds one interval to the previous row; the WHERE in the recursive member stops when the end is reached. MySQL: SELECT d + INTERVAL 1 DAY FROM days WHERE d < '2026-12-31'. SQLite: SELECT date(d, '+1 day') FROM days WHERE d < '2026-12-31'. SQL Server has no RECURSIVE keyword: WITH days AS (SELECT CAST('2026-01-01' AS date) AS d UNION ALL SELECT DATEADD(day, 1, d) FROM days WHERE d < '2026-12-31') SELECT d FROM days OPTION (MAXRECURSION 400);

Mind the limits. MySQL's cte_max_recursion_depth defaults to 1,000, enough for under three years of days; raise it with SET SESSION cte_max_recursion_depth = 5000. SQL Server stops at 100 levels unless you add OPTION (MAXRECURSION n), where 0 means unlimited. For number sequences, the same loop counts n + 1 from 1, or you can cross join a ten-row digits table with itself to get 100, 1,000 or 10,000 numbers without recursion at all.

First day of each month in 2026 (MySQL)Query example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1WITH RECURSIVE2  months AS (3    SELECT4      DATE ('2026-01-01') AS m5    UNION ALL6    SELECT7      m + INTERVAL 1 MONTH8    FROM9      months10    WHERE11      m < '2026-12-01'12  )13SELECT14  m15FROM16  months;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · SQL expression

Read this line together with the surrounding statement as part of the same SQL expression.

1/16
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output4 sample rows
Expected output
m
2026-01-01
2026-02-01
2026-11-01
2026-12-01

Note: Shows 4 of the 12 generated month-start rows; output formatting for DATE values varies by client.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

returns 12 rows.

Key takeaway: Anchor + add one interval + stop condition; mind the engine's recursion limit.

From spine to calendar table

A recursive CTE builds rows one iteration at a time, which is fine for a few hundred or thousand periods but slow for decades of hours. If many reports need dates, generate them once into a permanent calendar table covering, say, 2015 to 2035, with columns such as day of week, ISO week, month start, fiscal quarter, is_weekend and is_holiday.

A calendar table turns hard questions into simple filters and joins: business days between two dates are SELECT COUNT(*) FROM calendar WHERE d BETWEEN a AND b AND NOT is_weekend AND NOT is_holiday; fiscal-quarter reports group by a column instead of date arithmetic. Holidays come from a maintained list, which no generated series can know. In a warehouse this table is the date dimension.

Filling a calendar table (MySQL)Query example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SET2  SESSION cte_max_recursion_depth = 8000;34INSERT INTO5  calendar (d, dow, is_weekend)6WITH RECURSIVE7  days AS (8    SELECT9      DATE ('2015-01-01') AS d10    UNION ALL11    SELECT12      d + INTERVAL 1 DAY13    FROM14      days15    WHERE16      d < '2035-12-31'17  )18SELECT19  d,20  DAYOFWEEK (d),21  DAYOFWEEK (d) IN (1, 7)22FROM23  days;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · SQL expression

Read this line together with the surrounding statement as part of the same SQL expression.

1/23
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output
SET 7670 row(s) inserted

Note: The inclusive 2015-01-01 through 2035-12-31 sample spans 7,670 dates when the calendar is empty; status wording varies by dialect.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Recursive spines for one-off reports; a calendar table for shared, attribute-rich dates.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Anchor

Write the anchor

Select the first date with the right type, because the anchor sets the column's type for every row.

SQL at this step
1SELECT2  DATE ('2026-11-01') AS d
What to watch at this step
Type
date, not text
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

A date spine is a list of every date (or month, or hour) in a range, used to report on periods with no data. PostgreSQL has generate_series, but MySQL, SQLite and SQL Server before 2022 don't, so you build the spine with a recursive CTE: start at the first date and add one day until the last. The same loop makes number sequences, and the spine is often saved as a permanent calendar table with useful attributes.

Why it matters: Daily reports must show zero days, not skip them, and many teams work on MySQL, SQL Server or SQLite. Knowing the recursive pattern, each engine's recursion limit and when to switch to a calendar table is everyday analytics engineering and a frequent interview follow-up to "what if there's no generate_series?".

When to reach for it

  • Gap-filled daily, weekly or monthly reports on MySQL or SQL Server
  • Number sequences for test data or splitting
  • Seeding a calendar or date dimension table

When to avoid or be careful

  • Text anchors like '2026-11-01' in MySQL when you mean a date
  • Hourly spines over years with a recursive CTE
  • Calculating business days without a holiday list

Recursive CTE vs generate_series vs a calendar table

Recursive CTE
Best for: MySQL, SQLite, SQL Server; one-off spines

Strengths: Works in nearly every modern engine with no setup.

Watch out: Row-by-row; recursion limits on long ranges.

generate_series / GENERATE_DATE_ARRAY
Best for: PostgreSQL, BigQuery and other engines that have one

Strengths: Short and fast.

Watch out: Not portable.

Permanent calendar table
Best for: Many reports, business days, fiscal periods, holidays

Strengths: Rich attributes; indexable; consistent everywhere.

Watch out: Must be created and extended before it runs out.

Interview signals & numbers to know

When this topic comes up

  • “Show days with zero sales”
  • “MySQL doesn't have generate_series”
  • “Count business days between two dates”
  • Recursion limits
  • Date dimensions

Benchmarks & rules of thumb

1,000 -
MySQL's default cte_max_recursion_depth
100 -
SQL Server's default MAXRECURSION
0 -
MAXRECURSION value meaning unlimited
SQL Server 2022 -
first version with GENERATE_SERIES (numbers)

Common mistakes & follow-ups

Common interview mistakes

  • Building a 10-year daily spine in MySQL and hitting the 1,000-iteration limit.
  • Forgetting OPTION (MAXRECURSION …) in SQL Server, so a month-long spine fails after 100 rows.
  • Using COUNT(*) after the LEFT JOIN, so empty days show 1 instead of 0.

Likely interviewer follow-ups

  • How would you produce a daily report with zero days in MySQL?
  • What limits recursive CTEs in MySQL and SQL Server?
  • What columns would you put in a calendar table?
Interview tip: Write the recursive spine, name the engine's recursion limit, then suggest a calendar table for repeated use. It shows you know both the trick and the production answer.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Generating Calendars, Date Spines & Number Sequences with Recursive CTEs with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Traversing Organizational Charts & Category Trees with Recursive CTEs
Next topic
Graph Traversal & Cycle Detection in Recursive CTEs