Conditional Statements in SQL with CASE
- If you have ever wondered how to
IF
like conditional statements in SQL,CASE
is your answer. - It’s supported in all versions of SQL Server
CASE
can be added to both theSELECT
portion of aSELECT
statement as well as theORDER BY
portionCASE
statements can be used inside otherCASE
statements
With
CASE
you can easily group data into various ranges, you can beautify the results of a SQL query, and can allow for dynamic sorting of the query’s results.CASE
statements can also be used to give subtitles toROLLUP
andCUBE
queries, and can be used in computed columns to boot.
SELECT
CASE <variable>
WHEN <value> THEN <returnvalue>
WHEN <othervalue> THEN <returnthis>
ELSE <returndefaultcase>
END AS <newcolumnname>
FROM <table>
AS <newcolumnname>
after theEND
names the resulting column. Optional.