Lesson 5 of 5

Progress: 0/3 exercises solved (0%)

← PreviousFinal lesson

Solve all exercises below to unlock the next lesson.

CASE WHEN — conditional logic in SQL

Lesson Description

Build confidence in SQL Fundamentals by practicing this lesson with structured prompts and real query execution.

Easy Project

Mini project: Turn this lesson into a real-world query artifact by writing one clean business report query and validating output quality.

CASE WHEN — conditional expressions

CASE WHEN evaluates conditions top-to-bottom and returns the result for the first match. It is SQL's if/else.

Searched CASE (most common)

SELECT
  first_name,
  salary,
  CASE
    WHEN salary < 5000  THEN 'Junior'
    WHEN salary < 10000 THEN 'Mid'
    ELSE 'Senior'
  END AS tier
FROM employees;
  • Conditions are tested in order; the first match wins.
  • ELSE is optional. If omitted and no condition matches, the result is NULL.
  • END closes the expression.

Simple CASE (equality checks only)

SELECT
  id,
  CASE status
    WHEN 'shipped'   THEN 'On the way'
    WHEN 'delivered' THEN 'Complete'
    WHEN 'cancelled' THEN 'Cancelled'
    ELSE 'Processing'
  END AS status_label
FROM orders;

CASE in ORDER BY

Control sort order programmatically:

ORDER BY
  CASE status
    WHEN 'cancelled' THEN 1
    WHEN 'pending'   THEN 2
    ELSE 3
  END

CASE in aggregates (conditional counting)

SELECT
  COUNT(*) FILTER (WHERE salary < 5000)  AS junior_count,
  COUNT(*) FILTER (WHERE salary >= 5000
                     AND salary < 10000) AS mid_count,
  COUNT(*) FILTER (WHERE salary >= 10000) AS senior_count
FROM employees;

(The FILTER approach is cleaner; CASE inside COUNT works too.)

Tips

  • CASE can be used in SELECT, WHERE, ORDER BY, GROUP BY, and HAVING.
  • Nest CASE expressions for multi-dimensional logic, but prefer FILTER or a lookup table for readability.
  • All branches must return compatible data types.

Learning context

This lesson is part of SQL Fundamentals. Focus on the core idea in CASE WHEN — conditional logic in SQL, then validate with deliberate practice.

What to master

  • Understand clause order and intent
  • Write deterministic result queries
  • Use clear aliases and readable structure

Common mistakes

  • Skipping ORDER BY in final outputs
  • Using joins before validating base rows
  • Not checking row counts after changes

High-level strategy

  • Start simple, then layer complexity
  • Run often and compare expected shape
  • Refactor with CTEs when logic grows

Task ladder

  1. Baseline query: get a correct first output.
  2. Add one complication: edge case, join, filter, or ranking rule.
  3. Re-run and refine until output is stable and explainable.

Transparent data checks

  • Check row count before and after each major clause.
  • Validate one manual sample row for correctness.
  • Confirm final ordering and column naming for trust.

Retention loop

  • Run the solution once.
  • Rewrite from memory with one variation.
  • Explain the logic in plain English in one sentence.

Logical reasoning for commands

WHERE

Why: Limits rows to only the business-relevant subset.

Memory cue: Filter early to reduce noise.

ORDER BY

Why: Makes output deterministic and reviewable.

Memory cue: No ORDER BY means no guaranteed row order.

AS alias

Why: Makes output columns readable for teams and reports.

Memory cue: If the name is clear, the query is easier to trust.

Concept check

Quick check: CASE WHEN — conditional logic in SQL

3 quick questions. One at a time. Instant score at the end.

Exercise 1

Employee salary tier

Enterprise Workforce Analyticseasy

Return first_name, last_name, salary, and a tier column: 'Junior' if salary < 5000, 'Mid' if salary < 10000, otherwise 'Senior'. Order by salary ascending.

Run a query to see results here.
Exercise 2

Human-readable order status

Commerce Operations Intelligenceeasy

From the store sandbox, return id (alias order_id) and a status_label column that maps: 'shipped' → 'On the way', 'delivered' → 'Complete', 'cancelled' → 'Cancelled', anything else → 'Processing'. Order by id.

Run a query to see results here.
Exercise 3

Patient age group classification

Clinical Care Performanceeasy

From the hospital sandbox, return first_name, last_name, date_of_birth, and an age_group column: 'Born after 1990' if dob > 1990-01-01, 'Born 1960–1990' if dob > 1960-01-01, otherwise 'Born before 1960'. Order by date_of_birth DESC.

Run a query to see results here.

Final checkpoint

End-of-course high-level quiz

Pass mark: 80%. Review each explanation after you submit.

1. Which clause should you use to filter grouped results?

2. What is the safest way to avoid accidental row multiplication in joins?

3. Which feature is best for ranking rows within partitions?

4. Why should final analytical queries usually include ORDER BY?

5. When query logic gets complex, what improves readability most?

Lesson 5 of 5

0/3 solved (0%)

← PreviousFinal lesson

Finish this lesson to unlock next.