Ravindra BagaleCourses & study guides Track your progress

9. Date and Time Queries for Analysts

9.2 How to Extract Year, Month and Day in SQLite with strftime()

Why. Managers ask for totals by month or by year. You need the month as its own value to group by it.

What. strftime(format, date) returns a part of a date as text. '%Y' gives the year, '%m' gives the month as 01 to 12, '%d' gives the day, and '%Y-%m' gives year and month together, like 2026-09.

How. Split a few dates into parts, then count transactions per month with GROUP BY.

Steps

  1. Run the first example and read the year, month and day columns.
  2. Run the second example to get one row per month.
  3. Check that the month column sorts correctly because it is in the YYYY-MM format.
  4. Use the month column in your monthly report.

Examples

Example 1 · dataset: northstar_bank

SELECT posted_at,
       strftime('%Y', posted_at) AS year,
       strftime('%m', posted_at) AS month,
       strftime('%d', posted_at) AS day
FROM transactions
WHERE txn_id IN (2, 9, 18);

Output

posted_atyearmonthday
2026-08-19 14:40:0020260819
2026-09-14 13:10:0020260914
2026-10-20 16:45:0020261020

Meaning. Each date is split into year, month and day. The parts are text, so the month shows as 08, not 8.

Example 2 · dataset: northstar_bank

SELECT strftime('%Y-%m', posted_at) AS month,
       COUNT(*)                     AS transactions
FROM transactions
GROUP BY month
ORDER BY month;

Output

monthtransactions
2026-087
2026-099
2026-109

Meaning. There is one row per month. August has 7 transactions, September has 9 and October has 9.

Ravindra Bagale's Tip

Use '%Y-%m' rather than '%m' alone for monthly reports. With '%m' alone, September of two different years would join into one group.