CASE Statements Flashcards
How does a CASE statement work?
A CASE statement evaluates a list of conditions and
returns the first condition that resolves to true. The statement can contain one or more WHEN conditions. WHEN…THEN condition is similar to an IF…THEN condition. If no condition resolves to true then the ELSE condition resolves. If there is no ELSE condition, then the
statement returns NULL.
What are the two CASE statement expressions?
Simple CASE expression
Searched CASE expression
What’s the simple CASE Syntax
You start with the keyword CASE and then mention the column or expression you want to evaluate.
CASE expression
WHEN value1 THEN result1
WHEN value2 THEN result2
…
WHEN valueN THEN resultN
ELSE default_result
END
SELECT
employee_id,
salary,
CASE department_id
WHEN 1 THEN ‘Sales’
WHEN 2 THEN ‘Engineering’
WHEN 3 THEN ‘HR’
ELSE ‘Other’
END AS department_name
FROM employees;
What’s a caveat with a simple case statement?
No operators. Instead, its only equality comparisons to avoid complexity.
What keyword must you terminate your CASE statement with?
END
Where do you place the ELSE statement and what does it do?
The ELSE keyword resolves when none of the WHEN THEN
clauses resolve to true
ELSE is inserted after all the WHEN THEN clauses
How is a SIMPLE CASE STATEMENT different than a SEARCH CASE STATEMENT?
A Simple CASE statement evaluates a single expression against a set of fixed values.
Each WHEN clause in a Searched CASE statement is independent and can use any column, constant, or function. This independence allows for more complex and varied conditions.
What’s another way to create complex conditional logic using CASE statements?
You can NEST them?
How many statements can you nest at a time?
10