mysql select query with case to switch value
There is switch control flow in mysql just like the switch statements in a programming language. Assume we have a table processes with two columns, pid and p_status. Status have values 1, 2 and 3 representing pending, running, and done respectively. When you do a regular select statements, it will give you the values 1, 2 or 3 for column status. Here is an example of mysql select query uses case to switch the values 1, 2 and 3 to pending, running, and done respectively.
SELECT pid, CASE p_status WHEN 1 THEN 'pending' WHEN 2 THEN 'running' WHEN 3 THEN 'done' FROM processes;
You can also set a default value when the value is not 1, 2, or 3.
SELECT pid, CASE p_status WHEN 1 THEN 'pending' WHEN 2 THEN 'running' WHEN 3 THEN 'done' ELSE 'Unknown' FROM processes;
Search within Codexpedia
Custom Search
Search the entire web
Custom Search
Related Posts