Switch Case Conditional Statement with MySQL

July 17th, 2011 - Posted by Steve Marks to MySQL, Web Development.

When selecting fields in a MySQL statement you can perform certain conditional statements to get the values you require based on other values. One of these is the Switch Case conditional statement. If you’re familiar with other programming languages you probably know how to do this already but allow me to demonstrate how this can be done within a MySQL query:

SELECT
	CASE `field`
		WHEN 'value1' THEN 'output_value1'
		WHEN 'value2' THEN 'output_value2'
		WHEN 'value3' THEN 'output_value3'
	END AS fieldAlias
FROM
	`table`

Heres an another example using the Switch Case conditional statement that will output a users active state based on a number in the database:

SELECT
	CASE `userActive`
		WHEN '1' THEN 'Active'
		WHEN '2' THEN 'Pending'
		WHEN '3' THEN 'Deleted'
	END AS userActive
FROM
	`user`
Tags:
This entry was posted on Sunday, July 17th, 2011 at 7:55 pm by +Steve Marks and is filed under MySQL, Web Development. You can follow any responses to this entry through the RSS 2.0 feed.
Comments...

Fear not, we won't publish this

Comments (6)
  1. bhavesh says:

    Nice expiation

  2. GFS says:

    very clear example thank you , i was looking for a solution in my search.php page and instead of many if statements this just saved my life

  3. lucs says:

    Thanks dude. Very usefull

  4. Alejandro Becerra says:

    It was very useful, thank you!

    Grettings!

  5. wowwwwww, that is so perfect, you saved me about 200 lines of code in my website search field…thank you

  6. David Dingvean says:

    Fab! just what i needed! :D