SQL Server in a minute: The CASE expression (the equivalent of the Excel IF function)



The CASE expression and the IIF function allows you to test values or conditions, and get different outcomes.
My SQL Server Udemy courses are:
70-461, 70-761 Querying Microsoft SQL Server with T-SQL: https://rebrand.ly/querying-microsoft-sql-server
98-364: Database Fundamentals (Microsoft SQL Server): https://rebrand.ly/database-fundamentals
70-462 SQL Server Database Administration (DBA): https://rebrand.ly/sql-server-dba
Microsoft SQL Server Reporting Services (SSRS): https://rebrand.ly/sql-server-ssrs
SQL Server Integration Services (SSIS): https://rebrand.ly/sql-server-ssis
SQL Server Analysis Services (SSAS): https://rebrand.ly/sql-server-ssas-mdx
Microsoft Power Pivot (Excel) and SSAS (Tabular DAX model): https://rebrand.ly/microsoft-powerpivot-ssas-tabular-dax
—-
Do you want the equivalent of the Excel function IF in SQL Server?
You could use IIF. This allows you to enter a condition, a value if true, and a value if false.
Are you wanting more than two outcomes? Rather than using nested IIF, you could use the CASE expression.
If you are testing a value, then you can say CASE and the name of your column, then WHEN and the name of the single value you are testing for, THEN and the result.
You can have as many WHEN THEN as you wish.
At the end you can optionally have an ELSE and a result to be shown if none of the WHENs are true.
At the end, please add an END and maybe an alias.
Do you want to test for a condition? Instead of CASE field WHEN, you can use CASE WHEN condition.
This time, you have to specify the field multiple times, but you can use different conditions
Again, you can add an END and maybe an alias.
For more tips, please subscribe.
I’m Phillip Burton of I Do Data.com.