Purpose
With the help of the CASE function, an IF THEN ELSE logic can be expressed within the SQL language.
Syntax
case::=
                                                                         
                                                                    
simple_case_expr::=
                                                                     
                                                                
searched_case_expr::=
                                                                     
                                                                
Usage Notes
- With the simple_case_expr, theexpris compared with the specified alternatives. TheTHENpart of the first match defines the result.
- With the searched_case_expr, the row is evaluated using all of the conditions until one equates to theTRUEvalue. TheTHENpart of this condition is the result.
- If none of the options apply, the ELSEvalue is returned. If this was not specified, theNULLvalue is returned.
Examples
SELECT name, CASE grade WHEN 1 THEN 'VERY GOOD'
                        WHEN 2 THEN 'GOOD'
                        WHEN 3 THEN 'SATISFACTORY'
                        WHEN 4 THEN 'FAIR' 
                        WHEN 5 THEN 'UNSATISFACTORY'
                        WHEN 6 THEN 'POOR'
                        ELSE 'INVALID'
                        END AS GRADE FROM student;Result
| NAME | GRADE | 
| Fischer | VERY GOOD | 
| Schmidt | FAIR | 
SELECT name, CASE WHEN turnover>1000 THEN 'PREMIUM'
                                     ELSE 'STANDARD'
                                     END AS CLASS FROM customer;Result
| NAME | CLASS | 
| Meier | STANDARD | 
| Huber | PREMIUM |