← Learn SQL

Dates & Times — Getting Ranges and Boundaries Right

Group by month and keep the year, so June 2023 and June 2024 stay two separate months. Spot partial periods, write date ranges that never count a day twice, anchor recent on the data, subtract dates correctly, and fill the months that have no rows.

intermediate#sql#intermediate#dates#date_trunc#interval#date-ranges#generate_series

This article is part of the Learn SQL hands-on course series.

Prerequisite — this is a hands-on lesson. Reading it is not enough. Run every query yourself in CloudBeaver, against the Northwind Company sample database on PostgreSQL — and solve the koans yourself on DuckDB, the same Northwind Company data.

Not set up yet? It only takes a couple of minutes:

See here how to connect with CloudBeaver, and how to run the koans

Orders per month: EXTRACT throws the year away

Mnemosyne, questioning
Mnemosyne

Leo, the manager wants a chart: orders per month. One bar for every month we've been trading.

Leo, excited
Leo

I can already do that. EXTRACT the month from the order date, group by it — the GROUP BY lesson.

Mnemosyne, pointing-right
Mnemosyne

Go on, then. EXTRACT(MONTH FROM "OrderDate"), and group by it.

SELECT EXTRACT(MONTH FROM "OrderDate")
         AS "Month",
       count(*) AS "Orders"
FROM "Orders"
GROUP BY EXTRACT(MONTH FROM "OrderDate")
ORDER BY "Month";
Leo, smiling
Leo

One row per month — ready for the manager's chart.

Month
Orders
1
805
2
809
3
825
4
786
5
774
6
739
7
828
8
653
9
751
10
821
11
1104
12
1105
Leo, surprised
Leo

June had 739 orders. November and December, the busiest. Looks right.

Mnemosyne, questioning
Mnemosyne

Which June, Leo? We've traded five years, January 2020 to December 2024 — sixty months. Your chart has twelve.

the June bar — five Junes stacked

MonthOrders
June 2020120
June 2021130
June 2022144
June 2023168
June 2024177
The June bar739

177 — June 2024 on its own

Every bar is five months added up. Next to it, June 2024 looks like a crash.

Leo, surprised
Leo

…Twelve? So my June is every June — 2020 to 2024, added into one bar.

Mnemosyne, questioning
Mnemosyne

Exactly. EXTRACT kept the month and threw the year away. The manager will read 739 as one June. June 2024 had 177 — next to 739, it looks like a crash that never happened.

Leo, surprised
Leo

So the crash is in my chart, not in the shop. Every bar needs its year — June 2024, not just June.

date_trunc keeps the year

Mnemosyne, questioning
Mnemosyne

Then use date_trunc. date_trunc('month', …) cuts every date back to the first of its month — and keeps the year. The 5th of June 2024 becomes the 1st of June 2024.

SELECT date_trunc('month', "OrderDate")
         AS "Month",
       count(*) AS "Orders"
FROM "Orders"
GROUP BY date_trunc('month', "OrderDate")
ORDER BY "Month";
Leo, thinking
Leo

So each bar is a real month, not just a month's name.

60 rows — January 2020 to December 2024
Month
Orders
2020-01-01 00:00:00.000
138
2020-02-01 00:00:00.000
128
2020-03-01 00:00:00.000
126
…
…
2024-09-01 00:00:00.000
168
2024-10-01 00:00:00.000
205
2024-11-01 00:00:00.000
277
2024-12-01 00:00:00.000
254
1
2
3
57
58
59
60
Mnemosyne, proud
Mnemosyne

Sixty real months — every June back in its own year.

the same 60 months, as a chart — the five Junes lit, the line through each year's average month

2020
1,638
2021
1,802
2022
1,982
2023
2,180
2024
2,398

About 10% more orders every year.

Leo, excited
Leo

Same orders, sixty groups instead of twelve — and now I can see the company growing.

Weeks, and the edges of the data

Mnemosyne, pointing-right
Mnemosyne

date_trunc also takes quarter, year — and week. Orders per week, and this time ask for the first and last order in each week as well.

SELECT date_trunc('week', "OrderDate")
         AS "Week",
       count(*) AS "Orders",
       min("OrderDate") AS "First order",
       max("OrderDate") AS "Last order"
FROM "Orders"
GROUP BY date_trunc('week', "OrderDate")
ORDER BY "Week";
Leo, questioning
Leo

Why do I need those? The count is the report.

