Conditional Logic in SQL: The CASE Statement, Explained

UPI Study › Courses › Database Programming › Free lessons › Lesson 5.8 Free with a free account

Conditional Logic in SQL: The CASE Statement

Database Programming · Chapter 5: Querying, Filtering, and Sorting DataSection 5.8 · lesson 33 of 769 min · free with a free account

← Replacing Nulls with the NVL FunctionNext lesson: Grouping Rows and Calculating Summaries with GROUP BY →

A free account plays all of Chapter 1 and 3 more lessons of Database Programming. Create a free account →

Earn 3 college credits for Database ProgrammingRecommended for credit by NCCRS · Computer Science 381 · self-paced · one payment, lifetime access

In this lesson

Using simple and searched CASE expressions to label, sort, and filter rows.

  • Distinguish simple CASE equality mappings from searched CASE conditions
  • Order overlapping WHEN conditions so the intended branch is chosen first
  • Explain what CASE returns when no branch matches or a value is NULL
  • Use CASE expressions in SELECT, ORDER BY, and WHERE clauses

Free study notes

Get this lesson's notes by email

The key points and 4 practice questions with answers, in your inbox. One email, free.

One email. Unsubscribe in one click.

Transcript

Everything said in the video, section by section (1,065 words). Read along, or search it.

Opening Question

Largest Balances Labeled Silver

Maya Rao wants Lantern Books' loyalty report to show readable tiers. Her first attempt labels every customer above one hundred points Silver, including the largest balances. The arithmetic is correct, but the decision rules are in the wrong order. How can a query choose a label without losing the higher tier? Case is an expression that selects a value. Its first true condition determines the result, so both the boundaries and the order of tests matter.

Definition

WHEN, THEN, ELSE, and END

Start with our canonical customer points and cities. These illustrative balances let us test exact matches, ranges, and a row-dependent threshold. A case expression in select calculates another output value. It does not update the stored point balance or membership record. When introduces a match or condition, then supplies a result, and else supplies a fallback. End closes the complete expression. An alias names the calculated output. Here case means an expression, distinct from procedural case statements that some systems provide inside stored programs.

Simple CASE

Mapping Cities to Countries

Simple case puts one expression after case, then lists values to compare for equality. It suits a small collection of exact codes or names. Here each city is compared with the listed cities. A matching when supplies its country label; a city outside the list uses Other. This is a reporting mapping for these sample cities. A production geography model may need identifiers and maintained reference data, instead of hard-coded text. Run the mapping. The result retains each original city and adds the chosen country, making the transformation easy to inspect. All six customers match a listed city. A simple case can be rewritten using complete equality conditions, but its compact form cannot directly express a range.

Searched CASE

Higher Point Threshold First

Searched case has no comparison expression after case. Each when contains its own condition, so it can use ranges, null tests, and combined predicates. Place the higher point threshold first. A customer meeting that condition also meets the lower threshold, but the first true branch determines the label. The remaining qualifying customers reach Silver, and everybody else reaches Bronze. For these nonnull balances, the fallback covers values below the lower threshold. Run the ordered rules. End closes the expression, and the alias tier names its result beside the original points. Elena receives Gold, Asha and Chen receive Silver, and the others receive Bronze. The stored balances have not changed.

Common Mistake

Reversed Conditions Hide the Gold Tier

Reverse the overlapping conditions, and the meaning changes. The broad Silver threshold now catches everybody who might otherwise qualify for Gold. The later Gold branch cannot win for these numeric balances. This is a logic error in a valid expression, so a syntax check will not rescue it. Run the altered rules on the larger balances. Comparing results with the intended policy is essential, even when the database reports successful execution. Chen and Elena both become Silver. To repair the report, put the narrower high-balance condition before the broader lower-balance condition.

NULL and ELSE

Missing ELSE and NULL Matching

An omitted else returns null when nothing matches. That can be intentional, but an accidental gap may make a report look incomplete. Simple case compares by ordinary equality. When null is not a successful match for null, because that equality is unknown rather than true. Use a searched case with is null for missingness. Keep the result branches compatible too, avoiding accidental text-to-number conversion rules. Run these small examples. They separate an unmatched city, an equality attempt, and an explicit missingness condition. The unmatched city produces null, ordinary equality chooses Other, and the direct test chooses Missing. A fallback is part of the policy, not merely punctuation.

CASE in ORDER BY

Custom Sort Putting Pune First

Case can appear wherever a suitable value expression is allowed. In order by, it can construct a ranking that no stored column directly provides. This expression assigns Pune a smaller sort number. Later keys order names inside each resulting bucket, with the identifier resolving any remaining tie. Run the custom order. Case supplies a numeric sort key, rather than moving records into a different permanent storage position. The Pune customers appear first, with other cities afterward. This changes presentation without filtering away anybody or changing the cities themselves.

CASE in WHERE

City-Dependent Point Thresholds

