You will learn how to use the IF() function to return a value if a condition is true or false.
Overview
This function returns the specified value if the condition is TRUE and another value if the condition is FALSE. The syntax of the IF()function is shown below:
Syntax
|
IF(expression, true_result, else_result)
⚠️ The expression must be a Boolean expression.
Examples
#Case 1: IF() with a table
In this example, we have the test_result table. We want to know which participants passed and which failed from the table below:
+---------------+--------------------+--------+| applicant_id | name | score |+---------------+--------------------+--------+|78765| Mike Aoki |677||78786| Julie Grahams |650||78986| Alexandra Jones |450||79742| Lucas Moore |487||79769| Augustine Harkness |572|+---------------+--------------------+--------+
1) IF function in the query below states that IF the score is equal to or greater than 500, then return “PASSED“. Otherwise, if the score is smaller than 500, return “NOT PASSED”.
+--------------------+-------------+| name |case|+--------------------+-------------+| Mike Aoki | PASSED || Julie Grahams | PASSED || Alexandra Jones |NOT PASSED || Lucas Moore |NOT PASSED || Augustine Harkness | PASSED |+--------------------+-------------+
#Case 2: IF() with expressions as return value
In the second example, we have another table named “deptcost”. We want to know which department exceeded the budget and which one did not from the following table.