W3. SQL Case Flashcards

1
Q

Q: What does the SQL CASE expression do?

A

A: It goes through conditions and returns a value when the first condition is met, similar to an if-then-else statement.

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

Q: What happens if no conditions in a CASE expression are true and there is no ELSE?

A

A: It returns NULL.

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

Q: Write the syntax for a CASE expression.

A

CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2

ELSE result
END;

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

Q: Write a query to categorize Quantity as “greater than 30,” “equal to 30,” or “under 30” using CASE.

A

SELECT OrderID, Quantity,
CASE
WHEN Quantity > 30 THEN ‘The quantity is greater than 30’
WHEN Quantity = 30 THEN ‘The quantity is 30’
ELSE ‘The quantity is under 30’
END AS QuantityText
FROM OrderDetails;

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

Q: How can CASE be used in an ORDER BY clause?

A

A: CASE can be used to define the order based on conditions, such as ordering by a different column if a value is NULL.

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

Q: Write a query to order customers by City, but if City is NULL, then order by Country.

A

SELECT CustomerName, City, Country
FROM Customers
ORDER BY
(CASE
WHEN City IS NULL THEN Country
ELSE City
END);

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