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

 

In SQL, you can use the CASE expression to perform conditional logic within a SELECT statement. The CASE expression allows you to evaluate conditions and return different values based on those conditions. Here's how you can use it to achieve your example:

Suppose you have a table named Product with columns Obsolete and InStock, and you want to create a new column named Saleable that is 1 if either Obsolete is 'N' or InStock is 'Y', and 0 otherwise. You can use the CASE expression as follows:

sql
SELECT CASE WHEN Obsolete = 'N' OR InStock = 'Y' THEN 1 ELSE 0 END AS Saleable, * FROM Product;

In this example, the CASE expression is used within the SELECT statement to evaluate the conditions specified by Obsolete = 'N' OR InStock = 'Y'. If the condition is true, the expression returns 1; otherwise, it returns 0. The resulting value is aliased as Saleable.

The * in the SELECT statement retrieves all columns from the Product table.

Here's a more concrete example:

Suppose you have the following Product table:

ProductIDProductNameObsoleteInStock
1Product ANY
2Product BYN
3Product CNN

You can use the CASE expression to create the Saleable column:

sql
SELECT CASE WHEN Obsolete = 'N' OR InStock = 'Y' THEN 1 ELSE 0 END AS Saleable, * FROM Product;

The result will be:

SaleableProductIDProductNameObsoleteInStock
11Product ANY
02Product BYN
03Product CNN

This example demonstrates how to use the CASE expression to perform conditional logic within a SELECT statement in SQL.

Comments