bugl
bugl
HomeLearnPatternsPathsSearch
HomeLearnPatternsPathsSearch

Loading lesson path

Learn/SQL/SQL Tutorial
SQL•SQL Tutorial

SQL CASE Expression

Flash cards

Review the key moves

1/4
Core idea

What is the main idea behind SQL CASE Expression?

Lesson checks

Practice each idea before moving on

Short Mimo-style checks built from this lesson's code, terms, and sequence.

1Quick choice

Which statement best captures the main point of this lesson?

2Fill blank

Complete the missing token from the example code.

___
3Order

Put the learning moves in the order that makes the concept easiest to apply.

The CASE expression goes through the conditions and stops at the first match (like an if-then-else statement).
The CASE expression is used to define different results based on specified conditions in an SQL statement.
The SQL CASE Expression

The SQL CASE Expression

The CASE expression is used to define different results based on specified conditions in an SQL statement.

The CASE expression goes through the conditions and stops at the first match (like an if-then-else statement). So, once a condition is true, it will stop processing and return the result. If no conditions are true, it returns the value in the ELSE clause. If there is no ELSE clause and no conditions are true, it returns NULL.

CASE Syntax

CASE WHEN
condition1
 THEN
result1
 WHEN
condition2
 THEN
result2
 WHEN
conditionN
 THEN
resultN
 ELSE
default_result
END;

SQL CASE Example

Here we use the CASE expression to categorize data (Price) and we create a new column (PriceCategory) that shows in which price category each product is:

Example

SELECT ProductName, Price,

CASE

  WHEN Price < 20 THEN 'Low Cost'

  WHEN Price BETWEEN 20 AND 50 THEN 'Medium Cost'

  ELSE 'High Cost'

END AS PriceCategory

FROM Products;

Previous

SQL INSERT INTO SELECT Statement

Next

SQL NULL Functions