Home >Database >Mysql Tutorial >How Can I Use an IF Statement to Conditionally Select Values in a SQL SELECT Statement?
Use 'IF' in SELECT statement for conditional value selection
In the following SELECT statement, we want to retrieve the amount column from the report table:
<code class="language-sql">SELECT id, amount FROM report</code>
However, we need to modify the output based on conditions. If the value of the type column is 'P', we want the amount column to remain unchanged. If the value of the type column is 'N', we want to invert the amount column.
To achieve this, we can use the IF() function in the SELECT statement. The IF() function allows us to specify a logical condition and return different values depending on whether the condition is true or false.
The query modified using the IF() function is:
<code class="language-sql">SELECT id, IF(type = 'P', amount, amount * -1) as amount FROM report</code>
Breakdown of query:
This modified query will generate a modified amount column based on the conditions, providing the desired output.
The above is the detailed content of How Can I Use an IF Statement to Conditionally Select Values in a SQL SELECT Statement?. For more information, please follow other related articles on the PHP Chinese website!