How do I use a case statement in the where clause in SQL Server?

How do I use a case statement in the where clause in SQL Server?

CASE STATEMENT IN WHERE CLAUSE:

  • The CASE statement returns the value based on condition.
  • We can use a case statement in Where, Order by and Group by clause.
  • In the Customer table, I have displayed the First Name is Ram or the Last Name is Sharma?s salary.
  • So, by using a CASE statement with the where condition displays the result.

EXAMPLE:-

  • I want to display Salary in the Customer table the First Name is ?RAM? or Last Name is ?SHARMA?

Image for postCUSTOMER TABLE

QUERY:-

SELECT *

FROM [dbo].[Customer]

WHERE [Salary] =

CASE

WHEN [First_Name] = ?RAM? THEN [Salary]

WHEN [Last_Name] = ?SHARMA? THEN [Salary]

ELSE NULL

END

RESULT:-

Image for postRESULT

If you are new to SQL Server start with the following must-watch video:-

15