Working With Calendars in SQL: Month Boundaries, Date Series and Missing Dates
Calendar techniques in SQL: first and last day of a month or quarter, leap years, generating date series, filling missing dates with zeros, a calendar table with holidays, the nth weekday of a month, and printing a month calendar.
kvi5hnuCode Sprout team member9 min readOn this page
Reports work with calendar periods: "sales per day this month, including days with no sales", "the last working day of each month", "how many working days in April?". These need two things that tables of events don't contain: the boundaries of periods, and a list of every date, including the ones on which nothing happened.
This article covers both. It builds on the date types and arithmetic of articles 39 and 40, and the techniques appear again in reporting (article 46) and gaps-and-islands problems (article 30).
Month, quarter and year boundaries
-- Month boundaries for any date
SELECT d,
CAST(DATE_TRUNC('month', d) AS date) AS first_day,
CAST(DATE_TRUNC('month', d) + INTERVAL '1 month' - INTERVAL '1 day' AS date) AS last_day,
CAST(DATE_TRUNC('month', d) + INTERVAL '1 month' AS date) AS next_month_start,
EXTRACT(DAY FROM DATE_TRUNC('month', d) + INTERVAL '1 month' - INTERVAL '1 day') AS days_in_month,
CAST(DATE_TRUNC('quarter', d) AS date) AS quarter_start
FROM (VALUES (DATE '2026-02-14'), (DATE '2028-02-14'), (DATE '2026-11-30')) AS t(d);
-- Leap years: is 29 February a real date? Equivalently, is the year 366 days long?
SELECT y,
(MAKE_DATE(y + 1, 1, 1) - MAKE_DATE(y, 1, 1)) = 366 AS is_leap_year
FROM (VALUES (1900), (2000), (2026), (2028)) AS t(y);
d | first_day | last_day | next_month_start | days_in_month | quarter_start
------------+------------+------------+------------------+---------------+---------------
2026-02-14 | 2026-02-01 | 2026-02-28 | 2026-03-01 | 28 | 2026-01-01
2028-02-14 | 2028-02-01 | 2028-02-29 | 2028-03-01 | 29 | 2028-01-01
2026-11-30 | 2026-11-01 | 2026-11-30 | 2026-12-01 | 30 | 2026-10-01
(3 rows)
y | is_leap_year
------+--------------
1900 | f
2000 | t
2026 | f
2028 | t
(4 rows)
With DATE_TRUNC and interval arithmetic, every boundary is one expression:
| Boundary | Expression |
|---|---|
| first day of the month | DATE_TRUNC('month', d) |
| first day of next month | DATE_TRUNC('month', d) + INTERVAL '1 month' |
| last day of the month | DATE_TRUNC('month', d) + INTERVAL '1 month' - INTERVAL '1 day' |
| first day of the quarter or year | DATE_TRUNC('quarter', d), DATE_TRUNC('year', d) |
| days in the month | EXTRACT(DAY FROM last day ) |
The "last day" pattern is "first day of the next month, minus one day", which always works, whatever the month's length. February has 28 days in 2026 and 29 in 2028.
For filters, you rarely need the last day: use the first day of the next period as an exclusive end, d >= first_day AND d < next_first_day (article 40). The last day is for display. As the end of a filter on timestamps, it would cut off everything after midnight on that day.
Leap years: a year is a leap year if it's divisible by 4, except century years, which must be divisible by 400. So 2000 was a leap year and 1900 wasn't. Rather than coding the rule, let the database do it: a year is a leap year if it has 366 days. MAKE_DATE(year, month, day) builds a date from numbers (PostgreSQL 9.4+).
Equivalents for the last day of the month: LAST_DAY(d) in MySQL and Oracle, EOMONTH(d) in SQL Server, and date(d, 'start of month', '+1 month', '-1 day') in SQLite. SQL Server uses DATEFROMPARTS(y, m, d) to build a date, and MySQL uses MAKEDATE(year, day_of_year) or STR_TO_DATE.
Generating a series of dates
Tables of events only contain the dates on which something happened. To report on every date, generate them. In PostgreSQL, generate_series(start, stop, step) returns one row per value:
-- Daily takings of a market stall; no trading on 4 March
CREATE TABLE daily_sales (
day DATE PRIMARY KEY,
amount DECIMAL(8, 2) NOT NULL
);
INSERT INTO daily_sales VALUES
(DATE '2026-03-01', 120.00),
(DATE '2026-03-02', 80.00),
(DATE '2026-03-03', 150.00),
(DATE '2026-03-05', 60.00),
(DATE '2026-03-06', 200.00),
(DATE '2026-03-07', 90.00),
(DATE '2026-03-08', 110.00);
-- One row per day in a range: generate_series
SELECT CAST(d AS date) AS day
FROM generate_series(DATE '2026-03-01', DATE '2026-03-08', INTERVAL '1 day') AS d;
-- Fill the gaps: every day, with 0 for days that have no sales row
SELECT CAST(d AS date) AS day,
COALESCE(s.amount, 0) AS amount,
s.day IS NULL AS missing
FROM generate_series(DATE '2026-03-01', DATE '2026-03-08', INTERVAL '1 day') AS d
LEFT JOIN daily_sales s ON s.day = d
ORDER BY day;
-- Series in other steps: the first day of each month in a half-year
SELECT CAST(m AS date) AS month_start
FROM generate_series(DATE '2026-01-01', DATE '2026-06-01', INTERVAL '1 month') AS m;
day
------------
2026-03-01
2026-03-02
2026-03-03
2026-03-04
2026-03-05
2026-03-06
2026-03-07
2026-03-08
(8 rows)
day | amount | missing
------------+--------+---------
2026-03-01 | 120.00 | f
2026-03-02 | 80.00 | f
2026-03-03 | 150.00 | f
2026-03-04 | 0 | t
2026-03-05 | 60.00 | f
2026-03-06 | 200.00 | f
2026-03-07 | 90.00 | f
2026-03-08 | 110.00 | f
(8 rows)
month_start
-------------
2026-01-01
2026-02-01
2026-03-01
2026-04-01
2026-05-01
2026-06-01
(6 rows)
- The first query lists every day from 1 to 8 March. With dates and an interval step,
generate_seriesreturnstimestamp with time zonevalues, so the query casts them todate. - The second query left-joins the sales to the series. Every date is kept, and 4 March, which has no sales row, gets NULL, which
COALESCEturns into 0. This is the standard way to produce reports and charts without missing days. Without it, a chart would join 3 March to 5 March directly, hiding the gap. - The third query steps by a month, giving the first day of each month.

