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 36/ 160
02. Aggregations, Functions & Data Manipulation

Generating Series & Synthetic Data (GENERATE_SERIES)

Build number and date spines for reporting gaps and synthetic test data.

IntermediateGENERATE_SERIES · Date Spine3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

generate_series makes a list of numbers or dates for you, so you can fill in days that have no data.

Think of it like…

A blank calendar printed before the month starts: every day has a box, whether or not anything happens on it, so empty days are visible instead of missing.

Where you’ve seen it

Daily signups for November including zero days: SELECT d::date AS day, COUNT(u.id) AS signups FROM generate_series('2026-11-01'::date, '2026-11-30', interval '1 day') AS d LEFT JOIN users u ON u.created_at::date = d::date GROUP BY 1 ORDER BY 1;

Words you’ll hear

Set-returning function
A function that returns rows and can be used in FROM.
Date spine
A complete list of dates used to fill gaps in time series.
Inclusive bounds
generate_series includes both start and stop (when the step lands on stop).
Equivalents
SQL Server 2022 GENERATE_SERIES (numbers), BigQuery GENERATE_DATE_ARRAY, recursive CTEs elsewhere.

Visual diagram

Loading interactive diagram

Theory & example queries

Numbers and timestamps

With integers, generate_series(1, 5) returns 1 to 5 and generate_series(0, 100, 10) steps by 10. With timestamps or dates, you pass an interval step and get timestamps back, so cast to date when you want days: generate_series('2026-11-01'::date, '2026-11-30', '1 day')::date. The stop value is included when a step lands on it exactly.

Because it's a set-returning function, you use it in FROM like a table (FROM generate_series(…) AS d) and can join to it. For test data, combine it with random functions: INSERT INTO orders (customer_id, amount, created_at) SELECT (random() * 1000)::int + 1, round((random() * 5000)::numeric, 2), now() - random() * interval '365 days' FROM generate_series(1, 1000000); creates a million realistic-looking rows in seconds.

Hourly buckets for the last dayQuery example
1Input dataStart from the source rows or state that the statement sees.
events
3 rows
events sample rows
idcreated_atarchived
12024-11-20false
22024-12-15false
32026-01-05false
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  h AS hour_start,3  COUNT(e.id)4FROM5  generate_series(6    date_trunc('hour', now()) - interval '23 hours',7    date_trunc('hour', now()),8    interval '1 hour'9  ) AS h10  LEFT JOIN events e ON e.created_at >= h11  AND e.created_at < h + interval '1 hour'12GROUP BY13  h14ORDER BY15  h;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/15
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative hourly buckets3 sample rows
Representative hourly buckets
hour_startcount
2026-11-20T10:00:00+00:004
2026-11-20T11:00:00+00:000
2026-11-20T12:00:00+00:007

Note: The query returns 24 ordered buckets. These are the first three for an illustrative UTC window; the empty bucket is kept by the LEFT JOIN and event counts vary with the data and clock.

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

Key takeaway: Numbers or timestamps, inclusive bounds, usable like a table.

Gap-filling patterns and portability

The gap-filling pattern is always the same: generate the spine, LEFT JOIN the data on the spine value (or a range), and count a column from the data table, such as COUNT(u.id), so empty buckets show 0. For several dimensions, cross join the spine with the dimension list (days × products) before the LEFT JOIN.

With timestamptz and a step of '1 day', days follow the session timezone, and around daylight-saving changes a "day" can be 23 or 25 hours, so generating dates rather than timestamps is safer for daily reports. Other databases: SQL Server 2022 has GENERATE_SERIES for numbers, BigQuery has GENERATE_DATE_ARRAY with UNNEST, Snowflake has GENERATOR, and MySQL needs a recursive CTE or a permanent calendar table.

A recursive CTE where generate_series isn't available (MySQL 8)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  d AS (3    SELECT4      DATE '2026-11-01' AS DAY5    UNION ALL6    SELECT7      DAY + INTERVAL 1 DAY8    FROM9      d10    WHERE11      DAY < '2026-11-30'12  )13SELECT14  DAY15FROM16  d;
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.
Representative generated dates4 sample rows
Representative generated dates
day
2026-11-01
2026-11-02
2026-11-29
2026-11-30

Note: The result contains all 30 dates inclusively; the middle 26 rows are omitted from this sample.

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

Key takeaway: Spine → LEFT JOIN → count the data column; use a recursive CTE elsewhere.

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 1generate_series

Generate the spine

Create every number, day or hour in the range you need, cast to the type you'll join on.

Focus at this step

generate_series(start, stop, interval '1 day')::date

What to watch at this step
Bounds
inclusive
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

PostgreSQL's generate_series(start, stop, step) produces a set of rows on the fly: numbers (generate_series(1, 10)) or timestamps (generate_series('2026-11-01', '2026-11-30', interval '1 day')). Both ends are inclusive. It's the quickest way to build a complete calendar for gap-free reports, generate test data, or create time buckets.

Why it matters: Reports built only from existing rows silently skip days with no activity, which makes charts and rolling averages wrong. A generated date spine fixes that. Generating millions of rows of test data in one statement is also invaluable for testing indexes and query performance.

When to reach for it

  • Filling missing days, hours or months in reports
  • Generating large test datasets
  • Creating number sequences for bucketing

When to avoid or be careful

  • COUNT(*) after the LEFT JOIN (empty days count as 1)
  • Timestamp spines across daylight-saving changes when you need calendar days
  • INNER JOIN to data, which removes the empty days again

generate_series vs calendar table vs recursive CTE

generate_series
Best for: PostgreSQL gap-filling and test data

Strengths: One line; any step size; very fast.

Watch out: PostgreSQL-specific; no business-calendar attributes.

Permanent calendar table
Best for: Data warehouses and fiscal or holiday-aware reporting

Strengths: Holds holidays, fiscal periods, week numbers; works in any database.

Watch out: Needs to be built and extended over time.

Recursive CTE
Best for: Databases without generate_series

Strengths: Portable.

Watch out: More verbose; recursion limits apply.

Interview signals & numbers to know

When this topic comes up

  • “Show zero for days with no orders”
  • “Generate a million rows of test data”
  • “Missing dates in the chart”
  • Date spine / calendar table
  • Rolling averages over gappy data

Benchmarks & rules of thumb

Both ends -
included by generate_series
1,000,000 -
rows in one INSERT … SELECT from generate_series
SQL Server 2022 -
added GENERATE_SERIES

Common mistakes & follow-ups

Common interview mistakes

  • Using COUNT(*) after the LEFT JOIN and reporting 1 signup on days with none.
  • Forgetting to cast timestamps to date, so the join to a date column doesn't match.
  • Filtering the data table in WHERE after the LEFT JOIN, which drops the empty days.

Likely interviewer follow-ups

  • How would you show daily sales including days with no sales?
  • How would you generate test data for a performance test?
  • How would you build a date spine in MySQL?
Interview tip: Show the spine + LEFT JOIN + COUNT(column) pattern and point out the COUNT(*) trap. Interviewers often hide exactly that bug in gap-filling questions.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Generating Series & Synthetic Data (GENERATE_SERIES) with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Bulk Data Loading (COPY, CSV Imports & Exports)
Next topic
Regular Expressions in SQL (REGEXP_MATCHES, REGEXP_REPLACE, ~)