3 Use Cases for SQL Case When Statement | by Soner Yıldırım | Jul, 2023


1. Use Case When to Derive New Columns

The CASE WHEN (or CASE) statement allows for evaluating conditions whose results can be used to create new columns.

(image by author)

For instance, we can create a new column price_group with values low, medium, high based on product prices. It can be considered as creating product price groups.

SELECT
product_description,
price,
CASE
WHEN price > 20 THEN 'high'
WHEN price <= 20 AND price > 10 THEN 'medium'
WHEN price <= 10 THEN 'low'
END AS price_group
FROM product_inventory
The first 10 rows of the output of the query above (image by author)

The CASE WHEN statement creates the product_column based on the following criteria:

  • If the price is higher than 20, the value is “high”.
  • If the price is between 10 and 20, the value is “medium”.
  • If the price is less than 10, the value is “low”.

We can also write this query as follows:

SELECT
product_description,
price,
CASE
WHEN price > 20 THEN 'high'
WHEN…



Source link

Leave a Comment