What is IF() in SQL?
The IF() function is a conditional statement. This function returns a value given as a parameter if the condition is true; otherwise, it returns another value given as a parameter.
Figure 1 shows a visual representation of the IF() function.
Syntax
IF(condition, valueIfTrue, valueIfFalse)
Parameter
The IF() function takes three parameters:
- Condition or expression one needs to validate.
- Value if the expression is true. This can be
stringornumber. - Value if the expression is false. This can be
stringornumber.
Return value
The IF() function returns a specified value if the condition is true; otherwise, it returns a different specified value.
Example
-- true value and output stringSELECT IF(2>1,'First value > Second Value', 'First value < Second Value');-- False value and output stringSELECT IF(1>2,'First value > Second Value', 'First value < Second Value');-- true value and output number 1:true 0:falseSELECT IF(2>1,1,0);-- False value and output number 1:true 0:falseSELECT IF(2<1,1,0);