Master Case When SQL W3 A Complete Guide

The CASE statement is a powerful tool in SQL (Structured Query Language) used for conditional queries, similar to if-then-else statements in other programming languages. It's particularly useful when you want to return different results based on different conditions. Today, we'll explore the CASE statement in depth, providing examples and explaining its usage with a special focus on SQL tutorials for beginners, like those found on w3schools.

SQL CASE WHEN Explained with Examples | Beginner SQL Tutorial
SQL CASE WHEN Explained with Examples | Beginner SQL Tutorial

Let's kickstart our journey by understanding the basic syntax of the CASE statement, which sets the stage for more complex queries.

SQL Basics Cheat Sheet for Beginners | Learn SQL Fast 💻
SQL Basics Cheat Sheet for Beginners | Learn SQL Fast 💻

Understanding the CASE Statement

The CASE statement evaluates an expression and returns a result based on the value of the expression. It's essentially an extended form of the IF statement, allowing for multiple conditions.

Learn SQL Fast 🚀 | Beginner SQL Commands Cheat Sheet for Data Analysts
Learn SQL Fast 🚀 | Beginner SQL Commands Cheat Sheet for Data Analysts

Here's the basic syntax of the CASE statement:

  1. Simple CASE - This is the basic form of the CASE statement, which checks an expression against a list of values and returns the result of the first matching case:
  2. CASE expression WHEN value THEN result END
  3. Searched CASE - This form evaluates each WHEN clause until it finds a true condition and returns the result of that condition. If no conditions are met, it returns the result of the ELSE clause:
  4. CASE condition1 WHEN result1 THEN result2 WHEN condition2 WHEN result2 THEN result3 END
  5. Else Clause - In both Simple and Searched CASE, if none of the conditions match, the ELSE clause is executed if provided. Otherwise, NULL is returned.
SQL Quick Notes Cheat Sheet | SQL Queries, Joins, Functions & Database Commands for Beginners
SQL Quick Notes Cheat Sheet | SQL Queries, Joins, Functions & Database Commands for Beginners

Simple CASE Statement Example

Let's say we have an Orders table with the columns OrderID, CustomerID, and Quantity. We want to determine the order status based on the quantity. We can use a Simple CASE statement like this:

SELECT OrderID, CustomerID, Quantity, CASE Quantity WHEN 1 THEN 'Small' WHEN 2 THEN 'Medium' WHEN 3 THEN 'Large' END AS 'Order Status' FROM Orders;

Searched CASE Statement Example

7 SQL Projects for Beginners | Build a Real Data Portfolio
7 SQL Projects for Beginners | Build a Real Data Portfolio

Now, let's use a Searched CASE statement to categorize customers based on their total purchase amount. We'll first need to calculate the total purchase for each customer using a subquery.

SELECT CustomerID, (SELECT SUM(Quantity * Price) FROM OrderDetails WHERE CustomerID = o.CustomerID) AS TotalPurchase, CASE WHEN TotalPurchase > 100 THEN 'Premium' WHEN TotalPurchase > 50 THEN 'Gold' ELSE 'Silver' END AS 'Customer Tier' FROM Orders o;

Using CASE in Updates and Deletes

The CASE statement isn't restricted to SELECT queries. It can also be used in UPDATE and DELETE statements to perform conditional updates or deletions.

SQL CTE Explained with Examples | Common Table Expression Tutorial
SQL CTE Explained with Examples | Common Table Expression Tutorial

Conditional Update

Let's update the customer tier based on their latest purchase. We'll use a Searched CASE statement in the SET clause of our UPDATE statement:

SQL Joins Explained with Examples | Complete JOIN Cheat Sheet for Beginners
SQL Joins Explained with Examples | Complete JOIN Cheat Sheet for Beginners
SQL Cheatsheet In 2026 🚀
SQL Cheatsheet In 2026 🚀
Sql Cheat Sheet, Learn Sql, Learn Web Development, Excel Tutorials, Sql Server, Career Options, Data Analyst, Data Scientist, Data Analysis
Sql Cheat Sheet, Learn Sql, Learn Web Development, Excel Tutorials, Sql Server, Career Options, Data Analyst, Data Scientist, Data Analysis
SQL in 60 days
SQL in 60 days
SQL Essentials Cheat Sheet | The Only SQL Notes You'll Need for Revision
SQL Essentials Cheat Sheet | The Only SQL Notes You'll Need for Revision
Complete SQL Cheat Sheet for Beginners | SQL Commands, Joins, Queries & Database Guide
Complete SQL Cheat Sheet for Beginners | SQL Commands, Joins, Queries & Database Guide
SQL IN NUTSHELL
SQL IN NUTSHELL
SQL Cheat Sheet for Beginners
SQL Cheat Sheet for Beginners
SQL IN A NUTSHELL
SQL IN A NUTSHELL
(2) Facebook Software, Engineering
(2) Facebook Software, Engineering
Save This SQL Commands Cheat Sheet Before Your DBMS Exam! 💻📚
Save This SQL Commands Cheat Sheet Before Your DBMS Exam! 💻📚
SQL - Using where clause with not and between operators
SQL - Using where clause with not and between operators
SQL ORDER BY Explained with Examples | Sort Data in SQL
SQL ORDER BY Explained with Examples | Sort Data in SQL
an image of the server list for windows and mac oss servers, with different types of
an image of the server list for windows and mac oss servers, with different types of
a blue and white poster with information about different types of dental equipment on it's side
a blue and white poster with information about different types of dental equipment on it's side
SQL Joins Cheat Sheet Every Developer Should Save
SQL Joins Cheat Sheet Every Developer Should Save
WHOLE SQL CHEAT SHEET
WHOLE SQL CHEAT SHEET
SQL Cheat Sheet for Beginners & Interviews
SQL Cheat Sheet for Beginners & Interviews

UPDATE Customers SET CustomerTier = CASE WHEN LatestPurchase > 100 THEN 'Premium' WHEN LatestPurchase > 50 THEN 'Gold' ELSE 'Silver' END;

Conditional Delete

To delete orders that are more than two years old, we can use a Simple CASE statement in our DELETE statement to ensure we only delete orders with a status of 'Closed':

DELETE FROM Orders WHERE OrderID = CASE WHEN OrderStatus = 'Closed' AND DATEDIFF(year, OrderDate, GETDATE()) > 2 THEN OrderID END;

In conclusion, mastering the CASE statement empowers you to write more sophisticated and dynamic SQL queries. It's a versatile tool that can greatly enhance your SQL skills. Practice and explore to see how it can solve complex data retrieval and manipulation tasks in your projects.

Happy coding, and don't forget to check out more SQL tutorials on w3schools to further enhance your skills!

Related Articles

Procedure In Postgresql W3schools Order By Sql Query Example W3 Sql View Sql W3 Inner Join Sql Query W3 What Does Order By 3 Mean In Sql Triggers In Postgresql W3schools Learn Pl Sql W3schools Sql W3 Like W3 Sql Not Equal