Date Subtraction Yields Days Or Interval

Subtracting dates returns integer days while subtracting timestamps returns an interval, so mixing the two types changes the result's shape.

SqlData Fetching

Code

sqlsnippet
16 lines
-- 相同的"相减",操作数类型决定结果的形状:
-- date - date 得整数天数;timestamp - timestamp 得 interval
SELECT
    check_in,
    check_out,
    check_out::date - check_in::date AS nights,        -- integer
    check_out - check_in             AS stay_interval, -- interval
    age(check_out, check_in)         AS humanized      -- interval(按年月日拆分)
FROM (VALUES
    (TIMESTAMP '2026-11-01 14:00', TIMESTAMP '2026-11-09 11:30')
) AS stay(check_in, check_out);

-- interval 可以继续参与算术:加时长、乘系数都是一等运算
SELECT
    TIMESTAMP '2026-11-14 09:00' + INTERVAL '90 minutes' AS meeting_end,
    INTERVAL '7 days' * 12 AS quarter_lead_time;

How it works

The same subtraction operator produces three differently shaped results depending on the operand types. Over one VALUES row — check_in = TIMESTAMP '2026-11-01 14:00', check_out = TIMESTAMP '2026-11-09 11:30' — the first statement returns: check_out::date - check_in::date AS nights casts both sides to date first, so the result is an integer day count; check_out - check_in AS stay_interval subtracts the timestamps directly and returns an interval; age(check_out, check_in) AS humanized also returns an interval, but split into years, months, and days.

The second statement shows intervals participating in further arithmetic: TIMESTAMP '2026-11-14 09:00' + INTERVAL '90 minutes' AS meeting_end adds a duration to a timestamp, and INTERVAL '7 days' * 12 AS quarter_lead_time scales an interval by an integer factor.

What to watch for

  • Mixing the two operand shapes changes the result’s type: date - date is an integer, timestamp - timestamp is an interval — the file’s comment spells out this rule, and the two aliased columns (nights, stay_interval) demonstrate it on the same pair of values.

Using it

Both statements are self-contained SELECTs over literal values, so they run against PostgreSQL without any table; the column aliases name each result shape (nights, stay_interval, humanized, meeting_end, quarter_lead_time).

Key statements

SELECT
TIMESTAMP '2026-11-14 09:00' + INTERVAL '90 minutes' AS meeting_end,
INTERVAL '7 days' * 12 AS quarter_lead_time;

Interactive Tools for This Topic