The join condition must compare like with like. s.day = d works here because PostgreSQL compares the date column with the series' timestamps at midnight. If the event table holds timestamps, aggregate them to dates first: GROUP BY CAST(created_at AS date), then join the series to that.
A calendar table
Generating dates in every query works, but many teams keep a permanent calendar table instead: one row per date for, say, 30 years, with columns for everything reports need. That's about 11,000 rows, which is tiny.
-- A calendar table: one row per date, with the attributes reports need
CREATE TABLE calendar AS
SELECT CAST(d AS date) AS cal_date,
EXTRACT(YEAR FROM d)::int AS year,
EXTRACT(MONTH FROM d)::int AS month,
TO_CHAR(d, 'Mon') AS month_name,
EXTRACT(ISODOW FROM d)::int AS iso_dow,
TO_CHAR(d, 'Dy') AS day_name,
EXTRACT(ISODOW FROM d) >= 6 AS is_weekend,
EXTRACT(ISODOW FROM d) < 6 AS is_working_day
FROM generate_series(DATE '2026-01-01', DATE '2026-12-31', INTERVAL '1 day') AS d;
ALTER TABLE calendar ADD PRIMARY KEY (cal_date);
-- Holidays are data: mark them once, and every query respects them
UPDATE calendar SET is_working_day = false
WHERE cal_date IN (DATE '2026-04-03', DATE '2026-04-06', DATE '2026-12-25', DATE '2026-12-28');
SELECT month_name,
COUNT(*) AS days,
COUNT(*) FILTER (WHERE is_weekend) AS weekend_days,
COUNT(*) FILTER (WHERE is_working_day) AS working_days
FROM calendar
WHERE month IN (3, 4, 12)
GROUP BY month, month_name
ORDER BY month;
month_name | days | weekend_days | working_days
------------+------+--------------+--------------
Mar | 31 | 9 | 22
Apr | 30 | 8 | 20
Dec | 31 | 8 | 21
(3 rows)
The table is created with CREATE TABLE ... AS from a series (article 31), and given a primary key. Its columns precompute attributes: year, month, month name, weekday, weekend flag and working-day flag. The real advantage shows in the UPDATE: public holidays can't be computed by a simple rule, so they're stored as data. Here, Good Friday and Easter Monday 2026 (3 and 6 April) and the Christmas holidays are marked as non-working days. April then has 20 working days instead of 22, and every query that uses the calendar respects that automatically.
Typical columns in a production calendar table:
cal_date(primary key), year, quarter, month, day, day of year- ISO year and ISO week, weekday number and name
is_weekend,is_holiday,holiday_name,is_working_day- fiscal year, fiscal quarter and fiscal period, which often don't match calendar ones
- the first and last day of the month and week, and "working day number within the month"
With a calendar table, "the third working day after the order date" (article 40) becomes a simple query, and the definitions of fiscal periods live in one place.
The nth weekday of a month
Recurring dates like "the first Monday of the month" or "the last Friday" are common in scheduling and payroll:
-- The first Monday and the last Friday of each month in the first half of 2026
SELECT CAST(m AS date) AS month_start,
CAST(m + ((8 - EXTRACT(ISODOW FROM m)::int) % 7) * INTERVAL '1 day' AS date) AS first_monday,
(SELECT MAX(CAST(d AS date))
FROM generate_series(m, m + INTERVAL '1 month' - INTERVAL '1 day', INTERVAL '1 day') AS d
WHERE EXTRACT(ISODOW FROM d) = 5) AS last_friday
FROM generate_series(DATE '2026-01-01', DATE '2026-06-01', INTERVAL '1 month') AS m;
month_start | first_monday | last_friday
-------------+--------------+-------------
2026-01-01 | 2026-01-05 | 2026-01-30
2026-02-01 | 2026-02-02 | 2026-02-27
2026-03-01 | 2026-03-02 | 2026-03-27
2026-04-01 | 2026-04-06 | 2026-04-24
2026-05-01 | 2026-05-04 | 2026-05-29
2026-06-01 | 2026-06-01 | 2026-06-26
(6 rows)
- First Monday: from the first day of the month, move forward
(8 - ISODOW) % 7days. If the month starts on a Monday (ISO day 1), that's 0 days. If it starts on a Thursday (4), it's 4 days. June 2026 starts on a Monday, so its first Monday is 1 June. For another weekdayw, the formula is(w + 7 - ISODOW) % 7. - Last Friday: generate the month's days and take the latest Friday with
MAX. A formula also works, starting from the last day and stepping back, but the series is easier to read and to change, for example to "the last working day" by adding a calendar-table condition.
With a calendar table, add a column such as "occurrence of this weekday within the month", and "the second Tuesday" becomes WHERE iso_dow = 2 AND weekday_occurrence = 2.
A printed month calendar
The classic calendar layout, one row per week and one column per weekday, is a pivot (article 44) of a date series:
-- March 2026 as a printed calendar: one row per ISO week, one column per weekday
SELECT EXTRACT(WEEK FROM d)::int AS wk,
MAX(CASE WHEN EXTRACT(ISODOW FROM d) = 1 THEN EXTRACT(DAY FROM d)::int END) AS mo,
MAX(CASE WHEN EXTRACT(ISODOW FROM d) = 2 THEN EXTRACT(DAY FROM d)::int END) AS tu,
MAX(CASE WHEN EXTRACT(ISODOW FROM d) = 3 THEN EXTRACT(DAY FROM d)::int END) AS we,
MAX(CASE WHEN EXTRACT(ISODOW FROM d) = 4 THEN EXTRACT(DAY FROM d)::int END) AS th,
MAX(CASE WHEN EXTRACT(ISODOW FROM d) = 5 THEN EXTRACT(DAY FROM d)::int END) AS fr,
MAX(CASE WHEN EXTRACT(ISODOW FROM d) = 6 THEN EXTRACT(DAY FROM d)::int END) AS sa,
MAX(CASE WHEN EXTRACT(ISODOW FROM d) = 7 THEN EXTRACT(DAY FROM d)::int END) AS su
FROM generate_series(DATE '2026-03-01', DATE '2026-03-31', INTERVAL '1 day') AS d
GROUP BY EXTRACT(WEEK FROM d)
ORDER BY MIN(d);
wk | mo | tu | we | th | fr | sa | su
----+----+----+----+----+----+----+----
9 | | | | | | | 1
10 | 2 | 3 | 4 | 5 | 6 | 7 | 8
11 | 9 | 10 | 11 | 12 | 13 | 14 | 15
12 | 16 | 17 | 18 | 19 | 20 | 21 | 22
13 | 23 | 24 | 25 | 26 | 27 | 28 | 29
14 | 30 | 31 | | | | |
(6 rows)
Each date is grouped by its ISO week, and conditional aggregation (article 21) places its day number in the column for its weekday. MAX picks the single value in each cell, and empty cells are NULL. The rows are ordered by the earliest date in each week, because ISO week numbers wrap around at the start of a year. March 2026 starts on a Sunday, so the first week has only one day.
Date series without generate_series
generate_series is PostgreSQL's. Other databases need another way to produce a series:
-- Daily takings of a market stall; no trading on 4 March
CREATE TABLE daily_sales (
day DATE PRIMARY KEY,
amount DECIMAL(8, 2) NOT NULL
);
INSERT INTO daily_sales VALUES
(DATE '2026-03-01', 120.00),
(DATE '2026-03-02', 80.00),
(DATE '2026-03-03', 150.00),
(DATE '2026-03-05', 60.00),
(DATE '2026-03-06', 200.00),
(DATE '2026-03-07', 90.00),
(DATE '2026-03-08', 110.00);
-- A portable date series with a recursive CTE (for databases without generate_series)
WITH RECURSIVE days (day) AS (
SELECT DATE '2026-03-01'
UNION ALL
SELECT day + 1
FROM days
WHERE day < DATE '2026-03-08'
)
SELECT d.day, COALESCE(s.amount, 0) AS amount
FROM days d
LEFT JOIN daily_sales s ON s.day = d.day
ORDER BY d.day;
day | amount
------------+--------
2026-03-01 | 120.00
2026-03-02 | 80.00
2026-03-03 | 150.00
2026-03-04 | 0
2026-03-05 | 60.00
2026-03-06 | 200.00
2026-03-07 | 90.00
2026-03-08 | 110.00
(8 rows)
A recursive CTE (article 25) starts with the first date and adds one day per step until it reaches the end. The same shape works elsewhere with each database's date arithmetic: MySQL 8 needs day + INTERVAL 1 DAY (plain + 1 turns the date into a number), SQLite uses text dates and date(day, '+1 day'), and SQL Server and Oracle drop the word RECURSIVE (SQL Server also uses DATEADD(day, 1, day)). It's fine for a few thousand rows. Remember the recursion limits: MySQL stops at 1,000 levels by default (cte_max_recursion_depth) and SQL Server at 100 (OPTION (MAXRECURSION 0) removes the limit).
Other options:
- SQL Server 2022:
GENERATE_SERIES(0, 30)returns numbers, whichDATEADD(day, value, start)turns into dates. - Oracle:
SELECT start_date + LEVEL - 1 FROM dual CONNECT BY LEVEL <= n. - SQLite: the
generate_seriestable-valued function, included in the command-line shell, or a recursive CTE. - Anywhere: a permanent numbers table or calendar table, which is often the fastest option.
What's current
- SQL Server 2022 added
GENERATE_SERIESfor numbers, andDATE_BUCKETandDATETRUNCfor period boundaries. - PostgreSQL 16 added
generate_seriesfortimestamptzvalues with a time zone argument, so daily series step correctly across daylight saving changes. - MySQL 9 still has no series function. Use a recursive CTE or a numbers table.
Common questions
How do I get the last day of the month?
DATE_TRUNC('month', d) + INTERVAL '1 month' - INTERVAL '1 day' in PostgreSQL, LAST_DAY(d) in MySQL and Oracle, EOMONTH(d) in SQL Server.
How do I include days with no data in a report?
Generate every date with generate_series or a recursive CTE, left-join the data to it, and use COALESCE for the missing values.
Is a calendar table worth it? Yes, for any system with reports on working days, holidays or fiscal periods. It's small, simple, and makes those rules data instead of code.
How do I check for a leap year?
Test whether the year has 366 days, or whether MAKE_DATE(y, 2, 29) is a valid date. The rule is: divisible by 4, except centuries not divisible by 400.
How do I find the first Monday of a month?
Add (8 - ISODOW(first day)) % 7 days to the first day of the month.
Summary
DATE_TRUNCgives the first day of a period. The last day is the next period's first day minus one day.LAST_DAYandEOMONTHexist in other databases.- Use exclusive ends,
< next period start, in filters. generate_seriescreates one row per date. Left-join data to it and useCOALESCEto show missing dates as zeros.- A calendar table stores one row per date with precomputed attributes, holidays and fiscal periods.
- Weekday-of-month calculations use
ISODOWarithmetic or a date series withMINorMAX. - Without
generate_series, use a recursive CTE,GENERATE_SERIESin SQL Server 2022,CONNECT BY LEVELin Oracle, or a numbers table.
Practice questions
Write an expression that returns the last day of the month containing DATE '2026-04-17', as a date.
Answer
CAST(DATE_TRUNC('month', DATE '2026-04-17') + INTERVAL '1 month' - INTERVAL '1 day' AS date)
It returns 2026-04-30.
Write a query that lists every day from 1 to 8 March with the number of orders placed that day, including days with no orders.
Answer
SELECT CAST(d AS date) AS day, COUNT(o.order_id) AS orders
FROM generate_series(DATE '2026-03-01', DATE '2026-03-08', INTERVAL '1 day') AS d
LEFT JOIN orders o ON o.placed_on = d
GROUP BY d
ORDER BY d;
COUNT(o.order_id) counts only matched orders, so days with none get 0. Orders 101 (2 March) and 102 (5 March) give 1 on those days.
What does (8 - EXTRACT(ISODOW FROM DATE '2026-03-01')::int) % 7 return, and what's the first Monday of March 2026?
Answer
1 March 2026 is a Sunday, ISO day 7, so the expression is (8 − 7) % 7 = 1. The first Monday is 1 March + 1 day = 2 March.
Why is a calendar table better than computing working days with ISODOW < 6 in every query?
Answer
Weekday arithmetic can't know about public holidays, which differ by country and change every year. A calendar table stores them once, so every query that counts or finds working days gets them right, and changing a rule means updating data, not rewriting queries.
In MySQL, a recursive CTE that generates the dates of the next five years fails. Why, and what's the fix?
Answer
Five years is about 1,826 days, so the CTE recurses more than 1,000 times, which exceeds MySQL's default cte_max_recursion_depth of 1,000. Raise it with SET SESSION cte_max_recursion_depth = 5000, or use a numbers or calendar table.
Previous: Date Arithmetic in SQL: Adding Intervals and Measuring Differences

More in SQL Course
Quiz: SQL Dialect Differences (PostgreSQL, MySQL, SQL Server, Oracle, SQLite)
Twenty-four questions on how the major SQL databases differ: limiting rows, concatenation, empty strings, identifier case, upserts, identity columns, transactional DDL, error handling, isolation defaults, booleans, set operations, RETURNING, dates and typing.
Quiz: SQL Delicate Details
Twenty-five questions on SQL's subtle corners: NULLs in aggregates, IN and CHECK, sort order of NULLs, rounding, CHAR padding, window frame defaults, identity gaps, LIKE escapes, empty groups, set operations and multi-column updates.
Quiz: SQL Interview Questions
Thirty SQL questions of the kind asked in developer and analyst interviews: WHERE vs HAVING, DELETE vs TRUNCATE, keys, joins, duplicates, Nth-highest values, window functions, ACID, isolation, locking, indexes, views, procedures and performance.
Quiz: SQL Course Final Exam (All 15 Parts)
The final exam for the SQL course: thirty questions across all fifteen parts, from query processing, NULLs, joins and aggregation through windows, data changes, types, design, indexes, security, transactions, procedural SQL and tuning.
Discussion
Sign in to ask a question or share what you learned.