Explore Courses Blog Tutorials Interview Questions
+2 votes
1 view
in SQL by (20.3k points)

How do I perform an IF...THEN in an SQL SELECT statement?

For example:

SELECT IF(Obsolete = 'N' OR InStock = 'Y' ? 1 : 0) AS Saleable, * FROM Product

1 Answer

+2 votes
by (40.4k points)
edited by

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.

Related questions

+1 vote
1 answer
0 votes
1 answer
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers


94k users

Browse Categories