Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 32/ 160
02. Aggregations, Functions & Data Manipulation

Date Arithmetic, Intervals & Formatting (AGE, NOW(), CURRENT_DATE, TO_CHAR)

Add intervals, compute ages, and format dates for humans and exports.

IntermediateIntervals · NOW / CURRENT_DATE3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

You can add days or months to dates, measure the gap between two dates, and turn dates into nicely written text.

Think of it like…

A wall calendar and a stopwatch: the calendar moves you forward a month to the same date when it can (and the last day when it can't), while the stopwatch measures exact elapsed hours and minutes.

Where you’ve seen it

Subscriptions renewing in the next 7 days: SELECT id, renews_on FROM subscriptions WHERE renews_on >= CURRENT_DATE AND renews_on < CURRENT_DATE + 7; and average resolution time in hours: SELECT AVG(EXTRACT(EPOCH FROM resolved_at - created_at) / 3600) FROM tickets;

Words you’ll hear

interval
A length of time such as '3 days' or '1 month 2 hours' (PostgreSQL).
NOW() / CURRENT_TIMESTAMP
The start time of the current transaction; clock_timestamp() is the actual current time.
AGE(a, b)
Symbolic difference in years, months and days.
TO_CHAR / DATE_FORMAT
Formats a date or timestamp as text using a pattern.

Visual diagram

Loading interactive diagram

Theory & example queries

Adding and subtracting

In PostgreSQL, adding an integer to a date adds days; adding an interval works for any unit: created_at + interval '30 minutes', renews_on + interval '1 year'. Month arithmetic is calendar-aware and clamps to the last valid day, so 31 January plus one month is 28 February (29 in a leap year), and adding a month twice doesn't always equal adding two months.

Subtracting two dates gives an integer number of days; subtracting timestamps gives an interval. To get hours or minutes as a number, extract epoch seconds and divide: EXTRACT(EPOCH FROM resolved_at - created_at) / 3600. AGE(later, earlier) returns a symbolic interval, which is useful for ages and tenure: EXTRACT(YEAR FROM AGE(CURRENT_DATE, birth_date)).

Days and hours between eventsQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  shipped_on - ordered_on AS days_to_ship,3  ROUND(4    EXTRACT(5      EPOCH6      FROM7        delivered_at - shipped_at8    ) / 3600,9    110  ) AS hours_in_transit11FROM12  shipments;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/12
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output3 sample rows
Expected output
days_to_shiphours_in_transit
118.5
231
06.8

Note: Illustrative shipment intervals; exact timestamp precision and date semantics depend on the dialect.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Intervals move dates; subtraction measures gaps; months clamp at month end.

Current time, dialects and formatting

NOW() and CURRENT_TIMESTAMP return the time the current transaction started, so every row inserted in one transaction gets the same timestamp; clock_timestamp() changes during the statement. CURRENT_DATE depends on the session's timezone. Dialects differ: MySQL uses DATE_ADD(d, INTERVAL 7 DAY), DATEDIFF(a, b) and TIMESTAMPDIFF(HOUR, a, b). SQL Server's DATEDIFF(year, '2025-12-31', '2026-01-01') returns 1, because it counts boundaries crossed rather than elapsed time.

Format dates only for final display, with TO_CHAR in PostgreSQL (TO_CHAR(created_at, 'DD Mon YYYY HH24:MI'), using FM to drop padding) or DATE_FORMAT in MySQL. Formatted text sorts alphabetically and can't be compared as dates, so keep calculations, filters and sorting on the real date columns.

A readable label, sorted correctlyQuery example
1Input dataStart from the source rows or state that the statement sees.
daily_revenue
4 rows
daily_revenue sample rows
dayamount
2026-11-15100
2026-11-17200
2026-11-2150
2026-11-2275
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  TO_CHAR(DAY, 'FMDD Mon YYYY') AS label,3  revenue4FROM5  daily_revenue6ORDER BY7  DAY;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/7
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output3 sample rows
Expected output
labelrevenue
1 Nov 202618200
2 Nov 202619550
3 Nov 20269100

Note: Illustrative dates and revenue; TO_CHAR syntax and output spelling are database-specific.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Sort by the date, show the text.

Key takeaway: Know what NOW() means; format at the very end; check dialect behaviour.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Question

Decide: move or measure?

Are you computing a new date (due date, renewal) or a gap (days to ship, hours to resolve)?

Focus at this step

due = created + 14 · gap = shipped − ordered

What to watch at this step
Two
different operations
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

Date arithmetic adds and subtracts time: in PostgreSQL, date + 7 moves seven days, ts + interval '2 hours' adds an interval, and date_b - date_a gives the number of days between them. AGE() returns a human-style interval ("1 year 2 mons 3 days"), NOW() and CURRENT_DATE give the current time and date, and TO_CHAR formats dates as text for display. MySQL uses DATE_ADD, DATEDIFF and DATE_FORMAT; SQL Server uses DATEADD, DATEDIFF and FORMAT.

Why it matters: Due dates, subscription renewals, "orders in the last 30 days", customer ages and time-to-resolve metrics all rely on date maths. The subtle parts (month-end arithmetic, what NOW() means inside a transaction, and dialect differences in DATEDIFF) cause real bugs and come up in interviews.

When to reach for it

  • Due dates, renewals and expiry
  • Time-to-ship, time-to-resolve and similar metrics
  • Relative ranges like "last 30 days"

When to avoid or be careful

  • Sorting or filtering on formatted date text
  • Assuming 'month + 1' always lands on the same day number
  • Assuming SQL Server DATEDIFF measures elapsed time

PostgreSQL vs MySQL vs SQL Server date functions

PostgreSQL
Best for: Interval arithmetic

Strengths: date + 7, ts + interval '1 month', AGE, TO_CHAR.

Watch out: Epoch extraction needed for numeric hours.

MySQL
Best for: Function-style date maths

Strengths: DATE_ADD, DATEDIFF, TIMESTAMPDIFF, DATE_FORMAT.

Watch out: Different names and argument order from PostgreSQL.

SQL Server
Best for: DATEADD / DATEDIFF style

Strengths: Explicit units in every call.

Watch out: DATEDIFF counts boundaries crossed, not elapsed time.

Interview signals & numbers to know

When this topic comes up

  • “Orders in the last 30 days”
  • “Average time to resolve a ticket”
  • “Customer age”
  • Formatting dates for reports
  • Month-end bugs

Benchmarks & rules of thumb

Jan 31 + 1 month -
= Feb 28 (or 29)
3600 -
seconds per hour, for epoch maths
NOW() -
fixed for the whole transaction

Common mistakes & follow-ups

Common interview mistakes

  • Using TO_CHAR in ORDER BY and getting 'Apr' before 'Jan'.
  • Computing hours with EXTRACT(HOUR FROM interval), which drops the days part.
  • Expecting NOW() to differ between rows inserted in the same transaction.

Likely interviewer follow-ups

  • How would you compute the average hours between ticket creation and resolution?
  • What does '2026-01-31' + interval '1 month' return in PostgreSQL?
  • What's the difference between NOW() and clock_timestamp()?
Interview tip: When date maths comes up, mention the month-end clamp and "format last". Both show you've dealt with real reporting bugs.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Date Arithmetic, Intervals & Formatting (AGE, NOW(), CURRENT_DATE, TO_CHAR) with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Date & Time Extraction (EXTRACT, DATE_PART, DATE_TRUNC)
Next topic
Type Casting & Conversion (CAST, ::, TRY_CAST)