Dates and date spines
Almost every data engineering query has a date in it: orders per day, revenue per month, days until the first order. This lesson covers the date functions you will use every week, and the date spine: the trick for reporting days on which nothing happened.
Foundations · SQL for data engineers · Silver · Structure, sets and dates, lesson 3 of 3
On this page
Read first: GROUP BY and HAVING (skip if you know it)
In plain words first
A date like 2026-03-04 can be read at different sizes: the day itself, its week, its month, its weekday. Most date questions are "group by one of these sizes" or "how far apart are two dates". Spark has a function for each.
Weeks, months and weekdays
Input: orders
| order_id | customer_id | city | amount | order_date |
|---|---|---|---|---|
| 201 | 1 | Pune | 420 | 2026-03-01 |
| 202 | 2 | Delhi | 650 | 2026-03-01 |
| 203 | 1 | Pune | 300 | 2026-03-02 |
| 204 | 3 | Pune | 540 | 2026-03-02 |
| 205 | 2 | Delhi | 280 | 2026-03-04 |
| 206 | 4 | Pune | 540 | 2026-03-04 |
| 207 | 5 | Mumbai | 390 | 2026-03-05 |
| 208 | 1 | Pune | 180 | 2026-03-05 |
| 209 | 2 | Delhi | 650 | 2026-03-06 |
| 210 | 5 | Mumbai | 210 | 2026-03-06 |
SELECT order_id, order_date, date_format(order_date, 'EEE') AS weekday, date_trunc('WEEK', order_date) AS week_start, trunc(order_date, 'MM') AS month_start, last_day(order_date) AS month_end FROM orders WHERE order_id IN (201, 205, 210)
| Function | Gives | Example for 2026-03-04 |
|---|---|---|
date_trunc('WEEK', d) | Start of the week (Monday), as a timestamp | 2026-03-02 00:00:00 |
trunc(d, 'MM') | First day of the month, as a date | 2026-03-01 |
last_day(d) | Last day of the month | 2026-03-31 |
date_format(d, 'EEE') | Short weekday name | Wed |
year(d), month(d), dayofmonth(d) | One part, as a number | 2026, 3, 4 |
dayofweek(d) | Weekday number, Sunday = 1 | 4 |
To report per week or per month, group by the truncated date. trunc(order_date, 'MM') is better than month(order_date) for this, because March 2026 and March 2027 stay apart.
Date arithmetic
Input: orders
| order_id | customer_id | city | amount | order_date |
|---|---|---|---|---|
| 201 | 1 | Pune | 420 | 2026-03-01 |
| 202 | 2 | Delhi | 650 | 2026-03-01 |
| 203 | 1 | Pune | 300 | 2026-03-02 |
| 204 | 3 | Pune | 540 | 2026-03-02 |
| 205 | 2 | Delhi | 280 | 2026-03-04 |
| 206 | 4 | Pune | 540 | 2026-03-04 |
| 207 | 5 | Mumbai | 390 | 2026-03-05 |
| 208 | 1 | Pune | 180 | 2026-03-05 |
| 209 | 2 | Delhi | 650 | 2026-03-06 |
| 210 | 5 | Mumbai | 210 | 2026-03-06 |
Input: customers
| customer_id | name | city | signup_date |
|---|---|---|---|
| 1 | Asha | Pune | 2026-01-05 |
| 2 | Ravi | Delhi | 2026-01-20 |
| 3 | Meera | Pune | 2026-02-02 |
| 4 | Kabir | Pune | 2026-02-14 |
| 5 | Zoya | Mumbai | 2026-03-01 |
SELECT c.name, c.signup_date, min(o.order_date) AS first_order, datediff(min(o.order_date), c.signup_date) AS days_to_first_order FROM customers c JOIN orders o ON o.customer_id = c.customer_id GROUP BY c.name, c.signup_date ORDER BY days_to_first_order
| Function | Returns |
|---|---|
datediff(end, start) | Whole days from start to end. The later date goes first. |
date_add(d, 7), date_sub(d, 7) | The date 7 days later or earlier |
add_months(d, 1) | One month later; 31 January becomes 28 February |
months_between(end, start) | Months between two dates, with a fraction |
Text into dates
Dates often arrive as text. to_date(text, pattern) parses them; the pattern says where each part is. yyyy is the year, MM the month (capital M: small mm means minutes), dd the day:
SELECT to_date('05/03/2026', 'dd/MM/yyyy') AS parsed, date_format(DATE'2026-03-05', 'dd MMM yyyy') AS pretty
Output
parsed | pretty 2026-03-05 | 05 Mar 2026
In Spark 4, where ANSI mode is on by default, text that does not match the pattern stops the query with an error; with ANSI mode off it quietly becomes NULLNULL: A missing or unknown value. It is not 0 or an empty string, and any comparison with it is unknown instead of true or false. Learn more →. If you turn ANSI off, count the NULLs after parsing so bad rows do not disappear silently.
Date ranges: start inclusive, end exclusive
For "orders from 2 to 4 March", write a half-open range: from the first day, up to but not including the day after the last:
Input: orders
| order_id | customer_id | city | amount | order_date |
|---|---|---|---|---|
| 201 | 1 | Pune | 420 | 2026-03-01 |
| 202 | 2 | Delhi | 650 | 2026-03-01 |
| 203 | 1 | Pune | 300 | 2026-03-02 |
| 204 | 3 | Pune | 540 | 2026-03-02 |
| 205 | 2 | Delhi | 280 | 2026-03-04 |
| 206 | 4 | Pune | 540 | 2026-03-04 |
| 207 | 5 | Mumbai | 390 | 2026-03-05 |
| 208 | 1 | Pune | 180 | 2026-03-05 |
| 209 | 2 | Delhi | 650 | 2026-03-06 |
| 210 | 5 | Mumbai | 210 | 2026-03-06 |
SELECT order_id, order_date, amount FROM orders WHERE order_date >= '2026-03-02' AND order_date < '2026-03-05' ORDER BY order_date
This works the same whether the column is a date or a timestamp. BETWEEN '2026-03-02' AND '2026-03-04' would lose every order placed after midnight on the 4th once the column holds times (the Bronze lesson on WHERE shows why).
Date spines: reporting days with no data
Group orders by day and 3 March is simply missing: no orders, so no row. A chart would join the 2nd straight to the 4th, and a 3-day average would be wrong. The fix is a date spine (or calendar table): a list of every day, which you LEFT JOIN your data onto.
- 1Find the first and last day you need.
- 2Generate every day between them:
sequence(first, last)makes an array of dates andexplodeturns it into one row per day. - 3LEFT JOIN the daily totals onto the spine, and turn the missing totals into 0 with
coalesce.
SELECT explode(sequence(DATE'2026-03-01', DATE'2026-03-06')) AS day
Input: orders
| order_id | customer_id | city | amount | order_date |
|---|---|---|---|---|
| 201 | 1 | Pune | 420 | 2026-03-01 |
| 202 | 2 | Delhi | 650 | 2026-03-01 |
| 203 | 1 | Pune | 300 | 2026-03-02 |
| 204 | 3 | Pune | 540 | 2026-03-02 |
| 205 | 2 | Delhi | 280 | 2026-03-04 |
| 206 | 4 | Pune | 540 | 2026-03-04 |
| 207 | 5 | Mumbai | 390 | 2026-03-05 |
| 208 | 1 | Pune | 180 | 2026-03-05 |
| 209 | 2 | Delhi | 650 | 2026-03-06 |
| 210 | 5 | Mumbai | 210 | 2026-03-06 |
WITH bounds AS ( SELECT min(to_date(order_date)) AS first_day, max(to_date(order_date)) AS last_day FROM orders ), calendar AS ( SELECT explode(sequence(first_day, last_day)) AS day FROM bounds ), daily AS ( SELECT to_date(order_date) AS day, count(*) AS orders, sum(amount) AS revenue FROM orders GROUP BY to_date(order_date) ) SELECT c.day, coalesce(d.orders, 0) AS orders, coalesce(d.revenue, 0) AS revenue FROM calendar c LEFT JOIN daily d ON d.day = c.day ORDER BY c.day
3 March is back, with 0 orders. Now LAG, moving averages and charts all see real calendar days. For many groups (every city on every day), cross join the calendar with the list of cities first, then LEFT JOIN the data.
sequence + explode is the quick way to make one inside a query.Common mistakes
- Grouping by month(d) across years — March of every year lands in one group. Group by trunc(d, 'MM') or date_trunc.
- datediff with the dates swapped — datediff(start, end) is negative. The later date goes first.
- BETWEEN on timestamps — The end date means midnight, so the last day is almost empty. Use >= start AND < day after end.
- Reporting only days that have data — Missing days vanish from charts and moving averages. LEFT JOIN onto a date spine.
- Writing mm for the month — mm is minutes. The month is MM.
Key takeaways
- Group by trunc(d, 'MM') or date_trunc('WEEK', d), not by month(d) alone.
- datediff(end, start): the later date first.
- Date ranges: >= first day AND < the day after the last.
- to_date(text, pattern): MM is month, mm is minutes; check for NULLs after parsing.
- A date spine (sequence + explode) LEFT JOINed to your data keeps days with no rows.
Interview prep
THE QUESTION
"Show daily revenue for March, including days with no orders as zero."
SELECT explode(sequence(DATE'2026-03-01', DATE'2026-03-31')) AS day as a CTE, daily totals grouped by to_date(order_ts) as another, then calendar LEFT JOIN daily with coalesce(revenue, 0). The spine must be on the left, or the empty days disappear again. If it is per city, cross join the calendar with the cities first so every city gets every day.Avoid: Grouping the orders by day and returning that. Days with no orders have no row, so the answer silently skips them, which is exactly what the question asked you not to do.
Follow-ups · answer out loud, then open
Follow-up"How do you group by week, and which day does the week start on?"
date_trunc('WEEK', d), which returns the Monday of the week as a timestamp (ISO weeks). For weeks starting on Sunday, shift the date by a day before truncating and back after, or keep a calendar table with the business's own week definition.Scenario"Events arrive as UTC timestamps, and the business reports by Indian day."
to_date(from_utc_timestamp(ts, 'Asia/Kolkata')). Taking the date of the UTC value puts everything between midnight and 05:30 IST on the wrong day. Fix the session time zone (spark.sql.session.timeZone) so results do not depend on the cluster.Trap"What is add_months('2026-01-31', 1)?"
Check yourself
4 questionsWhat does datediff('2026-03-05', '2026-03-01') return?
Show the answer
4. Later date first gives a positive number of days.
Which keeps March 2026 and March 2027 apart?
Show the answer
trunc(d, 'MM'). trunc keeps the year; month() is just 3 for both.
Which condition keeps every order on 2, 3 and 4 March, even with times?
Show the answer
d >= '2026-03-02' AND d < '2026-03-05'. A half-open range includes all of the last day.
Why does the date spine go on the left of the LEFT JOIN?
Show the answer
So days with no data are kept. A LEFT JOIN keeps every row of the left table.
Practise this
Problems that use this, graded on hidden tests
Keep going
Up next · new module: Interview patterns · 8 min readGaps and islands
Find streaks of consecutive days and runs of the same value with two reusable window tricks.
Related lessons
LAG and LEADSQL for data engineers · 7 min read
Running totals and window framesSQL for data engineers · 7 min read
SELECT, WHERE and ORDER BY
Previous: UNION, INTERSECT and EXCEPT
Primary sources: Date and timestamp functions · Datetime patterns · sequence