Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

SELECT IF(Obsolete = 'N' OR InStock = 'Y' ? 1 : 0) AS Saleable, * FROM Product 
like image 299
Eric Labashosky Avatar asked Sep 15 '08 14:09

Eric Labashosky


People also ask

CAN YOU DO IF THEN statements in SQL?

Any T-SQL statement can be executed conditionally using IF… ELSE. If the condition evaluates to True, then T-SQL statements followed by IF condition in SQL server will be executed. If the condition evaluates to False, then T-SQL statements followed by ELSE keyword will be executed.

Can we use select statement in IF condition?

It is like a Shorthand form of CASE statement. We can conveniently use it when we need to decide between two options. There are three parts in IIF statement, first is a condition, second is a value if the condition is true and the last part is a value if the condition is false.


1 Answers

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

SELECT CAST(              CASE                   WHEN Obsolete = 'N' or InStock = 'Y'                      THEN 1                   ELSE 0              END AS bit) as Saleable, * FROM Product 

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:

SELECT CASE             WHEN Obsolete = 'N' or InStock = 'Y'                THEN 1                ELSE 0        END as Saleable, * FROM Product 

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):

SELECT IIF(Obsolete = 'N' or InStock = 'Y', 1, 0) as Saleable, * FROM Product 
like image 134
Darrel Miller Avatar answered Sep 28 '22 23:09

Darrel Miller