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.
[code language=”sql”]
SELECT pid, CASE p_status
WHEN 1 THEN ‘pending’
WHEN 2 THEN ‘running’
WHEN 3 THEN ‘done’
FROM processes;
[/code]
You can also set a default value when the value is not 1, 2, or 3.
[code language=”sql”]
SELECT pid, CASE p_status
WHEN 1 THEN ‘pending’
WHEN 2 THEN ‘running’
WHEN 3 THEN ‘done’
ELSE ‘Unknown’
FROM processes;
[/code]
Search within Codexpedia
Search the entire web