CASE expressions
Branch inside a query to label rows, bucket values and sort custom orders.
What you will be able to do
- Write searched CASE expressions
- Aggregate with conditional counts
- Sort with a custom priority
CASE returns a value from the first matching branch. Use it to classify rows without changing the stored data.
SELECT title, minutes,
CASE
WHEN minutes >= 15 THEN 'Long'
WHEN minutes >= 12 THEN 'Medium'
ELSE 'Short'
END AS length_band
FROM lessons
ORDER BY minutes DESC;
SELECT course_slug,
COUNT(*) AS total,
SUM(CASE WHEN minutes >= 15 THEN 1 ELSE 0 END) AS long_lessons
FROM lessons
GROUP BY course_slug
ORDER BY long_lessons DESC;- The first matching WHEN wins, so order branches from most specific to least.
- Without ELSE, an unmatched CASE returns NULL.
- SUM(CASE WHEN ... THEN 1 ELSE 0 END) counts rows that meet a condition.
- CASE also works in ORDER BY for a custom sort key.
Your turn
MediumBand the courses
For each course_slug, return the rounded average minutes and a band: Deep at 15 or more, Standard at 12 or more, otherwise Fast.
SQL · starter
SELECT course_slug,
AVG(minutes) AS avg_minutes
FROM lessons
GROUP BY course_slugCheck your understanding before moving on.
Knowledge checkQuestion 1
What does CASE return when no WHEN matches and there is no ELSE?
Select an answer to continue
Study tools
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign inFinished reading?
Lock in what you just learned.
0%
Mark this lesson complete to save your place and move one step closer to the certificate.