Home > Database > Mysql Tutorial > How Can I Implement IF-THEN Logic in SQL SELECT Statements?

How Can I Implement IF-THEN Logic in SQL SELECT Statements?

Barbara Streisand
Release: 2025-01-22 15:27:09
Original
438 people have browsed it

How Can I Implement IF-THEN Logic in SQL SELECT Statements?

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

Other instructions

  • CASE statements can be nested to handle more complex conditions.
  • The CAST operator can be used to convert the result to a specific data type, such as Boolean.
  • Nested CASE statements and IIF statements can be included in aggregate functions.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template