In where, let case return the threshold and compare points with that number. Pune uses one hundred; other cities use two hundred. This is a value-producing expression inside a predicate. Returning a predicate itself from then is not a portable SQL Server form. Run the row-dependent rule. The same expression chooses a threshold independently for each input record. Asha, Chen, and Elena qualify. Farid is in Pune but below its threshold, while Ben and Dara are below the threshold for their cities.

Bucketing

Labeling Versus Bucketing Values

For price bucketing, use the unchanged bookstore product baseline. A bucket maps a continuous measure to a small collection of named ranges. Labeling translates a code into readable text; bucketing assigns values to bands. Both are expressions that can later support reports or aggregate summaries.

Worked Example

Price Bands With Exact Boundaries

Define ranges deliberately. Prices below five are Budget; remaining prices below twenty are Standard; the fallback covers the higher band. An exact boundary needs a home. Less than twenty leaves twenty itself for the fallback, while less than or equal would change that policy. Run the price bands. Compatible text results and a clear alias make the derived classification readable. The product rows receive one band each. Case can also feed aggregates later, but it is not a universal guard against expressions evaluated earlier by an engine.

Quick Check

A Boundary Test and a NULL Comparison

A new duration rule tests an exact boundary, followed by an ordinary comparison involving null. The fallback supplies the remaining label. Which label does the written case return? Check each condition's truth value in order. Pause, and decide.

Answer

Neither WHEN Is True, So ELSE Wins

The answer is Long label. Six is not less than six, and null equal to one is unknown, so neither when is true. The fallback supplies Long. Short would require a different boundary operator, and Missing would require a true condition such as an explicit missingness test. The run confirms the value selected by these rules. Trace the expression actually written, then decide whether those rules match the intended policy.

Key Takeaways

Order Conditions and Cover Fallbacks

Maya's report now gives the higher tier its chance before testing the broader range. She can explain the label for every boundary and missing-value case. Choose simple case for equality mappings, and searched case for conditions. Keep branches compatible, cover intended fallbacks, and close the expression with end. Use the resulting value in select, sorting, or a comparison. A case expression makes a reporting decision; clear conditions make that decision reviewable.

About Database Programming at UPI Study

Database Programming (Computer Science 381) is a self-paced online course of 76 video lessons in 12 chapters, from database applications, SQL setup, schema planning and normalization to keys and constraints, data types, filtering and sorting, joins, subqueries, views, indexes, ROLLUP and PIVOT, regular expressions and database security. It carries a NCCRS credit recommendation for 3 semester credits.

Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Compare: Database Fundamentals vs Database Programming

Why take it here

Why students take Database Programming with UPI Study

Write the SQL behind every appDatabase Programming teaches SQL in MySQL and SQL Server side by side: designing and normalizing tables, keys and constraints, data types, inserting, updating and deleting rows, filtering, grouping, joins, subqueries, views, indexes, transactions, and protecting data from SQL injection. It suits computer science and information technology degrees.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Where the credit goes

Universities that work with NCCRS

Database Programming carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.

FAQ

Questions students ask us

About Conditional Logic in SQL: The CASE Statement

What is the difference between simple CASE and searched CASE?
A simple CASE compares one expression against a list of values for equality, while a searched CASE evaluates a separate condition in each WHEN. CASE city WHEN 'Pune' THEN 'India' ELSE 'Other' END is simple. CASE WHEN points >= 200 THEN 'Gold' ELSE 'Bronze' END is searched, because it tests a range. Use the searched form for ranges, tests on several columns, or IS NULL checks, which simple CASE cannot express.
Does the order of WHEN conditions matter in a CASE expression?
Yes, CASE returns the result of the first WHEN condition that is true and skips the rest. If WHEN points > 100 THEN 'Silver' comes before WHEN points > 500 THEN 'Gold', a customer with 600 points is labeled Silver, and the Gold branch can never win. The query still runs without an error, so check overlapping conditions and list the most restrictive threshold first.
What does CASE return if no condition matches?
Without an ELSE branch, CASE returns NULL when no WHEN matches. A NULL value also does not match a simple CASE branch, so CASE bonus WHEN NULL THEN 'Missing' END returns NULL instead of 'Missing'. Use a searched test instead: CASE WHEN bonus IS NULL THEN 'Missing' ELSE 'Recorded' END. Add an ELSE to cover unexpected values, and keep every branch's result a compatible data type.
Can you use CASE in ORDER BY or WHERE?
Yes, a CASE expression can appear wherever a value is allowed, including ORDER BY and WHERE. ORDER BY CASE WHEN city = 'Pune' THEN 0 ELSE 1 END, name lists Pune first, then the rest alphabetically. WHERE points >= CASE WHEN city = 'Pune' THEN 100 ELSE 200 END applies a city-dependent threshold. CASE returns a value, not a condition, so SQL Server rejects a THEN that tries to return a comparison.

About the Database Programming course

How many college credits is Database Programming?
Database Programming (Computer Science 381) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Database Programming cost and what is included?
$250, paid once, with lifetime access: all 76 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Database Programming take?
It is self-paced with no deadlines. The 76 lessons total about 11 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

Ready for the full course? Earn 3 credits in Database Programming.

76 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

Updated

Database Programming
3 credits · NCCRS
Enroll →