Date/Time Functions & Ranges in SQL
Half-open ranges, EXTRACT, DATE_TRUNC, INTERVAL
Compare typed literals (DATE '2024-01-01'), range half-open for timestamp days (>= start AND < next) — BETWEEN misses end-day times. EXTRACT(YEAR FROM x) and DATE_TRUNC('month', x) bucket; INTERVAL arithmetic offsets (created_at + INTERVAL '7 days'). Never compare dates as strings; never wrap indexed columns in functions (unsargable). Store TIMESTAMPTZ, display AT TIME ZONE.
Range half-open
>= start AND < next keeps end-day times; BETWEEN drops them.
Truncate to bucket
DATE_TRUNC(month, x) for rollups; EXTRACT for parts.
Offset with INTERVAL
NOW() - INTERVAL 7 days — rolling windows without app math.
Zone at the edge
TIMESTAMPTZ UTC inside; AT TIME ZONE on display. Never VARCHAR dates.
1SELECT * FROM orders WHERE created_at >= DATE '2024-01-01' AND created_at < DATE '2024-02-01';
| order_id | created_at |
|---|---|
| order_101 | 2024-01-15 |
| order_102 | 2024-01-31 |
Half-open keeps Jan-31 afternoon rows that BETWEEN '2024-01-01' AND '2024-01-31' would drop at midnight. Raw column stays bare — index seeks instead of scanning.
January done right
Keeps Jan-31 afternoon rows.
1SELECT * FROM orders WHERE created_at >= DATE '2024-01-01' AND created_at < DATE '2024-02-01';
| order_id | created_at |
|---|---|
| order_101 | 2024-01-15 |
| order_102 | 2024-01-31 |
Monthly buckets + last-7-days
Truncate groups; interval filters.
1SELECT DATE_TRUNC('month', created_at) AS m, COUNT(*) FROM orders GROUP BY m;2SELECT * FROM orders WHERE created_at >= NOW() - INTERVAL '7 days';
| month | orders |
|---|---|
| 2024-01-01 | 2 |
| 2024-02-01 | 1 |
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Take the queries you just visualized and see the data structures that power real databases.