How to use the CASE WHEN statement in a query?
Jun 20, 2025 am 12:59 AMThe SQL CASE WHEN statement is used to handle conditional logic in queries by returning different results based on specified conditions. It functions like an if-else statement and can be applied in SELECT, WHERE, ORDER BY, and HAVING clauses. For example, it can classify sales as “Low”, “Medium”, or “High” based on amount ranges. Additionally, CASE WHEN supports data transformation, summary reporting, and conditional aggregation when paired with functions like SUM() or COUNT(). Best practices include testing conditions in order, avoiding overly long blocks, ensuring no overlapping conditions accidentally skip matches, and simplifying with helper tables or functions where possible.
When writing SQL queries, sometimes you need to handle conditional logic — like categorizing data or transforming values based on specific conditions. That’s where the CASE WHEN
statement comes in handy. It works a bit like an if-else statement in programming languages and lets you return different results depending on your data.
Basic Syntax of CASE WHEN
At its core, the CASE WHEN
structure is straightforward. You define one or more conditions using WHEN
, specify what should happen with THEN
, and finish it off with END
. Here's the general format:
SELECT column1, CASE WHEN condition1 THEN result1 WHEN condition2 THEN result2 ELSE default_result END AS new_column_name FROM table_name;
The ELSE
part is optional but useful for catching any unmatched cases. If you don’t include it and no condition matches, the result will be NULL
.
A quick example: say you have a sales table and want to label each sale as “Low”, “Medium”, or “High” based on the amount:
SELECT sale_amount, CASE WHEN sale_amount < 100 THEN 'Low' WHEN sale_amount BETWEEN 100 AND 500 THEN 'Medium' ELSE 'High' END AS sale_category FROM sales;
This gives you a new column that classifies each row based on the value in sale_amount
.
Using CASE in Different Parts of a Query
One nice thing about CASE WHEN
is that you can use it in various parts of a SQL query — not just in the SELECT
clause.
- In SELECT: As shown earlier, this is common for creating derived columns.
- In WHERE: Useful when filtering rows based on conditional logic.
- In ORDER BY: Helps sort data dynamically based on certain rules.
- In HAVING (for grouped data): Can help filter aggregated results conditionally.
Here’s an example using CASE
inside ORDER BY
to sort users by custom priority:
SELECT name, role FROM users ORDER BY CASE WHEN role = 'Admin' THEN 1 WHEN role = 'Editor' THEN 2 ELSE 3 END;
This way, admins come first, editors second, and everyone else last — without sorting alphabetically.
Common Use Cases and Tips
There are a few typical scenarios where CASE WHEN
shines:
- Creating summary reports: For instance, grouping age ranges into buckets like “Under 18”, “18–30”, etc.
- Data transformation: Like converting NULLs to “N/A” or turning boolean flags into readable labels.
-
Conditional aggregation: Combine
CASE
with aggregate functions likeSUM()
orCOUNT()
to count only matching rows.
A few tips to keep in mind:
- Always test your conditions in order — once a
WHEN
condition matches, the rest are skipped. - Try to avoid overly long
CASE
blocks; they get hard to read. - Be careful with overlapping conditions — make sure your logic doesn’t accidentally skip expected matches.
If you're dealing with many similar conditions, consider simplifying with helper tables or functions if your database supports them.
That’s how you work with CASE WHEN
in SQL — flexible enough to handle basic labeling and complex logic alike. It’s a must-know tool for anyone doing data reporting or transformation directly in the database.
The above is the detailed content of How to use the CASE WHEN statement in a query?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

MySQL's slow query log is a log record provided by MySQL. It is used to record statements in MySQL whose query time exceeds (greater than) the set threshold (long_query_time) and records them in the slow query log.

PHP and PDO: How to execute complex SQL query statements When processing database operations, PHP provides a powerful extension library PDO (PHPDataObjects) to simplify interaction with the database. PDO supports a variety of databases, such as MySQL, SQLite, etc., and also provides a wealth of functions and methods to facilitate developers to perform various database operations. This article will introduce how to use PDO to execute complex SQL query statements, and attach corresponding code examples. Connect to the database

In web development, tables are the most basic and commonly used elements, and PHP is a popular server-side programming language. There are many common techniques and methods in table operations. This article will introduce common table operations in PHP programming. Displaying data tables In PHP, you can use the table tag in HTML to display data tables. It is worth noting that the table must be generated in a PHP script. Here is an example of a basic HTML table tag: <table><tr>

In Go programming, using SQL queries is a common task. However, sometimes errors occur when executing SQL queries, causing the program to fail to execute correctly. In order to solve these errors, we need to have a deep understanding of how SQL queries and the Go language interact. Below are some possible errors and corresponding solutions. Lack of database driver In Go language, you need to use a specific database driver to connect and operate the database. If you try to perform a database query and the database driver is not properly installed and configured

PHP is a powerful server-side scripting language that is widely used in web development. In web development, we often need to interact with the database and execute query statements to obtain data. This article will introduce you to how to write query statements and usage examples in PHP. 1. Connect to the database Before using PHP to query the database, you first need to establish a connection with the database. Generally, we will use the MySQL database as an example. The code to connect to the database is as follows: $servername=

The core function of SQL query is to extract, filter and sort information from the database through SELECT statements. 1. Basic usage: Use SELECT to query specific columns from the table, such as SELECTname, departmentFROMemployees. 2. Advanced usage: Combining subqueries and ORDERBY to implement complex queries, such as finding employees with salary above average and sorting them in descending order of salary. 3. Debugging skills: Check for syntax errors, use small-scale data to verify logical errors, and use the EXPLAIN command to optimize performance. 4. Performance optimization: Use indexes, avoid SELECT*, and use subqueries and JOIN reasonably to improve query efficiency.

How to optimize SQL query statements and index usage in PHP development? In PHP development, database query is a very common operation. However, when the amount of data increases, query performance may be affected, causing the application to slow down. In order to improve query performance, we need to optimize the use of SQL query statements and indexes. This article will introduce some optimization tips and best practices to help you improve SQL query performance in PHP development. 1. Use the correct index: Index is an important part of the database to improve query performance. in design data

BookmarksinphpMyAdminaresavedSQLqueriesthatstreamlinerepetitivetasks.Tousethem,createabookmarkbyclicking“Bookmarkthisquery”afterwritingorrunningaquery,optionallylabelit,andsetuseraccess.Savedbookmarksappearunder“BookmarkedSQLqueries”intheSQLwindow,wh
