Formation incluse

Case Statements for Conditional Logic in SQL

Nogho Belviane
9 Membres de l'équipe 2024 · 7,35 min lecture
0
Data Science and AI
Case Statements for Conditional Logic in SQL

SQL's CASE statement is a powerful tool for adding conditional logic directly into your queries. It allows you to define conditions and output specific results based on those conditions, making your queries more dynamic and insightful. This article will explore how CASE works, its syntax, use cases, and examples using our familiar dataset.

What is a CASE Statement?

A CASE statement is a conditional expression that evaluates conditions sequentially and returns a specified result when the first true condition is encountered. It's akin to an "if-else" structure in programming.

General Syntax:

sql code

CASE

WHEN condition1 THEN result1

WHEN condition2 THEN result2 ...

ELSE default_result END

Dataset

Customers Table:

CustomerID CustomerName Country
1 Alice USA
2 Bob Canada
3 Charlie UK

Orders Table:

OrderID CustomerID OrderAmount
101 1 250
102 2 450
103 4 300

1. Using CASE for Conditional Output

Example: Categorize Order Amounts

We want to categorize orders into "Low", "Medium", and "High" based on their amounts.

sql code

SELECT OrderID, OrderAmount,

CASE

WHEN OrderAmount < 300 THEN 'Low'

WHEN OrderAmount BETWEEN 300 AND 400 THEN 'Medium' ELSE 'High'

END AS OrderCategory

FROM orders;

Output:

OrderID OrderAmount OrderCategory
101 250 Low
102 450 High
103 300 Medium

Explanation:

  • Each OrderAmount is checked against conditions sequentially.
  • The first true condition returns the corresponding category.
  • The ELSE clause captures all other cases not explicitly defined.

2. Using CASE for Customizing Columns

Example: Add a Customer Region

We can add a column that indicates whether a customer is from North America or Other based on the Country.

sql code

SELECT CustomerName, Country,

CASE

WHEN Country IN ('USA', 'Canada') THEN 'North America'

ELSE 'Other' END AS Region

FROM customerss;

Output:

CustomerName Country Region
Alice USA North America
Bob Canada North America
Charlie UK Other

Explanation:

  • The CASE checks whether Country belongs to a predefined list.
  • Customers in the USA or Canada are tagged as North America.

3. Using CASE in Aggregations

Example: Total Orders by Category

We can use CASE to group order amounts into categories during aggregation.

sql code

SELECT

CASE

WHEN OrderAmount < 300 THEN 'Low'

WHEN OrderAmount BETWEEN 300 AND 400 THEN 'Medium'

ELSE 'High'

END AS OrderCategory, COUNT(*) AS TotalOrders

FROM orders

GROUP BY

CASE WHEN OrderAmount < 300 THEN 'Low'

WHEN OrderAmount BETWEEN 300 AND 400 THEN 'Medium' ELSE 'High' END;

Output:

OrderCategory TotalOrders
Low 1
Medium 1
High 1

Explanation:

  • The CASE statement is used both in the SELECT and GROUP BY clauses to classify and aggregate data simultaneously.

4. Using CASE with Joins

Example: Display Customer and Order Status

Combine customers and orders, adding a status to indicate whether a customer has placed an order.

sql code

SELECT c.CustomerName, o.OrderID,

CASE

 WHEN o.OrderID IS NULL THEN 'No Orders'

ELSE 'Has Orders'

END AS OrderStatus

FROM customerss c

LEFT JOIN orders o ON c.CustomerID = o.CustomerID;

Output:

CustomerName OrderID OrderStatus
Alice 101 Has Orders
Bob 102 Has Orders
Charlie NULL No Orders

Explanation:

  • A LEFT JOIN includes all customers.
  • The CASE identifies whether the customer has associated orders.

Strategies to Master CASE Statements

  1. Understand Condition Priority: Conditions are evaluated sequentially. Define more specific conditions first to avoid unexpected results.
  2. Test with Simple Queries: Start with basic queries to ensure your conditions are correctly evaluated.
  3. Use ELSE Wisely: Always include an ELSE clause to handle unexpected or default cases.
  4. Leverage in Aggregations: Combine CASE with aggregate functions like SUM or COUNT for powerful insights.
  5. Practice: Regular use in real-world scenarios will help solidify your understanding.

Conclusion

The CASE statement is an invaluable tool for conditional logic in SQL, enabling you to dynamically classify, customize, and analyze data. Whether you're categorizing records, creating custom columns, or enhancing aggregated results, mastering CASE will significantly enhance your SQL skills.

0

Applaudissez pour montrer votre soutien

Nogho Belviane

1 Suivez-nous · Rédacteur pour Data Science and AI