SQL WHEN Clause: A Complete Guide
In SQL, WHEN is part of the CASE expression and is used to specify the condition for each CASE clause. Following WHEN must be a condition expression that indicates when the clause should be executed.
WHEN clauses are usually used together with CASE structures to perform different operations based on various conditions. Here is how to use WHEN:
- WHAT TIME
SELECT column1,
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
...
ELSE result
END AS result_column
FROM table_name;
In the example above, different operations are executed and corresponding result columns are returned based on different conditions (condition1, condition2, etc).
- WHENEVER
SELECT column1,
CASE
WHEN condition1 AND condition2 THEN result1
WHEN condition3 OR condition4 THEN result2
...
ELSE result
END AS result_column
FROM table_name;
In the example above, multiple conditions can be combined using logical operators (such as AND, OR) to execute corresponding operations based on complex conditions.
It is important to note that the order of the WHEN clauses is crucial, as the CASE expression will check each WHEN clause from top to bottom and execute the first one that meets the condition. If no conditions are true, the operation in the ELSE clause will be executed.