From IF-ELSE to CASE Statement: Implementing Conditional Logic in SQL

Surely as an SQL developer, you found yourself one day in the situation where you want to implement an IF-ELSE statement when working with SQL and database tables. In this brief article we will explore the CASE statement which is equivalent to an IF-ELSE statement

The CASE statement checks each time conditions and returns a value when the condition is satisfied. It returns simply the specified value after the THEN clause.

The CASE statement returns NULL if there isn't an ELSE clause and none of the conditions are true.

In the example below, we will see how to implement the CASE statement inside a standard SELECT statement.

Person Experience
Max 7
Paul 2

SELECT  Person , Experience ,
CASE
    WHEN Experience > 5 THEN 'Senior Engineer'

    ELSE 'Junior Engineer'
END AS Jobtitle /* new column name near the Person and Experience column */

FROM Employee_Table;

Person Experience Jobtitle
Max 7 Senior Engineer
Paul 2 Junior Engineer