Using CASE in PL/pgSQL to Categorize Sales
📖 Scenario: You work in a retail company database. You want to categorize sales amounts into 'Low', 'Medium', and 'High' categories to better understand sales performance.
🎯 Goal: Create a PL/pgSQL function that uses a CASE statement to categorize sales amounts into three categories: 'Low' for sales less than 100, 'Medium' for sales between 100 and 500, and 'High' for sales above 500.
📋 What You'll Learn
Create a table called
sales with columns sale_id (integer) and amount (numeric).Insert exactly three rows into
sales with amounts 50, 200, and 600.Create a PL/pgSQL function called
categorize_sale that takes a numeric parameter sale_amount and returns a text category using a CASE statement.Use the
CASE statement inside the function to return 'Low', 'Medium', or 'High' based on the sale_amount.Create a query that selects
sale_id, amount, and the category by calling categorize_sale(amount) for each sale.💡 Why This Matters
🌍 Real World
Categorizing sales data helps businesses quickly understand performance levels and make decisions.
💼 Career
Database developers and analysts often write functions with CASE statements to classify and transform data inside the database.
Progress0 / 4 steps