CASE Clause

Description

CASE clause uses a rule to return a specific result based on the specified condition, similar to if/else statements in other programming languages.

Syntax

  1. CASE [ expression ] { WHEN boolean_expression THEN then_expression } [ ... ]
  2. [ ELSE else_expression ]
  3. END

Parameters

  • boolean_expression

    Specifies any expression that evaluates to a result type boolean. Two or more expressions may be combined together using the logical operators ( AND, OR ).

  • then_expression

    Specifies the then expression based on the boolean_expression condition; then_expression and else_expression should all be same type or coercible to a common type.

  • else_expression

    Specifies the default expression; then_expression and else_expression should all be same type or coercible to a common type.

Examples

  1. CREATE TABLE person (id INT, name STRING, age INT);
  2. INSERT INTO person VALUES
  3. (100, 'John', 30),
  4. (200, 'Mary', NULL),
  5. (300, 'Mike', 80),
  6. (400, 'Dan', 50);
  7. SELECT id, CASE WHEN id > 200 THEN 'bigger' ELSE 'small' END FROM person;
  8. +------+--------------------------------------------------+
  9. | id | CASE WHEN (id > 200) THEN bigger ELSE small END |
  10. +------+--------------------------------------------------+
  11. | 100 | small |
  12. | 200 | small |
  13. | 300 | bigger |
  14. | 400 | bigger |
  15. +------+--------------------------------------------------+
  16. SELECT id, CASE id WHEN 100 then 'bigger' WHEN id > 300 THEN '300' ELSE 'small' END FROM person;
  17. +------+-----------------------------------------------------------------------------------------------+
  18. | id | CASE WHEN (id = 100) THEN bigger WHEN (id = CAST((id > 300) AS INT)) THEN 300 ELSE small END |
  19. +------+-----------------------------------------------------------------------------------------------+
  20. | 100 | bigger |
  21. | 200 | small |
  22. | 300 | small |
  23. | 400 | small |
  24. +------+-----------------------------------------------------------------------------------------------+
  25. SELECT * FROM person
  26. WHERE
  27. CASE 1 = 1
  28. WHEN 100 THEN 'big'
  29. WHEN 200 THEN 'bigger'
  30. WHEN 300 THEN 'biggest'
  31. ELSE 'small'
  32. END = 'small';
  33. +------+-------+-------+
  34. | id | name | age |
  35. +------+-------+-------+
  36. | 100 | John | 30 |
  37. | 200 | Mary | NULL |
  38. | 300 | Mike | 80 |
  39. | 400 | Dan | 50 |
  40. +------+-------+-------+