262 week rows — the first two weeks and the last two
Week
Orders
First order
Last order
2019-12-30 00:00:00.000
21
2020-01-01 00:00:00.000
2020-01-05 00:00:00.000
2020-01-06 00:00:00.000
35
2020-01-06 00:00:00.000
2020-01-12 00:00:00.000
…
…
…
…
2024-12-23 00:00:00.000
60
2024-12-23 00:00:00.000
2024-12-29 00:00:00.000
2024-12-30 00:00:00.000
20
2024-12-30 00:00:00.000
2024-12-31 00:00:00.000
Leo, surprised
Leo

The last week crashed: 60 orders, then 20.

Mnemosyne, questioning
Mnemosyne

Before you call it a crash, read its last order. The 31st of December — the data ends there. That week has two days in it.

Leo, surprised
Leo

Wait — and the first row says 2019. A week starts on a Monday, the data starts on a Wednesday — five days.

Mnemosyne, questioning
Mnemosyne

Right, both are partial. A partial period can look like a crash or a record — so ask for the edges, and say so on the report.

BETWEEN counts an edge twice

Mnemosyne, questioning
Mnemosyne

Now a range. Shipping wants every order that shipped in November 2024.

SELECT count(*) AS "Shipments",
       max("ShippedDate") AS "Last shipped"
FROM "Orders"
WHERE "ShippedDate" BETWEEN DATE '2024-11-01'
                        AND DATE '2024-12-01';
Leo, smiling
Leo

BETWEEN the first of November and the first of December — both ends included, so nothing slips out. And the last ship date, to check the edge.

Shipments
Last shipped
277
2024-12-01 00:00:00.000
Mnemosyne, questioning
Mnemosyne

277 shipments. Read the last date.

Leo, surprised
Leo

The 1st of December? Mnemo, that isn't November.

Mnemosyne, questioning
Mnemosyne

It isn't. BETWEEN includes both ends — and the end you wrote was the 1st of December. So every order shipped that day is in November's report.

Mnemosyne, shrugging
Mnemosyne

And December's report, written the same way, starts on the 1st of December.

SELECT count(*) AS "Shipments",
       min("ShippedDate") AS "First shipped"
FROM "Orders"
WHERE "ShippedDate" BETWEEN DATE '2024-12-01'
                        AND DATE '2025-01-01';
Shipments
First shipped
236
2024-12-01 00:00:00.000

1 December, claimed by both reports

RangeCount
November's reportBETWEEN DATE '2024-11-01' AND DATE '2024-12-01'277
December's reportBETWEEN DATE '2024-12-01' AND DATE '2025-01-01'236

1 Dec: 14 shipments — counted in both

277 + 236 = 513 — for the 499 that actually shipped in those two months.

Leo, confused
Leo

Wait — the 1st of December again? Then those shipments are in November's report and in December's — counted twice.

Half-open ranges

Mnemosyne, proud
Mnemosyne

The fix is a habit, not a better end date. On or after the first day — and strictly before the first day of the next month.

SELECT count(*) AS "Shipments",
       max("ShippedDate") AS "Last shipped"
FROM "Orders"
WHERE "ShippedDate" >= DATE '2024-11-01'
  AND "ShippedDate" <  DATE '2024-12-01';
Shipments
Last shipped
263
2024-11-30 00:00:00.000

the same days — cut once

RangeCount
November's report>= DATE '2024-11-01' AND < DATE '2024-12-01'263
December's report>= DATE '2024-12-01' AND < DATE '2025-01-01'236

1 Dec: one cut — the 14 are December's

263 + 236 = 499. Every shipment counted once, in one month.

Leo, excited
Leo

There — 263. Fourteen fewer, and the last one shipped on the 30th. The 1st of December belongs to December alone.

Leo, thinking
Leo

Or I end the range on the 30th. Then the 1st of December can't get in.

SELECT SUM(CASE WHEN "CreatedAt" BETWEEN DATE '2024-11-01'
                                     AND DATE '2024-11-30'
           THEN 1 ELSE 0 END) AS "Ends on the 30th",
       SUM(CASE WHEN "CreatedAt" >= DATE '2024-11-01'
                 AND "CreatedAt" <  DATE '2024-12-01'
           THEN 1 ELSE 0 END) AS "Half-open"
FROM "Orders";
Mnemosyne, questioning
Mnemosyne

Try it — count it both ways on CreatedAt: your range next to the half-open one. It's when each order was keyed in — unlike the ship date, it has a time of day.

where DATE '2024-11-30' actually falls

