SQL

Implement Conditional Logic with SQL CASE Statement

Learn to apply if-then-else logic within your SQL queries using the CASE statement to categorize data or display custom, computed values.

SELECT
  product_name,
  price,
  CASE
    WHEN price < 50 THEN 'Low Priced'
    WHEN price >= 50 AND price < 200 THEN 'Medium Priced'
    ELSE 'High Priced'
  END AS price_category
FROM
  Products;
How it works: This query employs the `CASE` statement to assign a descriptive text category to each product based on its `price`. It evaluates conditions sequentially: if the `price` is less than 50, it's 'Low Priced'; if it's between 50 and 200 (inclusive of 50), it's 'Medium Priced'; otherwise, it's 'High Priced'. This is extremely useful for generating reports with custom classifications or flags directly within your SQL query without needing application-level logic.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs