Generate Series Calendar Table
Create a date calendar using generate_series for gap-free time series reporting and joins.
-- Generate a calendar of dates
WITH calendar AS (
SELECT d::date AS date
FROM generate_series(
'2025-01-01'::date,
'2025-12-31'::date,
'1 day'::interval
) AS d
)
SELECT
c.date,
COALESCE(SUM(o.amount), 0) AS daily_revenue,
COUNT(o.id) AS order_count
FROM calendar c
LEFT JOIN orders o ON o.created_at::date = c.date
GROUP BY c.date
ORDER BY c.date;
-- Generate hourly slots
SELECT generate_series(
'2025-01-01 00:00'::timestamp,
'2025-01-01 23:00'::timestamp,
'1 hour'::interval
) AS slot;Use Cases
- Daily revenue reports
- Gap-free time series
- Attendance tracking
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
String Aggregation with GROUP BY
Concatenate grouped values into comma-separated strings using STRING_AGG with ordering and filtering.
SQL Window Functions for Analytics
Advanced SQL window functions for running totals, rankings, moving averages, and gap analysis.
Keyset Pagination vs Offset
Efficient keyset (cursor) pagination pattern compared to traditional OFFSET for large datasets in PostgreSQL.
UPSERT with ON CONFLICT
Insert or update rows atomically using PostgreSQL ON CONFLICT clause with partial indexes and conditions.