# Topic 23: Date & Time Functions
NOW, CURRENT_DATE, EXTRACT, DATE_TRUNC, INTERVAL math, and UTC timestamp best practices.
1. Definition
SQL date and time functions handle temporal calculations, timezone conversions, period truncations, and date arithmetic.
2. Explain Like I'm 5
Date functions are a calendar and clock inside your database: they tell you what time it is, add 7 days to an expiration date, or tell you what day of the week it was.
3. Animation & Visual Simulation
Interactive Engine TraceDate & Time Functions Visual Simulator
SELECT DATE_TRUNC('day', created_at) AS day, COUNT(*) AS daily_sales
FROM orders
WHERE created_at >= NOW() - INTERVAL '30 days'
GROUP BY day
ORDER BY day;Active InputStep 1: Input & Parsing Stage
Initiating Date & Time Functions
Checking Table Invariants
The database engine inspects active tables, verifies permissions, and prepares the physical operation.
4. Real-World Example
A subscription billing engine calculating expiration dates and monthly revenue aggregates.
| started_at | Interval | expires_at |
|---|---|---|
| 2026-01-15 10:00:00 | INTERVAL '30 days' | 2026-02-14 10:00:00 |
5. SQL Syntax
ANSI SQL / PostgreSQL DialectSELECT CURRENT_DATE AS today, CURRENT_TIMESTAMP AS now_utc, CURRENT_TIMESTAMP + INTERVAL '7 days' AS one_week_later, CURRENT_TIMESTAMP - INTERVAL '1 month' AS last_month;
SELECT
DATE_TRUNC('month', created_at) AS month_bucket,
COUNT(*) AS signups
FROM users
GROUP BY month_bucket
ORDER BY month_bucket;SELECT EXTRACT(DOW FROM created_at) AS day_of_week FROM orders;
6. Important Rules & Behaviors
| Rule | Behavioral Explanation |
|---|---|
| TIMESTAMPTZ Always | Always use TIMESTAMPTZ (timestamp with time zone) in PostgreSQL to store normalized UTC timestamps. |
| NOW() Transaction Stability | In PostgreSQL, NOW() returns the start timestamp of the current transaction and does not change between statements in the same transaction. |
| CLOCK_TIMESTAMP() | If you need the true wall-clock time as a statement executes, use CLOCK_TIMESTAMP(). |
| TIMESTAMP vs TIMESTAMPTZ | TIMESTAMPTZ stores timestamps in UTC on disk and converts to client timezone; TIMESTAMP ignores timezones. |
| Index-friendly date truncation | Avoid DATE_TRUNC in WHERE clauses; use half-open range queries on raw timestamp columns. |
7. Deep Dive: Timestamp with Time Zone (TIMESTAMPTZ) Storage Reality
A common misconception is that TIMESTAMPTZ stores a string like "2026-01-01+05:30". In reality, PostgreSQL converts all incoming timestamps to UTC and stores them as an 8-byte integer representing microseconds since 2000-01-01 UTC.
-- Always use TIMESTAMPTZ for distributed systems: CREATE TABLE audit_trail ( id BIGINT PRIMARY KEY, occurred_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP );
8. Advantages & Disadvantages
Advantages
- •Native timezone math eliminates client-side timezone calculation bugs.
- •DATE_TRUNC simplifies time-series analytics.
Disadvantages & Trade-offs
- •Daylight savings transitions can complicate interval calculations across borders.
9. Common Interview Questions
Q1.What is the critical difference between TIMESTAMP WITHOUT TIME ZONE and TIMESTAMPTZ in PostgreSQL?
TIMESTAMPTZ converts incoming timestamps to UTC and stores them as an 8-byte UTC integer on disk. When read, it converts UTC to the client session’s local timezone. TIMESTAMP WITHOUT TIME ZONE stores the raw literal numbers without timezone metadata, making it impossible to determine when events actually occurred across distributed servers. Production distributed systems should ALWAYS use TIMESTAMPTZ.
Q2.Why is "WHERE DATE_TRUNC('day', created_at) = '2026-01-01'" a performance bug, and how do you fix it?
Wrapping created_at in DATE_TRUNC() destroys SARGability: the engine must execute the DATE_TRUNC function for every single row in the table, preventing any B-Tree index on created_at from being used. The correct index-friendly pattern is a half-open interval on the raw column: WHERE created_at >= '2026-01-01 00:00:00+00' AND created_at < '2026-01-02 00:00:00+00'.
Q3.How does interval arithmetic work in SQL and how do you calculate time differences?
Relational engines support INTERVAL types. You can add or subtract durations directly: NOW() - INTERVAL '30 days'. Subtracting two timestamps (ts2 - ts1) yields an INTERVAL representing exact days, hours, minutes, and seconds. EXTRACT(EPOCH FROM (ts2 - ts1)) converts the duration into total seconds as a floating-point number.
Q4.What is the difference between NOW(), CURRENT_TIMESTAMP, and CLOCK_TIMESTAMP() in PostgreSQL?
NOW() and CURRENT_TIMESTAMP return the start time of the CURRENT TRANSACTION and remain frozen throughout the transaction (ensuring all rows written by one transaction share an identical timestamp). CLOCK_TIMESTAMP() returns the actual real-world wall-clock time at the exact microsecond the function is executed.
Q5.How do you handle Daylight Saving Time (DST) edge cases in SQL?
DST transitions create ambiguity: an hour can be repeated (fall back) or skipped (spring forward). By storing all timestamps as UTC using TIMESTAMPTZ, internal math is strictly monotonic (zero leap hours or skipped hours). Local conversion only happens during presentation at the application edge using AT TIME ZONE 'America/New_York'.
10. Interview-Ready Answer
“SQL provides robust date and time manipulation through INTERVAL arithmetic, EXTRACT, and DATE_TRUNC. In production, always use TIMESTAMPTZ to normalize records to UTC and prevent timezone drift.”
11. Quick Test
In PostgreSQL, what does DATE_TRUNC('month', TIMESTAMP '2026-04-18 14:32:00') return?