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:

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

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

	CASE `userActive`
		WHEN '1' THEN 'Active'
		WHEN '2' THEN 'Pending'
		WHEN '3' THEN 'Deleted'
	END AS userActive
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.

Fear not, we won't publish this

Comments (7)
  1. Nice piece of code, you saved me lot of time.

  2. bhavesh says:

    Nice expiation

  3. 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

  4. lucs says:

    Thanks dude. Very usefull

  5. Alejandro Becerra says:

    It was very useful, thank you!


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

  7. David Dingvean says:

    Fab! just what i needed! :D