Follow the below steps to perform IF and THEN in the SQL statement.
Want to learn SQL from basics! Here's the right video for you on SQL provided by Intellipaat:
For Simple case you can use this code:
SELECT CASE <variable1> WHEN <value1> THEN <returnvalue1>
WHEN <othervalue1> THEN <returnthis>
ELSE <returndefaultcase>
END AS <newcolumnname1>
FROM <table>
For extended case you can use this:
SELECT CASE WHEN <test1> THEN <returnvalue1>
WHEN <othertest1> THEN <returnthis>
ELSE <returndefaultcase>
END AS <newcolumnname1>
FROM <table>
CASE statement: It goes through conditions and returns a value when the first condition is met (like an IF-THEN-ELSE statement). Therefore, if a condition is true, it will stop reading and return the result. If none of the conditions are met, then it returns the value in the ELSE clause.
Refer to this video to get a clear picture of CASE STATEMENT in SQL.
Case Statement returns NULL, if there is no ELSE part and no conditions are true.
You can even use case statements in an ORDER BY clause for better ordering.
You can even use Case Statement in an order by clause for better ordering.