RangeCount
Ends on the 30thBETWEEN DATE '2024-11-01' AND DATE '2024-11-30'271
Half-open>= DATE '2024-11-01' AND < DATE '2024-12-01'278

30 Nov: 7 orders keyed in on the 30th — outside the first range

A date is midnight at the START of that day. Ending on the 30th ends the range before the 30th happens.

Leo, thinking
Leo

271 against 278? So ending on the 30th means midnight at the start of the 30th — the 7 orders keyed in that day are gone.

Mnemosyne, questioning
Mnemosyne

Exactly — and it's the same trap with =: "CreatedAt" = DATE '2024-11-30' finds none. Nobody keys an order in at midnight.

Your turn, Leo.

Count the orders placed in May 2024.

Half-open: on or after the first, before the first of June. You should get 181.

▶ Continue once you've run it.

SELECT count(*) AS "Orders"
FROM "Orders"
WHERE "OrderDate" >= ___
  AND "OrderDate" <  ___;

“Recent” on data that has stopped

Leo, confused
Leo

Now the recent orders: the last 30 days. CURRENT_DATE minus an INTERVAL of 30 days.

SELECT count(*) AS "Orders"
FROM "Orders"
WHERE "OrderDate" >= CURRENT_DATE
                     - INTERVAL '30 days';
Orders
0
Mnemosyne, shrugging
Mnemosyne

Zero.

Leo, confused
Leo

Zero? Mnemosyne, we have ten thousand orders.

Mnemosyne, shrugging
Mnemosyne

We do — but CURRENT_DATE is today, and this data stops at the end of 2024. The query is right. There just aren't any orders in the 30 days before today.

Mnemosyne, questioning
Mnemosyne

On live data, CURRENT_DATE is exactly right. On a snapshot like ours, anchor on the data: the last order date, worked out in brackets — the subquery from the first lesson of this series.

SELECT count(*) AS "Orders",
       min("OrderDate") AS "From",
       max("OrderDate") AS "To"
FROM "Orders"
WHERE "OrderDate" >=
      (SELECT max("OrderDate") FROM "Orders")
      - INTERVAL '30 days';
Leo, thinking
Leo

So 'recent' means recent to the data. And I'll ask for the first and last order, to see the edges.

Orders
From
To
254
2024-12-01 00:00:00.000
2024-12-31 00:00:00.000
Mnemosyne, proud
Mnemosyne

254 orders, from the 1st to the 31st of December — 30 days back from the last day in the data.

Leo, smiling
Leo

So it starts at midnight on the 1st: a timestamp minus an INTERVAL is still a timestamp. And >= keeps that whole day.

Subtracting dates

Mnemosyne, questioning
Mnemosyne

Dates subtract, too. Which orders took more than a week to ship?

SELECT count(*) AS "Slow orders"
FROM "Orders"
WHERE "ShippedDate" - "OrderDate" > 7;
SQL Error [42883]: ERROR: operator does not exist: interval > integer
  Position: 82
Leo, confused
Leo

Shipped date minus order date, greater than 7. …And it won't run: operator does not exist, interval greater than integer?

Mnemosyne, questioning
Mnemosyne

A timestamp minus a timestamp is an INTERVAL — '4 days', a length of time. It isn't the number 4, so it can't be compared with 7.

Leo, questioning
Leo

So how do I get the number?

Mnemosyne, questioning
Mnemosyne

Cast both sides to DATE first. A date minus a date is a whole number of days — that's why the lesson on missing values cast both sides.

Mnemosyne, proud
Mnemosyne

Cast both sides, and it's days against days. 193 orders took more than a week to ship.

SELECT count(*) AS "Slow orders"
FROM "Orders"
WHERE CAST("ShippedDate" AS DATE)
      - CAST("OrderDate" AS DATE) > 7;
Slow orders
193
Leo, smiling
Leo

So I copied those casts without knowing why. Now I know what they were for.

Mnemosyne, pointing-right
Mnemosyne

Comparing two timestamps needs no arithmetic at all. "RequiredDate" is when the customer needs the order — which ones shipped after that, in December?

SELECT "OrderID",
       "RequiredDate", "ShippedDate"
FROM "Orders"
WHERE "ShippedDate" > "RequiredDate"
  AND "ShippedDate" >= DATE '2024-12-01'
  AND "ShippedDate" <  DATE '2025-01-01'
