Business Days With Generate Series
Count business days between two dates with generate_series over the day range and an ISODOW filter, keeping Monday-Friday and dropping weekends.
Code
-- 两个日期之间的工作日天数:ISODOW 周一=1、周日=7
WITH span AS (
SELECT date '2026-01-01' AS start_day,
date '2026-01-31' AS end_day
),
days AS (
SELECT generate_series(start_day, end_day, interval '1 day')::date AS day
FROM span
)
SELECT COUNT(*) FILTER (WHERE EXTRACT(ISODOW FROM day) < 6) AS business_days,
COUNT(*) AS calendar_days
FROM days;How it works
What runs is SELECT, with span, day and days as the object involved.
Breaking the statements into their working parts: a CTE (WITH … AS) that names an intermediate result before the main query; a WHERE clause limiting a statement to the rows that qualify; COUNT aggregation.
Putting it to use
Run the statement against the span table.
Interactive Tools for This Topic
Business Days CalculatorCount the weekdays between two dates, excluding weekends and any holidays you list, and see how many calendar and weekend days are involved.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Age CalculatorCalculate exact age in years, months, and days between a birth date and a reference date, plus total days and the next birthday countdown.
FAQ
- Which relations are involved here?
- `span`, `day`, `days` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.