Introduction to Case Statement in SQL
Many times there is a requirement like you have to display data based on some condition
Let me explain by a example
Suppose in your table you have a column Gender and you have inserted value like
M which denotes Male
F which denotes Female
If no values then Unknown
So for this type of scenarios we use case Statement
Below is the Example of Case Statement
create table employee
(name nvarchar(30),Gender nvarchar(15))
insert into employee values('xyz','M'),('abc','F'),('pqr',Null)
select * from employee
select name,case gender
when 'M' then 'Male'
when 'F' then 'Female'
else 'Unknown'
end
from employee
Don't forget to put end after finishing case statement otherwise it will throw an error.
The Case statement will check data for Gender column it will check if M then display Male
if F then Female else display Unknown
Note: you can achieve this result also by using if else if but when no. of condition are more it's a good practice to use Case Statement.
No comments:
Post a Comment