Must CASE statements always be indented?
Explanation
CASE statement doesn't have to be indented.
The CASE statement goes through conditions and returns a value when the first condition is met (like an IF-THEN-ELSE statement). So, once a condition is true, it will stop reading and return the result. If no conditions are true, it returns the value in the ELSE clause.
Theory
  • SQL - CASE Function

    The CASE statement selects one sequence of statements to execute. However, to select the sequence, the CASE statement uses a selector rather than multiple Boolean expressions.

    Syntax for MySQL

    CASE [ selector ]
       WHEN condition_1 THEN result_1
       ...
       WHEN condition_n THEN result_n
       ELSE result
    END
    
    Parameters or Arguments: selector - an optional expression, whose value is used to select one of several alternatives. condition_1, ... condition_n - Evaluated in the order listed. Once a condition is found to be true, the CASE function will return the result and not evaluate the conditions any further. result_1, ... result_n - The value returned once a condition is found to be true.

    NOTE

    If no condition is found to be true, then the CASE function will return the value in the ELSE clause, and if the ELSE clause is also omitted, then the CASE statement will return NULL.
  • EXAMPLE - INCLUDES EXPRESSION

    You could use the CASE function in a SQL statement where the expression is included.
    SELECT supplier_id,
    CASE quantity
      WHEN > 10 THEN 'The quantity is greater than 10'
      WHEN = 10 THEN 'The quantity is 10'
      ELSE 'The quantity is something else'
    END
    FROM suppliers;
    
    In this CASE function example, the expression is quantity whose value would be compared to each of the conditions until one is met. Then the corresponding value would be returned by the CASE function.
    Read more: MYSQL: CASE FUNCTION
  • EXAMPLE - EXCLUDES EXPRESSION

    You could use the CASE function in a SQL statement where the expression is omitted.
    SELECT
    CASE
      WHEN a < b THEN 1
      WHEN supplier_type = 'clothing' THEN 2
      ELSE 3
    END
    FROM suppliers;
    
    In this CASE function example, an expression has not been included so each condition is individually evaluated and can be completely different and unique. When a condition is met, the corresponding value would be returned.
    Read more: MYSQL: CASE FUNCTION

Следи за CodeGalaxy

Мобильное приложение Beta

Get it on Google Play
Обратная Связь
Продолжайте изучать
тесты по SQL
Cosmo
Зарегистрируйся сейчас
или Подпишись на будущие тесты