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
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Database Programming.
Lesson complete
Earn the 3 college credits for Database Programming
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: Grouping Rows and Calculating Summaries with GROUP BY →← 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 →
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.
Enroll now → Course details Download the syllabus All Computer Science courses Every credit course with PRO →
Why take it here
Why students take Database Programming with UPI Study
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.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →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?
Does the order of WHEN conditions matter in a CASE expression?
What does CASE return if no condition matches?
Can you use CASE in ORDER BY or WHERE?
About the Database Programming course
How many college credits is Database Programming?
How much does Database Programming cost and what is included?
Which universities accept UPI Study credits?
How long does Database Programming take?
How are the exams done?
How do my credits reach my college?
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
3 credits · NCCRSEnroll →