Section 2 · Lesson 3
CASE expressions and working with dates
Bucket values into business categories with CASE, count conditionally, and group by month or weekday with strftime.
Raw data rarely comes in the categories a business talks about. Budgets are numbers, but the
media plan talks about “high-spend” campaigns. Dates are days, but the board wants monthly
numbers. This lesson gives you two tools for reshaping data on the fly: CASE and SQLite’s date
functions.
CASE: if/then logic inside a query
SELECT id, amount,
CASE
WHEN amount >= 200 THEN 'large'
WHEN amount >= 50 THEN 'medium'
ELSE 'small'
END AS order_size
FROM orders;
How it works:
- Conditions are checked top to bottom and the first true one wins. Order matters: if
>= 50came first, a 300 USD order would be labeledmedium. ELSEcatches everything else. Without it, unmatched rows get NULL.- Every
CASEends withEND. Give the new column an alias.
When you’re only comparing one expression to fixed values, the shorter simple CASE form reads better:
CASE status WHEN 'completed' THEN 'kept'
WHEN 'refunded' THEN 'lost'
ELSE 'other' END
You can also GROUP BY a CASE expression to count rows per bucket, which is how you’d build an
order-size distribution in one query.
Conditional aggregation
Put CASE inside an aggregate to count or sum only some rows, while still seeing all rows
in the same query. This is how analysts build side-by-side columns without running several
queries:
SELECT channel,
COUNT(*) AS campaigns,
SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) AS active,
SUM(CASE WHEN end_date IS NULL THEN 1 ELSE 0 END) AS always_on
FROM campaigns
GROUP BY channel;
Dates in SQLite
SQLite has no separate date type. Our dates are text in ISO format (2026-03-14), which is
why sorting and comparing them with <, > and BETWEEN works. To pull out parts of a date,
use strftime(format, date):
| Format | Returns for 2026-03-14 |
Typical use |
|---|---|---|
'%Y' |
2026 |
yearly totals |
'%m' |
03 |
month number |
'%Y-%m' |
2026-03 |
monthly reports |
'%d' |
14 |
day of month |
'%w' |
6 (0 = Sunday) |
weekday patterns |
SELECT strftime('%Y-%m', date) AS month,
ROUND(SUM(spend), 2) AS spend
FROM daily_stats
GROUP BY month
ORDER BY month;
Gotcha: strftime returns text. strftime('%m', date) = 3 is false because the value
is the text '03'. Compare to '03', or convert with CAST(strftime('%m', date) AS INTEGER).
A few more helpers:
date('2026-03-14', 'start of month')returns2026-03-01.date('2026-03-14', '+7 days')returns2026-03-21.julianday(end_date) - julianday(start_date)gives the number of days between two dates, handy for campaign length.
Other databases: date functions are the least portable part of SQL. PostgreSQL uses
DATE_TRUNC('month', d)andEXTRACT(DOW FROM d); MySQL and SQL Server haveMONTH(d)andDATEPART. The ideas are identical; only the function names change. The video’sCASEexamples (SQL Server) work unchanged in SQLite.
Practice
Write your answer, press Run to see results and Check answer to grade it. Shortcuts: Ctrl/⌘ + Enter run, Shift + Enter check.
Budget tiers
DoneLabel every campaign with a budget tier. Return name, daily_budget and a third column with the tier:
highwhendaily_budgetis 1000 or more,mediumwhen it is 500 or more (but under 1000),lowotherwise.
Need a hint?
- Add another
WHEN ... THEN ...line between the existing two. - CASE stops at the first true condition, so check
>= 1000before>= 500.
Practice tasks, quizzes and the certificate are part of the course. The first lesson is free to try.
SELECT name,
daily_budget,
CASE WHEN daily_budget >= 1000 THEN 'high'
ELSE 'low'
END AS budget_tier
FROM campaigns;
Tables in this database
advertisers (12 rows)campaigns (40 rows)daily_stats (1,561 rows)customers (300 rows)orders (900 rows)ab_test (4,000 rows)Monthly order report
DoneBuild a monthly order report from orders with four columns: 1. the month as YYYY-MM text (for example 2026-01), 2. the total number of orders that month (any status), 3. the number of completed orders, 4. the total amount of completed orders, rounded to 2 decimals.
Sort by month, oldest first.
Need a hint?
- You can't use
WHERE status = 'completed'here, because column 2 needs all orders. - Count conditionally:
SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END). Use the same idea withamountfor column 4.
Practice tasks, quizzes and the certificate are part of the course. The first lesson is free to try.
SELECT strftime('%Y-%m', order_date) AS month,
COUNT(*) AS orders
FROM orders
GROUP BY month
ORDER BY month;
Tables in this database
advertisers (12 rows)campaigns (40 rows)daily_stats (1,561 rows)customers (300 rows)orders (900 rows)ab_test (4,000 rows)Conversions by day of the week
DoneDo conversions depend on the day of the week? From daily_stats, return two columns: the day name and the total conversions for that weekday. Use exactly these labels: Sun, Mon, Tue, Wed, Thu, Fri, Sat. Sort the rows from Sunday to Saturday.
Need a hint?
strftime('%w', date)returns the weekday as text:'0'for Sunday up to'6'for Saturday.- Translate it with a simple CASE:
CASE strftime('%w', date) WHEN '0' THEN 'Sun' ... END. Keep grouping and sorting by thestrftimevalue so Sunday comes first.
Practice tasks, quizzes and the certificate are part of the course. The first lesson is free to try.
SELECT strftime('%w', date) AS weekday,
SUM(conversions) AS conversions
FROM daily_stats
GROUP BY weekday
ORDER BY weekday;
Tables in this database
advertisers (12 rows)campaigns (40 rows)daily_stats (1,561 rows)customers (300 rows)orders (900 rows)ab_test (4,000 rows)