FROM [AdventureWorks2017].[HumanResources].[Employee];
Nesting CASE expression:
SELECT
[BusinessEntityID]
,[JobTitle]
,[HireDate]
,Seniority = CASEWHEN DATEDIFF(YEAR,[HireDate],GETDATE()) > 10 THEN'Longer than 10 years'
WHEN DATEDIFF(YEAR,[HireDate],GETDATE()) = 10 THEN'Exactly 10 years'
WHEN DATEDIFF(YEAR,[HireDate],GETDATE()) < 10 THEN'Shorter than 10 years'
ELSE'N/A'END
FROM [HumanResources].[Employee];
NOTE : CASE can not only be used in SELECT statements, but at any other place where an expression can be written. This includes UPDATE, DELETE, SET, MERGE, a WHERE or HAVING clause and an ORDER BY clause.
Example use in Order By :
SELECT
[BusinessEntityID]
,[JobTitle]
FROM [AdventureWorks2017].[HumanResources].[Employee]
Here is an example of CASE statement in SQL. You have a table of employees and want to check the designation on the basis of salary, you can write your using CASE-WHEN as:
Select EmployeeName, Salary,
CASE
WHEN Salary >=80000 AND Salary <=100000 THEN'Director'
WHEN Salary >=50000 AND Salary <80000 THEN'Senior Consultant'
CASE statements are used to create different outputs (Usually in the SELECT statement).
It is SQL's way of handling if-then logic.
SELECT
CASEWHEN [CONDITION 1] THEN'OUTPUT 1'
WHEN [CONDITION 2] THEN'OUTPUT 2'
ELSE'OUTPUT 3'END
FROM [TABLE_NAME]
In the above query, the output will be based on the conditions, if CONDITION 1 is true then the output will be OUTPUT 1, likewise, if CONDITION 2 is true then the output will be OUTPUT 2, if both conditions are false then the output will be OUTPUT 3.
Anupam MaitiPosted Apr 26, 2022, 6:41 AM
Kapil Singh KumawatPosted Apr 25, 2022, 10:11 AM
Hello,
Here is the sample example of using case in sql server
--Simple CASE expression: CASE input_expression WHEN when_expression THEN result_expression [ ...n ] [ ELSE else_result_expression ] END
for more info please refer Microsoft Docs-
https://docs.microsoft.com/en-us/sql/t-sql/language-elements/case-transact-sql?view=sql-server-ver15
Sachin SinghPosted Apr 24, 2022, 5:31 PM
Muhammad Imran AnsariPosted Apr 24, 2022, 10:37 AM
Md SarfarajPosted Apr 21, 2022, 5:16 AM
Ravinder SharmaPosted Apr 21, 2022, 2:09 AM
Uttam KumarPosted Apr 20, 2022, 7:25 AM