Using CASE Expression in PostgreSQL
📖 Scenario: You work at a bookstore that wants to categorize books by their price range to help customers quickly find affordable or premium books.
🎯 Goal: Create a PostgreSQL query that uses the CASE expression to classify books into price categories: 'Cheap', 'Moderate', and 'Expensive'.
📋 What You'll Learn
Create a table called
books with columns id (integer), title (text), and price (numeric).Insert exactly these three books with their prices: 'Book A' priced 10, 'Book B' priced 25, and 'Book C' priced 50.
Write a SELECT query that uses a
CASE expression to add a column price_category with values 'Cheap' if price < 15, 'Moderate' if price between 15 and 30, and 'Expensive' if price > 30.Order the results by
id ascending.💡 Why This Matters
🌍 Real World
Classifying products or items into categories based on numeric values is common in sales, inventory, and reporting systems.
💼 Career
Understanding CASE expressions helps in writing flexible SQL queries for data analysis and reporting tasks in many database-related jobs.
Progress0 / 4 steps