Recursive CTE Recurring Event Expansion

Expand recurring calendar events with a recursive CTE that advances each rule by its own step interval until the end date.

SqlData Fetching

Code

snippet
-- WITH RECURSIVE expands recurring events: each rule advances by its own step until end_date
CREATE TABLE event_rules (
    rule_id   int PRIMARY KEY,
    title     text NOT NULL,
    starts_on date NOT NULL,
    step      interval NOT NULL,
    end_date  date NOT NULL
);

INSERT INTO event_rules VALUES
    (1, 'weekly sync',   DATE '2026-01-05', INTERVAL '7 days',  DATE '2026-02-01'),
    (2, 'monthly close', DATE '2026-01-31', INTERVAL '1 month', DATE '2026-04-30');

WITH RECURSIVE occurrences AS (
    -- anchor: the first day of each rule (a date, matching the recursive arm's cast)
    SELECT rule_id, title, starts_on AS occurs_on, step, end_date
    FROM event_rules
    UNION ALL
    -- recursive: (occurs_on + step)::date keeps both arms one column type; strictly increasing dates guarantee termination
    SELECT rule_id, title, (occurs_on + step)::date AS occurs_on, step, end_date
    FROM occurrences
    WHERE occurs_on + step <= end_date
)
SELECT rule_id, title, occurs_on::date AS occurs_on
FROM occurrences
ORDER BY rule_id, occurs_on;

A walk through the code

SELECT / INSERT / CREATE statements share the script, touching event_rules and occurrences.

Mechanically, the statements are built from: a CTE (WITH … AS) that names an intermediate result before the main query; a WHERE clause that keeps only the rows a statement is meant to touch; an ORDER BY that fixes the output order; a UNION merging rows produced by different queries; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.

Applying it

The event_rules table is the working surface here.

Statements that matter

INSERT INTO event_rules VALUES
    (1, 'weekly sync',   DATE '2026-01-05', INTERVAL '7 days',  DATE '2026-02-01'),
    (2, 'monthly close', DATE '2026-01-31', INTERVAL '1 month', DATE '2026-04-30');
CREATE TABLE event_rules (
    rule_id   int PRIMARY KEY,
    title     text NOT NULL,
    starts_on date NOT NULL,
    step      interval NOT NULL,
    end_date  date NOT NULL
);

Interactive Tools for This Topic

FAQ

Which tables appear in this script?
`event_rules`, `occurrences`.