Date Arithmetic, Intervals & Formatting (AGE, NOW(), CURRENT_DATE, TO_CHAR)
Add intervals, compute ages, and format dates for humans and exports.
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
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)).
SELECT shipped_on - ordered_on AS days_to_ship, ROUND( EXTRACT( EPOCH FROM delivered_at - shipped_at ) / 3600, 1 ) AS hours_in_transitFROM shipments;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Expected output3 sample rows
| days_to_ship | hours_in_transit |
|---|---|
| 1 | 18.5 |
| 2 | 31 |
| 0 | 6.8 |
Note: Illustrative shipment intervals; exact timestamp precision and date semantics depend on the dialect.
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.
| day | amount |
|---|---|
| 2026-11-15 | 100 |
| 2026-11-17 | 200 |
| 2026-11-21 | 50 |
| 2026-11-22 | 75 |
SELECT TO_CHAR(DAY, 'FMDD Mon YYYY') AS label, revenueFROM daily_revenueORDER BY DAY;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Expected output3 sample rows
| label | revenue |
|---|---|
| 1 Nov 2026 | 18200 |
| 2 Nov 2026 | 19550 |
| 3 Nov 2026 | 9100 |
Note: Illustrative dates and revenue; TO_CHAR syntax and output spelling are database-specific.
Sort by the date, show the text.
Key takeaway: Know what NOW() means; format at the very end; check dialect behaviour.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Decide: move or measure?
Are you computing a new date (due date, renewal) or a gap (days to ship, hours to resolve)?
due = created + 14 · gap = shipped − ordered
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
Strengths: date + 7, ts + interval '1 month', AGE, TO_CHAR.
Watch out: Epoch extraction needed for numeric hours.
Strengths: DATE_ADD, DATEDIFF, TIMESTAMPDIFF, DATE_FORMAT.
Watch out: Different names and argument order from PostgreSQL.
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()?
Knowledge check
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.