Mastering MySQL for Data AnalystsLesson 35 of 42
Lesson 35 of 42

Temporal Analytics: NOW, CURDATE, DATE_FORMAT, STR_TO_DATE, DATEDIFF & DATE_ADD in MySQL

Overview & Learning Objectives

Temporal analysis drives essential business metrics: Month-over-Month (MoM) revenue pacing, customer churn periods, and delivery SLA breaches. Working with dates in SQL requires mastering temporal parsing, formatting, and arithmetic. In MySQL, analysts rely on `DATE_FORMAT()` to extract month/year periods, `STR_TO_DATE()` to ingest dirty date strings, `DATEDIFF()` and `TIMESTAMPDIFF()` to measure durations, and `DATE_ADD()` for forward projections.

  • Extract calendar intervals and format executive date strings using `DATE_FORMAT()`.
  • Parse custom date strings (e.g. "13/11/2026") into valid MySQL dates using `STR_TO_DATE()`.
  • Calculate delivery durations and customer age using `DATEDIFF()` and `TIMESTAMPDIFF()`.
  • Execute date arithmetic using `DATE_ADD(col, INTERVAL n DAY)`.

Industry Standard

Standard: Analytics pipelines at Uber and DoorDash compute exact delivery SLA durations in integer minutes using `TIMESTAMPDIFF(MINUTE, pickup_time, drop_time)` rather than naive date subtraction.

Real-World Example: ScoopCraft Dark-Store Delivery SLA Performance

ScoopCraft tracks delivery timestamps from order placement to door delivery to flag SLA breaches (> 25 minutes).

order_idorder_timedelivered_timeDuration in Min (TIMESTAMPDIFF)SLA Status
ORD-8012026-11-13 14:02:102026-11-13 14:18:4516 minutesWithin SLA (< 25 min)
ORD-8022026-11-13 14:10:002026-11-13 14:38:2028 minutesBreached SLA (+3 min)
ORD-8032026-11-13 14:15:302026-11-13 14:34:1018 minutesWithin SLA

Functions & Syntax Covered in this Chapter

Here is the definition, execution syntax, parameter breakdown, and real-world business example for each function/syntax covered in this chapter:

Feature 1

NOW(), CURDATE() & CURTIME()

Definition: Returns the current datetime, current date, or current time according to the server's active timezone.

Syntax / Code Pattern:
SELECT CURDATE() AS today, NOW() AS current_datetime;
Real-World Example (Order Placement Timestamp):
Problem / Scenario: Stamp transactions with the exact current timestamp.
SQL Query / Expression: NOW()
Result: '2026-11-13 16:30:00'
Why it works: Generates ISO 8601 YYYY-MM-DD HH:MM:SS datetime stamp.
Feature 2

DATE_FORMAT(date, format)

Definition: Formats a date or datetime value according to specifier tokens (%Y=4-digit year, %m=month, %d=day, %H=24-hr, %i=min).

Syntax / Code Pattern:
SELECT DATE_FORMAT(order_date, "%Y-%m") AS sales_month, DATE_FORMAT(order_date, "%W, %M %e, %Y") FROM orders;
Parameters Breakdown:
  • format: Format string using MySQL date specifiers (%Y, %m, %d, %H, %i, %s, %W, %M).
Real-World Example (Monthly Cohort Formatting):
Problem / Scenario: Group orders by Year-Month string for monthly financial aggregation.
SQL Query / Expression: DATE_FORMAT(order_date, '%Y-%m')
Result: '2026-11'
Why it works: Converts full datetime into a standardized month-level grouping key.
Feature 3

DATEDIFF(expr1, expr2) & TIMESTAMPDIFF(unit, expr1, expr2)

Definition: DATEDIFF returns days between two dates (expr1 - expr2). TIMESTAMPDIFF computes exact intervals (MINUTE, HOUR, DAY, MONTH, YEAR) between expr1 and expr2 (expr2 - expr1).

Syntax / Code Pattern:
SELECT DATEDIFF(CURDATE(), signup_date) AS days_active, TIMESTAMPDIFF(MINUTE, order_time, delivery_time) AS delivery_min FROM orders;
Parameters Breakdown:
  • unit: In TIMESTAMPDIFF: SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, YEAR.
  • expr1, expr2: Datetime expressions.
Real-World Example (Delivery SLA Duration in Minutes):
Problem / Scenario: Measure order dispatch-to-doorstep delivery time in integer minutes.
SQL Query / Expression: TIMESTAMPDIFF(MINUTE, dispatch_time, delivered_time)
Result: 18 minutes
Why it works: Calculates elapsed integer minutes between two timestamps.
Feature 4

DATE_ADD() & DATE_SUB()

Definition: Adds or subtracts specified time intervals (INTERVAL n DAY/MONTH/HOUR) to/from a date or datetime.

Syntax / Code Pattern:
SELECT DATE_ADD(CURDATE(), INTERVAL 30 DAY) AS expiry_date, DATE_SUB(NOW(), INTERVAL 7 DAY) AS week_ago;
Parameters Breakdown:
  • INTERVAL n unit: Specifies interval magnitude and unit (e.g. INTERVAL 1 MONTH).
Real-World Example (Subscription Expiry Calculation):
Problem / Scenario: Calculate when a 3-month VIP membership expires from purchase date.
SQL Query / Expression: DATE_ADD(purchase_date, INTERVAL 3 MONTH)
Result: 2026-11-13 + 3 months -> 2027-02-13
Why it works: Adds calendar months taking into account variable month lengths.

Common Mistakes & Limitations

  • Writing `DATEDIFF(order_time, delivered_time)` and getting negative numbers because DATEDIFF evaluates (t1 - t2).
  • Using naive date subtraction (`date1 - date2`) in MySQL, which performs numeric integer subtraction on formatted numbers rather than true calendar math.

Keyboard Shortcuts (MySQL Workbench)

ActionWindowsMac
Execute QueryCtrl + EnterCmd + Enter

Pro Tips & Modern Best Practices

  • To group by month, always use `DATE_FORMAT(date, "%Y-%m")` or `LAST_DAY(date)` to ensure proper sorting across multi-year trends.
  • Use `NOW()` for full timestamps (including time) and `CURDATE()` when you only need midnight dates without time components.