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:
ProductID | ProductName | Obsolete | InStock |
---|---|---|---|
1 | Product A | N | Y |
2 | Product B | Y | N |
3 | Product C | N | N |
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:
Saleable | ProductID | ProductName | Obsolete | InStock |
---|---|---|---|---|
1 | 1 | Product A | N | Y |
0 | 2 | Product B | Y | N |
0 | 3 | Product C | N | N |
This example demonstrates how to use the CASE
expression to perform conditional logic within a SELECT
statement in SQL.
Comments
Post a Comment