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.

30 min 3 practice tasks
Intermediate SQL Tutorial | Case Statement | Use Cases by Alex The Analyst on YouTube

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 >= 50 came first, a 300 USD order would be labeled medium.
  • ELSE catches everything else. Without it, unmatched rows get NULL.
  • Every CASE ends with END. 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') returns 2026-03-01.
  • date('2026-03-14', '+7 days') returns 2026-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) and EXTRACT(DOW FROM d); MySQL and SQL Server have MONTH(d) and DATEPART. The ideas are identical; only the function names change. The video’s CASE examples (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.

1

Budget tiers

Label every campaign with a budget tier. Return name, daily_budget and a third column with the tier:

  • high when daily_budget is 1000 or more,
  • medium when it is 500 or more (but under 1000),
  • low otherwise.
Need a hint?
  1. Add another WHEN ... THEN ... line between the existing two.
  2. CASE stops at the first true condition, so check >= 1000 before >= 500.
SQL · SQLite
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)
id, name, industry, country
campaigns (40 rows)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status
daily_stats (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
customers (300 rows)
id, first_name, last_name, email, country, segment, age_group, signup_date
orders (900 rows)
id, customer_id, campaign_id, order_date, amount, status
ab_test (4,000 rows)
user_id, variant, device, time_on_page_sec, converted, revenue
2

Monthly order report

Build 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?
  1. You can't use WHERE status = 'completed' here, because column 2 needs all orders.
  2. Count conditionally: SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END). Use the same idea with amount for column 4.
SQL · SQLite
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)
id, name, industry, country
campaigns (40 rows)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status
daily_stats (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
customers (300 rows)
id, first_name, last_name, email, country, segment, age_group, signup_date
orders (900 rows)
id, customer_id, campaign_id, order_date, amount, status
ab_test (4,000 rows)
user_id, variant, device, time_on_page_sec, converted, revenue
3

Conversions by day of the week

Do 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?
  1. strftime('%w', date) returns the weekday as text: '0' for Sunday up to '6' for Saturday.
  2. Translate it with a simple CASE: CASE strftime('%w', date) WHEN '0' THEN 'Sun' ... END. Keep grouping and sorting by the strftime value so Sunday comes first.
SQL · SQLite
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)
id, name, industry, country
campaigns (40 rows)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status
daily_stats (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
customers (300 rows)
id, first_name, last_name, email, country, segment, age_group, signup_date
orders (900 rows)
id, customer_id, campaign_id, order_date, amount, status
ab_test (4,000 rows)
user_id, variant, device, time_on_page_sec, converted, revenue