Home > Database > Mysql Tutorial > How Can SQL's CASE Statement Be Used to Conditionally Assign Values in SELECT Queries?

How Can SQL's CASE Statement Be Used to Conditionally Assign Values in SELECT Queries?

Barbara Streisand
Release: 2024-12-29 17:12:15
Original
466 people have browsed it

How Can SQL's CASE Statement Be Used to Conditionally Assign Values in SELECT Queries?

Understanding CASE in SELECT Statements

In SQL, the CASE statement offers a flexible approach to conditionally retrieve data based on specific criteria. To understand how CASE works within a SELECT statement, let's consider an example where we want to assign values to a new column based on existing conditions:

Consider the query:

SELECT xxx, yyy,
CASE
  WHEN bbb = 'blackberry' THEN 'blackberry'
  WHEN sss = 'samsung' THEN 'samsung'
  ELSE NULL
END AS 'Handphone'
FROM (
  SELECT ???? .....
);
Copy after login

Here, the CASE statement is used to evaluate the values of two columns, bbb and sss. If bbb matches 'blackberry', 'blackberry' is assigned as the value for the new column 'Handphone'. Similarly, if sss matches 'samsung', 'samsung' is assigned. Otherwise, the value is set to NULL.

The output of this query will resemble the following:

name | age | Handphone |
xxx1 | yyy1 | blackberry |
xxx2 | yyy2 | blackberry |
Copy after login

In this case, 'blackberry' is assigned to 'Handphone' for rows where bbb equals 'blackberry'.

For further reference regarding CASE statement syntax and usage, consult resources such as the MSDN Transact SQL Reference (https://msdn.microsoft.com/en-us/library/ms181765.aspx). Additionally, SQL Server Central (https://www.sqlservercentral.com/) provides a comprehensive collection of resources for SQL Server enthusiasts.

The above is the detailed content of How Can SQL's CASE Statement Be Used to Conditionally Assign Values 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