ORDER BY "ShippedDate", "OrderID";
OrderID
RequiredDate
ShippedDate
9720
2024-12-12 00:00:00.000
2024-12-15 00:00:00.000
9696
2024-12-10 00:00:00.000
2024-12-20 00:00:00.000
9725
2024-12-12 00:00:00.000
2024-12-20 00:00:00.000
Leo, thinking
Leo

Just three. Order 9696 was needed on the 10th and shipped on the 20th.

The months that have no rows

Mnemosyne, questioning
Mnemosyne

One more: Bramble Supermarket's orders per month in 2024, for a chart.

SELECT date_trunc('month', "OrderDate") AS "Month",
       count(*) AS "Orders"
FROM "Orders"
WHERE "CustomerID" = 'BRAM3'
  AND "OrderDate" >= DATE '2024-01-01'
  AND "OrderDate" <  DATE '2025-01-01'
GROUP BY date_trunc('month', "OrderDate")
ORDER BY "Month";
Month
Orders
2024-01-01 00:00:00.000
2
2024-05-01 00:00:00.000
1
2024-10-01 00:00:00.000
1
2024-11-01 00:00:00.000
2
Leo, thinking
Leo

Easy. Four rows — January, May, October and November.

Bramble Supermarket, 2024 — what the query handed back

JanFebMarAprMayJunJulAugSepOctNovDec
2———1————12—
Mnemosyne, questioning
Mnemosyne

And what happened in February?

Leo, thinking
Leo

Nothing — so there's no row. The chart just draws a line from January to May… and eight months nobody can see.

Mnemosyne, questioning
Mnemosyne

So make the months first. generate_series produces twelve timestamps, one per month — and a LEFT JOIN hangs the orders on them. The customer goes in the ON.

SELECT s.month AS "Month",
       count(o."OrderID") AS "Orders"
FROM generate_series(
       TIMESTAMP '2024-01-01',
       TIMESTAMP '2024-12-01',
       INTERVAL '1 month') AS s(month)
LEFT JOIN "Orders" o
  ON date_trunc('month', o."OrderDate") = s.month
 AND o."CustomerID" = 'BRAM3'
GROUP BY s.month
ORDER BY s.month;

the twelve months first — orders hung on them

JanFebMarAprMayJunJulAugSepOctNovDec
200010000120

Twelve rows, whatever the orders did. The eight silences come back as eight zeros.

Leo, thinking
Leo

In the ON — because in a WHERE it would drop the empty months again. The LEFT JOIN trap from the lesson on JOINs.

Month
Orders
2024-01-01 00:00:00.000
2
2024-02-01 00:00:00.000
0
2024-03-01 00:00:00.000
0
2024-04-01 00:00:00.000
0
2024-05-01 00:00:00.000
1
2024-06-01 00:00:00.000
0
2024-07-01 00:00:00.000
0
2024-08-01 00:00:00.000
0
2024-09-01 00:00:00.000
0
2024-10-01 00:00:00.000
1
2024-11-01 00:00:00.000
2
2024-12-01 00:00:00.000
0
Mnemosyne, proud
Mnemosyne

Twelve rows, and the empty months say zero.

Leo, excited
Leo

A zero is something the chart can draw. A missing row was just a silence.

Leo, surprised
Leo

So Bramble's total for the year is count(*) over the spine.

SELECT count(*) AS "count(*)",
       count(o."OrderID") AS "count(OrderID)"
FROM generate_series(
       TIMESTAMP '2024-01-01',
       TIMESTAMP '2024-12-01',
       INTERVAL '1 month') AS s(month)
LEFT JOIN "Orders" o
  ON date_trunc('month', o."OrderDate") = s.month
 AND o."CustomerID" = 'BRAM3';
Mnemosyne, questioning
Mnemosyne

Is it? Run both — count(*) next to count(o."OrderID").

count(*)
count(OrderID)
14
6
Leo, surprised
Leo

Fourteen against six? So count(*) counted the 6 order rows and a row for each empty month. The order ID is NULL there, so only the real 6 get counted.

Case file: since when?

Leo, thinking
Leo

Mnemosyne, can I go back to Speedy Express — the courier with the orders marked Shipped but no ship date? Last lesson found them and ended with no explanation, and it has been bothering me since. What I want to know is since when. If it has always been like that, it's how they work. If it started on a particular day, something changed.

SELECT date_trunc('week', "OrderDate") AS "Week",
       count(*) AS "Orders",
       SUM(CASE WHEN "Status" = 'Shipped'
                 AND "ShippedDate" IS NULL
           THEN 1 ELSE 0 END) AS "No ship date"
