CASE Statements Flashcards

1
Q

How does a CASE statement work?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What are the two CASE statement expressions?

A

Simple CASE expression
Searched CASE expression

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What’s the simple CASE Syntax

A

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;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What’s a caveat with a simple case statement?

A

No operators. Instead, its only equality comparisons to avoid complexity.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What keyword must you terminate your CASE statement with?

A

END

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Where do you place the ELSE statement and what does it do?

A

The ELSE keyword resolves when none of the WHEN THEN
clauses resolve to true

ELSE is inserted after all the WHEN THEN clauses

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How is a SIMPLE CASE STATEMENT different than a SEARCH CASE STATEMENT?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What’s another way to create complex conditional logic using CASE statements?

A

You can NEST them?

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How many statements can you nest at a time?

A

10

How well did you know this?
1
Not at all
2
3
4
5
Perfectly