Skip to content
Learn Netverks

Lesson

Step 26/36 72% through track

case-expressions

CASE expressions

Last reviewed May 28, 2026 Content v20260528
Track mode
sql_sandbox
Means
SQL sandbox
Reading
~2 min
Level
intermediate

This lesson

This lesson teaches CASE expressions: the SQL patterns, schema habits, and query reasoning you need before advancing in SQL.

Teams query CASE expressions on every SQL codebase—skipping it leaves gaps in debugging and data reviews.

You will apply CASE expressions in contexts like: Postgres, MySQL, SQLite, warehouses, and ORMs that still expose SQL.

Copy SQL from each lesson into SQLite (sqlite3), DB Fiddle, or local Postgres—read result grids and row counts. The in-browser SQL lab (sql_sandbox) will run queries when the runner ships; until then, local clients are the practice path.

When you can explain the previous lesson's ideas without copying example queries verbatim.

CASE adds conditional logic in SELECT, WHERE, ORDER BY, and aggregates—SQL's answer to if/else without leaving the query.

Simple CASE

SELECT id,
       total,
       CASE
         WHEN total >= 100 THEN 'large'
         WHEN total >= 50 THEN 'medium'
         ELSE 'small'
       END AS order_size
FROM orders;

Practice: Advanced features vary by engine—SQLite 3.25+ supports window functions; test your version with a simple query.

CASE in aggregation

SELECT COUNT(CASE WHEN total >= 100 THEN 1 END) AS large_orders,
       COUNT(CASE WHEN total < 100 THEN 1 END) AS other_orders
FROM orders;

Conditional counts pivot categories in one pass—precursor to dedicated PIVOT syntax in some engines.

Searched vs simple

SELECT status,
       CASE status
         WHEN 'pending' THEN 1
         WHEN 'shipped' THEN 2
         ELSE 99
       END AS sort_key
FROM orders
ORDER BY sort_key;

Simple CASE compares to a single expression; searched CASE uses independent predicates.

Important interview questions and answers

  1. Q: CASE vs IF()?
    A: CASE is standard SQL; IF is MySQL-specific.
  2. Q: ELSE required?
    A: Omitting ELSE yields NULL when no branch matches—sometimes intentional.

Self-check

  1. How do you bucket numeric totals into labels in SQL?
  2. What value if no WHEN matches and no ELSE?

Tip: CASE in aggregates pivots categories without a separate PIVOT syntax.

Interview prep

CASE without ELSE?

Returns NULL when no branch matches.

CASE vs IF (MySQL)?

CASE is portable ANSI; IF is MySQL-specific.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • CASE in SELECT?
  • Pivot with CASE?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump