IF Function - SQL


Overview


The IF function in SQL evaluates a condition and returns one value if the condition is true and another value if the condition is false. It is used for conditional logic within queries.

Example:

SELECT IF(vacation_days > 0, 'Some vacation left', 'No vacation left')

Syntax:

SELECT IF(condition, true_result, false_result)

condition is the logical expression to evaluate.

true_result is the value returned if the condition is true.

false_result is the value returned if the condition is false.

Sample Data:

first_name vacation_days
Frank 5
Jane 2
Ashley 3
Glenn -3
Kelly 2
Richard -7
George 2
Kyle 1
James -2
Gustavo -10

Example: Hard-coded value


In this example, we are checking to see if 10 is greater than 5 using the IF function. Since the condition is true, it returns the value ‘This is true’.


Example: Query without the WHERE Statement


In this example, we are returning the vacation_days column for each employee and use the IF function to check if the vacation_days are greater than 0. If the condition is true, it returns ‘Some vacation left’ and if it is false, it returns ‘No vacation’.


Example: Query with the WHERE Statement


In this example, we are returning the vacation_days column for each employee with the department_id of 1 and use the IF function to check if the vacation_days are greater than 0. If the condition is true, it returns ‘Some vacation left’ and if it is false, it returns ‘No vacation’.