What is the purpose of ‘when’ in MySQL?

In MySQL, “WHEN” is a keyword used in conditional statements to define the condition expression.

“WHEN” is typically used in the following situations:

  1. In a “CASE” statement, the condition expression used to define each “WHEN” clause. The “CASE” statement selects a different path of execution based on the result of the condition expression.

For example:

SELECT 
    column_name,
    CASE 
        WHEN condition1 THEN result1
        WHEN condition2 THEN result2
        ELSE result3
    END
FROM 
    table_name;
  1. In “TRIGGER,” conditions are defined for triggers. Triggers are a special type of stored procedure that automatically fires when data is inserted, updated, or deleted in a table.

For example:

CREATE TRIGGER trigger_name
BEFORE/AFTER INSERT/UPDATE/DELETE
ON table_name
FOR EACH ROW
WHEN condition
BEGIN
    -- 触发器的操作
END;

In conclusion, the key role of the “WHEN” keyword is to assist MySQL in determining conditions and executing corresponding actions based on those conditions.

bannerAds