IF
like conditional statements in SQL, CASE
is your answer.CASE
can be added to both the SELECT
portion of a SELECT
statement as well as the ORDER BY
portionCASE
statements can be used inside other CASE
statementsWith
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.
1SELECT
2 CASE <variable>
3 WHEN <value> THEN <returnvalue>
4 WHEN <othervalue> THEN <returnthis>
5 ELSE <returndefaultcase>
6 END AS <newcolumnname>
7FROM <table>
AS <newcolumnname>
after the END
names the resulting column. Optional.