SQL Practice Logo

SQLPractice Online

Date & Time Functions: Concept

Module: SQL Fundamentals

Date and time functions manipulate temporal data - extract parts, calculate differences, format for display, and handle timezones.

**Date & Time Types:**

- DATE: Only calendar date (2024-12-25)

- TIME: Only time of day (14:30:45)

- TIMESTAMP: Date + time, no timezone

- TIMESTAMPTZ: Date + time WITH timezone (PostgreSQL)

**The Global Timezone Problem:**

Store all timestamps in UTC, convert to local timezone for display.

Database stores once (UTC), converts as needed.

**Extracting Date Parts:**

- EXTRACT(YEAR FROM date): Returns year as number

- EXTRACT(MONTH FROM date): Returns month (1-12)

- EXTRACT(DAY FROM date): Returns day (1-31)

- DATE_TRUNC('month', date): Round down to month start

**Date Arithmetic:**

- date + INTERVAL '7 days': Add 7 days

- date - INTERVAL '1 month': Subtract 1 month

- CURRENT_DATE - order_date: Days between dates

**Timezone Conversion:**

- AT TIME ZONE 'UTC': Convert to UTC

- AT TIME ZONE 'America/New_York': Convert to EST/EDT

Every developer faces temporal bugs. Timezone handling is the #1 source of production bugs in global applications. Stripe (payments), Airbnb (booking), Uber (scheduling) all depend on perfect date/time logic. Understanding TIMESTAMPTZ, UTC storage, and interval calculations is non-negotiable.

An e-commerce platform ships orders worldwide. Users in different timezones see order status: "Order placed 2 hours ago". Subscription billing must charge exactly at "2024-12-25 00:00:00 user's local time" in 150 countries. Reports show sales by hour, but must account for 24 different timezones.