IF
Example
Section titled “Example”SET @input = 5;SELECT IF(@input>3, 'Greater', 'Smaller') AS Result;Output
Section titled “Output”+---------+| Result |+---------+| Greater |+---------+Explanation
Section titled “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
Section titled “Example”DECLARE @Value INT;SET @Value = 10;
IF (@Value > 5)BEGIN PRINT 'Value is greater than 5';ENDELSEBEGIN PRINT 'Value is equal to or less than 5';ENDOutput
Section titled “Output”Value is greater than 5Explanation
Section titled “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
Section titled “Example”DECLARE EMP_SALARY NUMBER(6) := 5500;BEGIN IF EMP_SALARY > 8000 THEN DBMS_OUTPUT.PUT_LINE('High salary'); ELSE DBMS_OUTPUT.PUT_LINE('Low salary'); END IF;END;/Output
Section titled “Output”Low salaryExplanation
Section titled “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’.