Skip to content
Advertisement

How do I perform an IF…THEN in an SQL SELECT?

How do I perform an IF...THEN in an SQL SELECT statement?

For example:

Advertisement

Answer

The CASE statement is the closest to IF in SQL and is supported on all versions of SQL Server.

You only need to use the CAST operator if you want the result as a Boolean value. If you are happy with an int, this works:

CASE statements can be embedded in other CASE statements and even included in aggregates.

SQL Server Denali (SQL Server 2012) adds the IIF statement which is also available in access (pointed out by Martin Smith):

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement