In this SQL tutorial I give you an example of how to use SQL SELECT with CASE WHEN THEN ELSE and for the purpose of this tutorial I will use SQL Server 2012.
Very often you want to perform IF statement in SELECT and replace one value with another. In SQL we cannot use IF in SELECT clause however we can achieve the same result using CASE WHEN THEN ELSE.
In the below example I will use a very simple example where I will divide 7 days into 3 parts: Monday to Wednesday, Thursday to FrIday and Saturday to Sunday.
Normally I would use today's date with GETDATE() function or Date Field and use DATEPART function with DW (day of week) to determine day of week and then replace with with my text... so my input value would be something like that DATEPART(DW,GETDATE()) but for simplicity reasons I will just hard code my input value and put just number 7 which is 'Saturday'.
NOTE: Sunday = 1 and Saturday = 7
WHEN 2 THEN 'Monday to Wednesday'
WHEN 3 THEN 'Monday to Wednesday'
WHEN 4 THEN 'Monday to Wednesday'
WHEN 5 THEN 'Thursday to Friday'
WHEN 6 THEN 'Thursday to Friday'
WHEN 7 THEN 'Saturday to Sunday'
WHEN 1 THEN 'Saturday to Sunday'
END AS PartOfWeek
Below is result of the above SQL select statement