tags:

views:

50

answers:

4

Is it possible to have a SELECT statement in mySQL with an IF/ELSE clause in it?

E.g.

I want to SELECT all table rows and return color2 ONLY if color2 is 'brown'. My example SQL select statement of what I would like to accomplish is below.

APPLES
+------+--------+----------+----------+  
|  ID  |  NAME  |  COLOR1  |  COLOR2  |  
+------+--------+----------+----------+  
|  1   | apple1 |    red   |   brown  |
+------+--------+----------+----------+  
|  2   | apple2 |    red   |   green  |
+------+--------+----------+----------+  

SELECT name, (IF color2 = 'brown' SELECT color2 ELSE SELECT color1) AS color FROM apples

would return:

+----------+----------+
|  apple1  |   brown  |
+----------+----------+
|  apple2  |    red   |
+----------+----------+
+2  A: 

The Control Flow Function documentation should help you.

David Brown
+3  A: 

Check out the CASE statement in the MySQL Reference Manual.

Sixten Otto
+5  A: 

MySQL has an IF() function:

SELECT name, IF(color2='brown', color2, color1) AS color FROM apples
ChssPly76
Thanks ChssPly76. I have a follow up question here. I'm trying to use that new table column (colour) to join another table but the join is giving me this error: Unknown column 'color' in 'on clause'. Any ideas?
justinl
i posted the follow up here: http://stackoverflow.com/questions/1642147/how-can-i-use-a-mysql-select-if-statement-row-to-join-another-table. someone has answered it already. thanks!
justinl
+3  A: 

Use:

SELECT a.name, 
       CASE WHEN a.color2 = 'brown' THEN a.color2 ELSE a.color1 END AS color 
  FROM apples a

Reference: CASE

The CASE statement allows for IF/ELSE or SWITCH-like functionality, and has the benefit of being ANSI standard. That query would work on SQL Server, Oracle, MySQL...

OMG Ponies
Thanks Rexem. I have a follow up question here just like with ChssPly76. I'm trying to use that new table column (colour) to join another table but the join is giving me this error: Unknown column 'color' in 'on clause'. Any ideas?
justinl
i posted the follow up here: http://stackoverflow.com/questions/1642147/how-can-i-use-a-mysql-select-if-statement-row-to-join-another-table. someone has answered it already. thanks!
justinl