Date Functions
Lesson opener
In one line: Filter and group by time for operational reporting.
Why it matters: A full date column doesn't group cleanly by "signup year" until you peel off the parts you care about.
Before this lesson: CASE
Before you start
| Resource | Link |
|---|---|
| Previous | CASE |
| Next | Set operators |
What you will learn
Filter and group by time for operational reporting.
Parse and extract (MySQL)
[Pull year and month from signup date]
WHY: A full date column doesn't group cleanly by "signup year" until you peel off the parts you care about.
WHEN: You're cohorting customers by signup year and month for a retention chart.
SELECT customer_id, signup_date,
YEAR(signup_date) AS yr,
MONTH(signup_date) AS mo
FROM customers
LIMIT 10;Breaking it down:
YEAR(signup_date)→ four-digit year from the dateMONTH(signup_date)→ month number 1–12LIMIT 10→ sample rows while exploring
Use this when: You need date parts for grouping or labeling, not the full timestamp.
DATE_FORMAT and STR_TO_DATE
Plain English: DATE_FORMAT turns a real date into a label string (for reports). STR_TO_DATE turns a messy text string into a real date (for filtering and sorting).
When to use it: Exports store dates as '15/01/2024' or 'Jan 15, 2024' — you must parse before YEAR() or WHERE signup_date > '2024-01-01' works correctly.
Format a date for a report:
SELECT customer_id, signup_date,
DATE_FORMAT(signup_date, '%Y-%m') AS signup_month,
DATE_FORMAT(signup_date, '%d %b %Y') AS friendly_label
FROM customers
LIMIT 10;Breaking it down:
DATE_FORMAT(signup_date, '%Y-%m')→2024-01style month bucket'%d %b %Y'→15 Jan 2024style label for dashboards
Parse text into a date:
SELECT STR_TO_DATE('15/01/2024', '%d/%m/%Y') AS parsed_date;
SELECT STR_TO_DATE('2024-01-15', '%Y-%m-%d') AS iso_date;Breaking it down:
- First argument → the text column or literal
- Second argument → format mask telling MySQL where day, month, and year sit
- Wrong mask →
NULL(silent failure — always spot-check withLIMIT 10)
Filter after parsing messy text:
SELECT customer_id, raw_signup
FROM staging_customers
WHERE STR_TO_DATE(raw_signup, '%d/%m/%Y') >= '2024-01-01';Use this when: the column is text today but you need real date logic tomorrow.
[Revenue since June 2022]
WHY: Filtering individual order dates one by one is painful when your table already stores month as 'YYYY-MM' text.
WHEN: Finance wants monthly revenue from June 2022 onward for a board slide.
SELECT month, SUM(revenue) AS revenue
FROM sales
WHERE month >= '2022-06'
GROUP BY month
ORDER BY month;Breaking it down:
WHERE month >= '2022-06'→ works for YYYY-MM strings — lexicographic order matches chronologicalGROUP BY month→ one row per monthSUM(revenue)→ monthly total
Use this when: Your time grain is pre-bucketed month strings, not raw dates.
DATEDIFF / DATE_ADD
[Days since signup]
WHY: "How long have they been with us?" isn't stored — you compute it from signup date and today.
WHEN: Support prioritizes tickets from customers who signed up in the last 30 days vs long-tenure accounts.
SELECT customer_id, signup_date,
DATEDIFF(CURDATE(), signup_date) AS days_since_signup
FROM customers
LIMIT 10;Breaking it down:
CURDATE()→ today's date on the serverDATEDIFF(end, start)→ number of days between start and end — here, signup to todayAS days_since_signup→ tenure in days per customer
Use this when: You need tenure or age-in-days for segmentation or SLA rules.
Essential commands
| Command / action | What it does |
|---|---|
YEAR(date) / MONTH(date) | Extract date parts. |
DATE_FORMAT(date, '%Y-%m') | Format a date as text for labels. |
STR_TO_DATE(text, format) | Parse text into a real date. |
DATEDIFF(end, start) | Days between two dates. |
DATE_ADD(date, INTERVAL n DAY) | Shift a date forward. |
WHERE month_col >= '2022-06' | Filter YYYY-MM text chronologically. |
Practice
Before each query, name the three SQL beats — Source → Pattern → Result (SQL translation of Input → Logic → Output — see sql2).
Do this now:
- Tenure in days with
DATEDIFF(worked model below). - Monthly revenue trend filtered from June 2022 onward.
- One
YEAR/MONTHorDATE_FORMATextract for cohort labels. - Save
06_dates.sql.
Example framing for task 1:
-- Source: customers (customer_id, signup_date)
-- Pattern: DATEDIFF + CURDATE (tenure calc)
-- Result: one row per customer with days since signup (sample of 10)
SELECT customer_id, signup_date,
DATEDIFF(CURDATE(), signup_date) AS days_since_signup
FROM customers
LIMIT 10;Framing prompts for the rest (fill these blanks in your .sql comments before writing each query):
- Source: ___
Pattern: ___
Result: ___
- Source: ___
Pattern: ___
Result: ___
Checklist
- [ ] Date filter works
- [ ] Grouped by month
- [ ] One DATEDIFF example
- [ ] DATE_FORMAT and STR_TO_DATE used on sample text dates