CASE

Labels with CASE WHEN

SQLite in your browser
Lesson concept What you'll do
1 / 4

Give each book a label, like Long or Short.

CASE WHEN test THEN label works like IF in Excel. Check the biggest band first.

The database
10 rows
book_idtitleauthorgenreyearpages
1The Time MachineH.G. WellsScience Fiction1895118
2Pride and PrejudiceJane AustenRomance1813432
3MockingjaySuzanne CollinsScience Fiction2010390
4The Great GatsbyF. Scott FitzgeraldFiction1925180
5Angels & DemonsDan BrownThriller2000616
6DuneFrank HerbertScience Fiction1965412
7Charlotte's WebE.B. WhiteChildren1952184
8The Fellowship of the RingJ.R.R. TolkienFantasy1954423
9FrankensteinMary ShelleyHorror1818280
10The Fault in Our StarsJohn GreenRomance2012313
Click a name to type it
Your query
 
Hint: click the green edit button on the board, or type it yourself
Query output Ready to run

Run your query to see the result table.

Press the green Run button or Ctrl+Enter.

Study notes

How CASE works

CASE checks the WHENs from the top and stops at the first one that is true.

pick a book

  1. WHEN pages >= 400 THEN 'Long' 418 >= 400: true, stop here
  2. WHEN pages >= 250 THEN 'Medium' never checked
  3. ELSE 'Short' never checked
  4. Dracula comes out 'Long'
  • What does CASE do?

    CASE WHEN pages >= 400 THEN 'Long' ELSE 'Short' END

    It works out a value for each row from tests, like IF or IFS in Excel. The whole CASE ... END is one column.

  • What order are the WHENs checked in?

    Top to bottom, and the first true one wins. Put the strictest test first: >= 400 before >= 250.

  • What if no WHEN is true?

    The row gets the ELSE value. With no ELSE, it gets NULL.

  • Where can CASE go?

    Anywhere a value can: in SELECT, in ORDER BY, even inside SUM: SUM(CASE WHEN genre = 'Horror' THEN 1 ELSE 0 END) counts Horror books.

  • How is this like Excel?

    It's IFS: =IFS(F2>=400, "Long", F2>=250, "Medium", TRUE, "Short"), with ELSE as the final TRUE.

Other databases

How other databases do it

The lessons run on SQLite. Most of SQL is the same everywhere; these are the places where this lesson's SQL differs.

A shorter way for a two-way choice
DatabaseHowNote
SQLite (these lessons)IIF(year < 1900, 'Classic', 'Modern')Since SQLite 3.32 (2020).
PostgreSQLCASE only
MySQL / MariaDBIF(year < 1900, 'Classic', 'Modern')
SQL ServerIIF(year < 1900, 'Classic', 'Modern')Since SQL Server 2012.
OracleCASE onlyDECODE(x, a, b, c) is an older shortcut, but only for "equals".
Sybase ASECASE only

Know someone fighting with a spreadsheet? Send them this page.