Home > Database > Mysql Tutorial > How Can I Implement Conditional Logic in SQL SELECT Statements using CASE and IIF?

How Can I Implement Conditional Logic in SQL SELECT Statements using CASE and IIF?

DDD
Release: 2025-01-22 15:06:14
Original
325 people have browsed it

How Can I Implement Conditional Logic in SQL SELECT Statements using CASE and IIF?

Mastering Conditional Logic in SQL SELECT Statements: CASE and IIF

Efficiently managing conditional logic within SQL SELECT statements is crucial for data manipulation and filtering. While a direct IF...THEN construct isn't available in standard SQL, the CASE statement and IIF (in SQL Server Denali and later) provide robust alternatives.

The CASE Statement: Your SQL Conditional Workhorse

The CASE statement mirrors the functionality of IF...THEN, evaluating conditions sequentially and returning a value based on the first true condition. Its structure is as follows:

<code class="language-sql">SELECT
  CASE
    WHEN condition1 THEN value1
    WHEN condition2 THEN value2
    ...
    ELSE default_value
  END AS <alias>,  -- Assign an alias to the result
  *
FROM <table_name></code>
Copy after login

Consider this practical application:

<code class="language-sql">SELECT CAST(
  CASE
    WHEN Obsolete = 'N' OR InStock = 'Y' THEN 1
    ELSE 0
  END AS bit) AS Saleable,  -- Casts the result as a BIT (Boolean)
  *
FROM Product</code>
Copy after login

Note the CAST operator. Without it, the result is an integer (0 or 1); with CAST, it's converted to a Boolean (TRUE or FALSE).

IIF: A Concise Conditional Option (SQL Server)

SQL Server introduced the IIF (Immediate If) statement, offering a more compact alternative to CASE:

<code class="language-sql">SELECT IIF(condition, true_value, false_value) AS <alias>,
  *
FROM <table_name></code>
Copy after login

Here's how it applies to our example:

<code class="language-sql">SELECT IIF(Obsolete = 'N' OR InStock = 'Y', 1, 0) AS Saleable,
  *
FROM Product</code>
Copy after login

Both CASE and IIF are indispensable tools for implementing conditional logic in SQL SELECT queries, empowering dynamic data manipulation and efficient filtering.

The above is the detailed content of How Can I Implement Conditional Logic in SQL SELECT Statements using CASE and IIF?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template