Implement IF-THEN logic in SQL SELECT statement
A common need in SQL programming is to perform condition checks and return different results based on the results. This article will explore how to implement IF...THEN logic in a SQL SELECT statement.
Use CASE statement
The CASE statement is equivalent to the IF statement in SQL. It allows you to specify multiple conditions and corresponding actions.
<code class="language-sql">SELECT CASE WHEN condition1 THEN result1 WHEN condition2 THEN result2 ELSE result3 END AS conditional_column, * FROM table_name</code>
For example, to check if a product is salable based on its Obsolete and InStock values:
<code class="language-sql">SELECT CAST( CASE WHEN Obsolete = 'N' OR InStock = 'Y' THEN 1 ELSE 0 END AS bit) AS Saleable, * FROM Product</code>
Use IIF statement (SQL Server 2012 and above)
The IIF statement introduced in SQL Server 2012 simplifies the syntax of conditional statements. Its format is as follows:
<code class="language-sql">SELECT IIF(condition, result_if_true, result_if_false) AS conditional_column, * FROM table_name</code>
The above example can be rewritten using the IIF statement as:
<code class="language-sql">SELECT IIF(Obsolete = 'N' OR InStock = 'Y', 1, 0) AS Saleable, * FROM Product</code>
Other instructions
The above is the detailed content of How Can I Implement IF-THEN Logic in SQL SELECT Statements?. For more information, please follow other related articles on the PHP Chinese website!