Home > Database > Mysql Tutorial > How Can I Use SQL's CASE Statement to Perform Conditional Evaluations in SELECT Queries?

How Can I Use SQL's CASE Statement to Perform Conditional Evaluations in SELECT Queries?

Patricia Arquette
Release: 2024-12-28 01:50:09
Original
363 people have browsed it

How Can I Use SQL's CASE Statement to Perform Conditional Evaluations in SELECT Queries?

Understanding the CASE Statement in SELECT Queries

In SQL, the CASE statement allows you to perform conditional evaluations and return different results based on the specified conditions. This is especially useful when you want to categorize or classify data based on certain criteria.

Consider the following example:

SELECT xxx, yyy,
CASE
    WHEN bbb THEN 'blackberry'
    WHEN sss THEN 'samsung'
END 
FROM (
    SELECT ???? .....
)
Copy after login

In this example, the result would display the values of xxx and yyy along with the following:

Name Age Handphone
xxx1 yyy1 blackberry
xxx2 yyy2 blackberry

Syntax and Reference

For a comprehensive understanding of the CASE statement syntax and usage, refer to credible resources such as Microsoft's Transact-SQL Reference:

https://msdn.microsoft.com/en-us/library/ms181765.aspx

Example Usage

Let's consider a scenario where you want to categorize products in AdventureWorks2012 database based on their list prices:

USE AdventureWorks2012;
GO

SELECT ProductNumber, Name, 
"Price Range" = 
CASE 
    WHEN ListPrice = 0 THEN 'Mfg item - not for resale'
    WHEN ListPrice < 50 THEN 'Under '
    WHEN ListPrice >= 50 AND ListPrice < 250 THEN 'Under 0'
    WHEN ListPrice >= 250 AND ListPrice < 1000 THEN 'Under 00'
    ELSE 'Over 00'
END
FROM Production.Product
ORDER BY ProductNumber;
GO
Copy after login

This query will output the following result:

ProductNumber Name Price Range
1 Bike Under 0
2 Chair Under
3 Table Under 0

Additional Resource

For further exploration of SQL Server, consult the SQL Server Central website:

https://www.sqlservercentral.com/

The above is the detailed content of How Can I Use SQL's CASE Statement to Perform Conditional Evaluations in SELECT Queries?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template