CASE Statement in SQL Server

                                                    CASE Statement in SQL Server



The CASE Statement fundamentals


The CASE statement is SQL's way of handling if/then logic. 


What is CASE in SQL?


SQL CASE statement evaluates a condition and returns a result that meets that condition. If none of the conditions is evaluated to TRUE it returns a value from the ELSE block. In simple words, the CASE expression is the way to build the IF - THEN logic into SQL.



Why is CASE so important in SQL?


If you’re analyzing or manipulating data, you’ll often want to define rules based on certain conditions therefore CASE helps us to retrive data based on our requirement.


A quick review of CASE rules:


CASE must be followed by at least one WHEN... THEN expression

Every CASE statement must end with the END keyword

The ELSE argument is optional

CASE can be used in any statement or clause that allows a valid expression

Only 10 levels of nesting are allowed in SQL Server


Syntax example

The syntax for the SELECT statement with a simple CASE expression is as follows:


Database: AdventureWorks2022

SELECT DISTINCT JOBTITLE, MARITALSTATUS,GENDER,SickLeaveHours,

CASE 

WHEN SickLeaveHours > 60 THEN 'REJECT'

WHEN SickLeaveHours > 50 THEN 'PARTIAL REJECT'

WHEN SickLeaveHours BETWEEN 30 AND 50 THEN 'PARTIAL ELIGABLE'

ELSE 'ELIGIBLE'

END AS ELIGIBLE_CRITERIA

FROM HUMANRESOURCES.EMPLOYEE

ORDER BY SickLeaveHours DESC;



Please Follow , Like , Share and Comment to get the valuable insights related to DATA ANALYST / BUSINESS ANALYST related topics.

Follow Thanaselvi C

#happylearning  😊 

 #dataanalytics #dataanalyst #businessanalysis #businessanalytics #carrergrowth #itprofessional #excelskills #sqlserver #sqldeveloper #sqllearning #cdc #coe #fresher #freshgraduate 









Comments

Popular posts from this blog

SQL Case Study Finance Analysis

SQL Query Order of Execution

A Day in the Life of a Data Analyst Interviewee