IF
IF is a conditional statement in SQL that allows you to perform different actions based on whether a certain condition is true or false. It checks the condition first; if it evaluates to true, a certain statement or block of statements gets executed. If the condition evaluates to false, another set of statements are executed. This makes the control flow of SQL statements more flexible and dynamic.
Example
Output
Explanation
In this example, the IF
statement in SQL is used to compare a variable (@input
) to a specific value. The IF
statement checks if the value of @input
is greater than 3. If the condition is true, it returns ‘Greater’. If the condition is false, it returns ‘Smaller’. The returned value is displayed as ‘Result’. In this case, since the value of @input
is 5 which is indeed greater than 3, the output is ‘Greater’.
Example
Output
Explanation
In this example, an integer variable @Value
is declared and set to 10. A conditional IF
statement checks if the value is greater than 5. If the condition is true, it outputs Value is greater than 5
. If it’s false, it would have output Value is equal to or less than 5
. Since @Value
was set to 10, the true condition was met resulting in the displayed output.
Example
Output
Explanation
In this example, a variable EMP_SALARY
is declared and assigned a value of 5500. The IF
statement checks whether the salary is greater than 8000. If the salary is above 8000, the string ‘High salary’ is output. Otherwise, ‘Low salary’ is output. As the set value of 5500 is less than 8000, the output is ‘Low salary’.