FROM "Orders"
WHERE "OrderDate" >= DATE '2024-01-01'
  AND "OrderDate" <  DATE '2025-01-01'
GROUP BY date_trunc('week', "OrderDate")
ORDER BY "Week";
Mnemosyne, smiling
Mnemosyne

Your manager asked why invoicing fell. Asking when the trouble at Speedy Express started was your own idea — and a good one: when it started is how you trace what caused it. How would you count it?

Leo, thinking
Leo

Week by week, over 2024 — with a CASE count, so the weeks with none come back as zeros, not missing rows.

53 rows — the weeks around the start and the stop
Week
Orders
No ship date
2024-02-19 00:00:00.000
50
0
2024-02-26 00:00:00.000
52
0
2024-03-04 00:00:00.000
44
8
2024-03-11 00:00:00.000
53
8
…
…
…
2024-08-19 00:00:00.000
35
7
2024-08-26 00:00:00.000
33
4
2024-09-02 00:00:00.000
35
0
2024-09-09 00:00:00.000
38
0
Leo, thinking
Leo

Zero, zero — then 8 in the week of the 4th of March.

Mnemosyne, pointing-right
Mnemosyne

And 3 to 12 every week after it, up to the week of the 26th of August. Then zero again.

Leo, thinking
Leo

So it didn't creep in or build up like a busy season. It started in one week and lasted 26 weeks in a row — six months, March to August.

Mnemosyne, pointing-right
Mnemosyne

So that's since when: the week of the 4th of March. Outside those 26 weeks, Northwind Company's whole year has just one more order like that, in October — 178 in all. What we don't know yet is how much this cost.

Leo, thinking
Leo

Then the next question is what those 178 orders are worth. Their prices aren't in "Orders" — they're in "Order Details", one row per product ordered. I'll work out how much money that is.

Mnemosyne, pointing-right
Mnemosyne

That's the next lesson, Leo: several tables at once — joining "Orders" to "Order Details". You'll work out that total there.

What to take away, and what is next

Mnemosyne, questioning
Mnemosyne

Before we stop — four habits, Leo. Truncate the date, keep the year, and check the first and last date. Make every range half-open. Anchor 'recent' on the data. And cast before you subtract — then count the orders, not the rows.

Leo, smiling
Leo

Each habit fixes a wrong number I got today — and every one of them looked right. June at 739 when that was five Junes, the 1st of December counted in two months, zero orders in the last 30 days, and 14 orders that were really 6.

Your turn, Leo.

▶ Walk the path to enlightenment.

cd c:/DataPallas/db/datazeus
.\zeus.bat koans learnsql series2 _10
  • date_trunc keeps the year: how many months had an invoice
  • diagnose: five Marches in one count
  • a half-open range: invoices issued in the first quarter of 2024
  • …and seven more, ending with two you write yourself

…/learnsql/series2/_10/DatesAndTimesKoans.groovy

Mnemosyne, excited
Mnemosyne

That was dates, Leo. Keep the year, make ranges half-open, anchor on the data, cast before you subtract, and count the orders — not the rows. Next lesson: several tables at once — and how much money is on those orders?

Leo, excited
Leo

That's what I want to find out: what the 178 orders with no ship date are worth.

That's all, folks!

  1. Subqueries — one query's result inside another
  2. CASE — SQL's if/then for labels & buckets
  3. Dates & Times — ranges and boundaries (this lesson)
  4. Multi-Table JOINs & Grain — rows dropped or multiplied
  5. CTEs (WITH) — a long query, in named steps
  6. VIEWs, CREATE TABLE AS & Temp Tables — query or answer
  7. EXISTS & Correlated Subqueries — and the NOT IN trap
  8. Self-JOINs & Hierarchies — rows in the same table
  9. Window Functions I: OVER, PARTITION BY & ROW_NUMBER
  10. String Functions, LIKE & Regex — clean up messy data
  11. Window Functions II: LAG/LEAD, Running Totals & Frames
  12. UNION, INTERSECT, EXCEPT — stack and reconcile lists
  13. GROUPING SETS, ROLLUP & CUBE — subtotals in one pass
  14. INSERT, UPDATE, DELETE & Transactions — safely
  15. UPSERT & MERGE — insert or update, safely re-run
  16. Median and Percentiles — WITHIN GROUP, not AVG
  17. Subqueries + CTEs + Window Functions — a real case

Found this to be a little gem? Help others find it too — someone out there is stuck trying to learn SQL right now. The button opens Reddit with the link and title already filled in, so you just pick a community and post.

Share on Reddit