NO. 07 · 7 exercises

7. Numbers & Dates

Rounding, math, and making time behave.

The lesson

Numbers & Dates

Two kinds of data make people reach for calculators: money and time. So far you've selected, filtered and grouped them like any other value. This chapter gives you the functions that make them behave — rounding, absolute values, and the whole machinery for slicing dates into years, months and day-counts.

Rounding: ROUND

Invoices average out to a long, unfriendly decimal. The accountant wants one tidy number:

SELECT ROUND(AVG(total), 2) AS avg_invoice
FROM invoices;

ROUND(number, digits) rounds to the digits you ask for — 2 gives cents, 0 gives whole numbers. Without the second argument, ROUND rounds to a whole number by default.

Why bother? The course's grader is lenient about decimals, but money reports shouldn't be. ROUND(x, 2) is what real accounting exports expect, and it's a habit worth building from day one. (Your answers here will still match if you skip it — rounding only shows in reports.)

Absolute value: ABS

ABS(x) strips the minus sign. "How far off" questions are its natural habitat. A radio show only plays tracks near the five-minute mark; how far is each track from 300 seconds?

SELECT title, ABS(duration_sec - 300) AS off_by
FROM tracks;

midnight train is 301 seconds — ABS(1), which is also just 1. Copper Wire is 176 seconds — ABS(-124) becomes 124. With ABS, "too long" and "too short" both turn into plain positive distances.

What a date is in SQLite

Here's the secret about dates in this database: they're text. invoice_date is a TEXT column containing '2022-01-15' — and that's fine, because SQLite orders that format correctly: '2022-01-15' < '2023-06-30' sorts chronologically, and WHERE invoice_date >= '2023-01-01' works as-is.

The date functions accept that text, validate it, and let you pull it apart. The master key is strftime, which extracts any piece of a date:

SELECT strftime('%Y', invoice_date) AS year, COUNT(*) AS invoices
FROM invoices
GROUP BY year;

strftime('%Y', invoice_date) hands back the four-digit year as text, and the query groups by it — GROUP BY from chapter 5 works on any expression, not just plain columns. The store cut 10 invoices in 2022, 9 in 2023 and 3 in 2024.

strftime takes a format string describing what you want:

CodeMeansExample for 2023-06-21
%YYear, four digits2023
%yYear, two digits23
%mMonth, zero-padded06
%dDay of month21
%jDay of year172
%HHour (00–23)00
%MMinute00
%SSecond00
%wDay of week (0 = Sunday)3

Combine codes into a label: strftime('%Y-%m', invoice_date) gives 2023-06 — a month label that also sorts chronologically as text. That's the trick behind monthly reports.

Days between dates: julianday

Months and years are easy to pull apart, but "how many days between two dates?" needs arithmetic. SQLite converts any date to a day count with julianday() — the number of days since a fixed moment in history:

SELECT julianday(MAX(invoice_date)) - julianday(MIN(invoice_date)) AS days_between
FROM invoices;

The store's history — from its first invoice on 2022-01-15 to its latest on 2024-03-05 — spans 780 days. Subtract day counts and the result is a plain number of days (with a fraction, usually).

You can also compare against today with date('now'), which returns the current date:

SELECT first_name, ROUND(julianday(date('now')) - julianday(joined_date), 0) AS days_with_us
FROM customers;

julianday(date('now')) is today's day count, julianday(joined_date) is the day each customer signed up — the difference is their tenure, rounded to whole days. Note ROUND(..., 0) — nothing here should display as 1910.3692....

date() also takes modifiers for calendar arithmetic: date('now', '-30 days') is a month ago, date('2024-01-01', '+2 years') is 2026. Useful for "invoices from the last 90 days" filters.

Grouping time: reports by month

All the pieces snap together. Yearly revenue, from chapter 5's aggregates plus this chapter's date functions:

SELECT strftime('%Y', invoice_date) AS year, ROUND(SUM(total), 2) AS revenue
FROM invoices
GROUP BY year
ORDER BY revenue DESC;

2022 leads with 27.45, 2023 follows with 20.61, 2024 trails at 5.55. And the full monthly report — the shape you'll practice in the boss exercise — is the same query with a finer grain:

SELECT strftime('%Y-%m', invoice_date) AS month,
       COUNT(*) AS invoices,
       ROUND(SUM(total), 2) AS revenue
FROM invoices
GROUP BY month
ORDER BY month;

Twenty months produced invoices, each with its count and its revenue, ordered chronologically. Money, grouped by time, rounded — that's a report an accountant will actually sign.

What you just learned

  • ROUND(x, 2) rounds to a number of decimals — use it for money.
  • ABS(x) turns differences positive — "how far off" questions.
  • Dates are text in SQLite, and compare correctly in YYYY-MM-DD form.
  • strftime('%Y', date) extracts pieces of a date; %Y-%m makes sortable month labels.
  • julianday(date) counts days; subtracting day counts measures spans; date('now') is today, and date() takes modifiers like '-30 days'.
  • strftime + GROUP BY turns a pile of dates into year and month reports.

Dialect note. SQLite has no dedicated date type — dates are text, and the date functions do the work. PostgreSQL and MySQL have real DATE/TIMESTAMP types, where you'd use EXTRACT(YEAR FROM date) or DATE_FORMAT(date, '%Y') instead of strftime, and DATEDIFF() instead of subtracting julianday() values. The ideas carry over perfectly; only the names change. On SQLite, strftime and julianday are the tools.

Time to put dates to work. The exercises below assume you've read this far.