// SQL snippet

Find rows expiring within N days in SQL

Renewal notices and cleanup jobs key off expiry dates: soon-to-expire, already-expired, and never-expires rows each need different handling.

Main statement
PostgreSQL
同時涵蓋
SQL Server MySQL

The task

One CASE splits the timeline into expired, expiring soon and active, with NULL handled as never expires.

The snippet

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

PostgreSQL
SELECT
    subscription_id,
    expires_at,
    CASE
        WHEN expires_at IS NULL THEN 'never'
        WHEN expires_at < CURRENT_TIMESTAMP THEN 'expired'
        WHEN expires_at < CURRENT_TIMESTAMP + interval '30 days' THEN 'expiring'
        ELSE 'active'
    END AS status
FROM subscriptions;

它的運作方式

NULL means no expiry, so the first CASE branch must run before any comparison, because NULL < anything is NULL, not true. The order of the WHEN branches matters too: 'expired' must be tested before 'expiring', because an expired row also satisfies expires_at < now + 30 days. Use the clock that matches how expires_at is stored: SYSUTCDATETIME() in the SQL Server variant assumes UTC values, while CURRENT_TIMESTAMP and NOW() follow the session time zone.

Variations

SQL Server

SQL Server
SELECT
    subscription_id,
    expires_at,
    CASE
        WHEN expires_at IS NULL THEN 'never'
        WHEN expires_at < SYSUTCDATETIME() THEN 'expired'
        WHEN expires_at < DATEADD(DAY, 30, SYSUTCDATETIME()) THEN 'expiring'
        ELSE 'active'
    END AS status
FROM subscriptions;

MySQL

MySQL
SELECT
    subscription_id,
    expires_at,
    CASE
        WHEN expires_at IS NULL THEN 'never'
        WHEN expires_at < NOW() THEN 'expired'
        WHEN expires_at < NOW() + INTERVAL 30 DAY THEN 'expiring'
        ELSE 'active'
    END AS status
FROM subscriptions;

Questions that come up

Why compare to the database clock, not the app clock?

Using CURRENT_TIMESTAMP / SYSUTCDATETIME() keeps every row evaluated against one clock and one time zone: the database's. App-server clocks drift and may run in local time, which silently shifts who counts as 'expiring'.

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.