// SQL snippet

Count business days between two dates in SQL

SLA clocks and delivery estimates count working days only. Weekends are computable; holidays need a lookup table.

Main statement
SQL Server
还支持
PostgreSQL

The task

Generate one row per calendar day between the dates, keep the weekdays, and count them.

The snippet

Written for SQL Server. Versions for PostgreSQL are under Variations.

SQL Server
DECLARE @start_date DATE = '2026-03-02', @end_date DATE = '2026-03-31';

WITH days AS (
    SELECT @start_date AS d
    UNION ALL
    SELECT DATEADD(DAY, 1, d) FROM days WHERE d < @end_date
)
SELECT COUNT(*) AS business_days
FROM days
WHERE (DATEPART(WEEKDAY, d) + @@DATEFIRST - 1) % 7 NOT IN (0, 6)
OPTION (MAXRECURSION 0);

工作原理

The recursive CTE walks one day at a time from start to end, and the WHERE drops Saturdays and Sundays: adding @@DATEFIRST to DATEPART(WEEKDAY) makes Sunday 0 and Saturday 6 whatever the session's DATEFIRST is, and unlike DATENAME it does not depend on the session language. March 2026 has 22 weekdays. MAXRECURSION 0 removes the 100-level default cap so long ranges work. For holidays, add AND d NOT IN (SELECT holiday_date FROM holidays).

Variations

PostgreSQL

PostgreSQL
SELECT COUNT(*) AS business_days
FROM generate_series(DATE '2026-03-02', DATE '2026-03-31', interval '1 day') AS g(d)
WHERE EXTRACT(ISODOW FROM d) < 6;

Questions that come up

Does this count the start date?

Both queries count both ends: the recursion emits the start date and keeps going until it has emitted the end date, and generate_series includes its upper bound. For a 'days until' style count that excludes the start, begin the series one day later; decide the convention once and document it.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.