Skip to content
Back to 50 Concepts
Topic 23 of 50foundationsBeginner

# 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.

Relational Invariant:Deterministic relational algebra contract evaluated by the Cost-Based Optimizer.

2. Explain Like I'm 5

Intuitive mental model for beginners

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 Trace
Interactive Engine Simulation

Date & Time Functions Visual Simulator

Step 1 of 3
SQL>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 Input

Step 1: Input & Parsing Stage

Engine Action: Validate SQL syntax and resolve schema metadata for Date & Time Functions
SQL Input

Initiating Date & Time Functions

Schema Catalog

Checking Table Invariants

How the Database Executes This:

The database engine inspects active tables, verifies permissions, and prepares the physical operation.

💡 Digital Clock and Calendar: Adding an interval moves the hands forward; DATE_TRUNC snaps the clock back to the start of the current period.

4. Real-World Example

A subscription billing engine calculating expiration dates and monthly revenue aggregates.

Subscription Math
started_atIntervalexpires_at
2026-01-15 10:00:00INTERVAL '30 days'2026-02-14 10:00:00
Relational walkthrough: started_at + INTERVAL '30 days' computes the exact renewal date.

5. SQL Syntax

ANSI SQL / PostgreSQL Dialect
Step 1: Current timestamps and interval arithmetic
SELECT
  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;
Step 2: Grouping by time bucket with DATE_TRUNC (PostgreSQL)
SELECT
  DATE_TRUNC('month', created_at) AS month_bucket,
  COUNT(*) AS signups
FROM users
GROUP BY month_bucket
ORDER BY month_bucket;
DATE_TRUNC collapses timestamps into clean time buckets (hour, day, week, month).
Step 3: Extracting specific date parts
SELECT EXTRACT(DOW FROM created_at) AS day_of_week FROM orders;
Extracts numeric year, month, day, hour, or day of week (0 = Sunday).

6. Important Rules & Behaviors

RuleBehavioral Explanation
TIMESTAMPTZ AlwaysAlways use TIMESTAMPTZ (timestamp with time zone) in PostgreSQL to store normalized UTC timestamps.
NOW() Transaction StabilityIn 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 TIMESTAMPTZTIMESTAMPTZ stores timestamps in UTC on disk and converts to client timezone; TIMESTAMP ignores timezones.
Index-friendly date truncationAvoid 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
);
Caution: Never use plain TIMESTAMP (without time zone) for financial or global web applications.

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

Scenario Question:

In PostgreSQL, what does DATE_TRUNC('month', TIMESTAMP '2026-04-18 14:32:00') return?

Select your answer: