In This Article, You Will Know About SQL CASE Statement.
SQL CASE Statement – Before moving ahead, let’s know a bit about the SQL SELECT INTO Statement.
Table of Contents
SQL CASE Statement
The SQL CASE Statement reads condition step-by-step and return a value when the first condition met TRUE. Once, the condition is TRUE, it stops reading the condition and returning any result. If no condition is met TRUE, then it returns an answer in the ELSE clause.
If no condition is met and not given any ELSE clause, then it returns NULL.
Syntax
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
WHEN condition3 THEN result3
ELSE result
END;
Example Database
Table name: Data_1
S.No | Name | Roll_No | Section_ID |
1 | Alex | 5 | A |
2 | Rolex | 6 | B |
3 | Salex | 7 | C |
4 | Jalex | 8 | C |
5 | Kalex | 9 | C |
Example: Use the SQL CASE Statement to return the answer if the condition is TRUE.
SELECT Name
CASE
WHEN Name = 'Alex' THEN 'Alex is present'
WHEN Name <> 'Alex' THEN 'Alex not is present'
ELSE 'Alex is missing'
END AS New_Column
FROM Data_1;
Example: Use the SQL CASE Statement to return the answer if the condition is TRUE.
SELECT Name, S.No
CASE
WHEN Name = 'Alex' THEN 'Alex is present'
WHEN Name <> 'Alex' THEN 'Alex not is present'
ELSE 'Alex is missing'
END AS New_Column
FROM Data_1;
Example: Select the Name on the based Section_ID, if Section_ID is NULL, then select from Roll_No.
SELECT Name, Roll_No, Section_ID FROM Data_1
ORDER BY (CASE
WHEN Section_ID IS NULL THEN Roll_No
ELSE Section_ID
END);
If you find anything incorrect in the above-discussed topic and have further questions, please comment below.
Connect on: