What is IF() in SQL?

Share

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.

Figure 1: Visual representation of 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 string or number.
  • Value if the expression is false. This can be string or number.

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 string
SELECT IF(2>1,'First value > Second Value', 'First value < Second Value');
-- False value and output string
SELECT IF(1>2,'First value > Second Value', 'First value < Second Value');
-- true value and output number 1:true 0:false
SELECT IF(2>1,1,0);
-- False value and output number 1:true 0:false
SELECT IF(2<1,1,0);