Monday, 16 July 2018

Switch Case Conditional Statement with MySQL

Switch Case Conditional Statement with MySQL

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:

  1. SELECT  
  2.     CASE `field`  
  3.         WHEN 'value1' THEN 'output_value1'  
  4.         WHEN 'value2' THEN 'output_value2'  
  5.         WHEN 'value3' THEN 'output_value3'  
  6.     END AS fieldAlias  
  7. FROM  
  8.     `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:

  1. SELECT  
  2.     CASE `userActive`  
  3.         WHEN '1' THEN 'Active'  
  4.         WHEN '2' THEN 'Pending'  
  5.         WHEN '3' THEN 'Deleted'  
  6.     END AS userActive  
  7. FROM  
  8.     `user` 

0 comments:

Post a Comment