Skip to content
Silver 6 min read · Dates 3 practice problems ↓

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

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

Spark SQL · One date, read several ways

Input: orders

order_idcustomer_idcityamountorder_date
2011Pune4202026-03-01
2022Delhi6502026-03-01
2031Pune3002026-03-02
2043Pune5402026-03-02
2052Delhi2802026-03-04
2064Pune5402026-03-04
2075Mumbai3902026-03-05
2081Pune1802026-03-05
2092Delhi6502026-03-06
2105Mumbai2102026-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)
FunctionGivesExample for 2026-03-04
date_trunc('WEEK', d)Start of the week (Monday), as a timestamp2026-03-02 00:00:00
trunc(d, 'MM')First day of the month, as a date2026-03-01
last_day(d)Last day of the month2026-03-31
date_format(d, 'EEE')Short weekday nameWed
year(d), month(d), dayofmonth(d)One part, as a number2026, 3, 4
dayofweek(d)Weekday number, Sunday = 14

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

Spark SQL · Days from signing up to the first order

Input: orders

order_idcustomer_idcityamountorder_date
2011Pune4202026-03-01
2022Delhi6502026-03-01
2031Pune3002026-03-02
2043Pune5402026-03-02
2052Delhi2802026-03-04
2064Pune5402026-03-04
2075Mumbai3902026-03-05
2081Pune1802026-03-05
2092Delhi6502026-03-06
2105Mumbai2102026-03-06

Input: customers

customer_idnamecitysignup_date
1AshaPune2026-01-05
2RaviDelhi2026-01-20
3MeeraPune2026-02-02
4KabirPune2026-02-14
5ZoyaMumbai2026-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
FunctionReturns
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:

Spark SQL · Parsing an Indian-style date
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:

Spark SQL · Orders on 2, 3 and 4 March

Input: orders

order_idcustomer_idcityamountorder_date
2011Pune4202026-03-01
2022Delhi6502026-03-01
2031Pune3002026-03-02
2043Pune5402026-03-02
2052Delhi2802026-03-04
2064Pune5402026-03-04
2075Mumbai3902026-03-05
2081Pune1802026-03-05
2092Delhi6502026-03-06
2105Mumbai2102026-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.

  1. 1
    Find the first and last day you need.
  2. 2
    Generate every day between them: sequence(first, last) makes an array of dates and explode turns it into one row per day.
  3. 3
    LEFT JOIN the daily totals onto the spine, and turn the missing totals into 0 with coalesce.
Spark SQL · Step 2 on its own: one row per day
SELECT explode(sequence(DATE'2026-03-01', DATE'2026-03-06')) AS day
Spark SQL · The whole spine: every day, with zeros

Input: orders

order_idcustomer_idcityamountorder_date
2011Pune4202026-03-01
2022Delhi6502026-03-01
2031Pune3002026-03-02
2043Pune5402026-03-02
2052Delhi2802026-03-04
2064Pune5402026-03-04
2075Mumbai3902026-03-05
2081Pune1802026-03-05
2092Delhi6502026-03-06
2105Mumbai2102026-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.

Tip: Warehouses usually keep a permanent calendar table (one row per day for decades, with weekday, month, holiday flags). 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."

Build a date spine and LEFT JOIN onto it: 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?"
Group by 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."
Convert before you take the date: 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)?"
2026-02-28: when the target month is shorter, Spark returns its last day. Adding one month and then subtracting one does not give back 31 January, so be careful with month arithmetic in billing logic.

Check yourself

4 questions

What 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 read
Gaps and islands
Find streaks of consecutive days and runs of the same value with two reusable window tricks.

Related lessons

Previous: UNION, INTERSECT and EXCEPT

Primary sources: Date and timestamp functions · Datetime patterns · sequence