Using IF-ELSIF-ELSE Control Flow in PostgreSQL
📖 Scenario: You are managing a small bookstore database. You want to classify books based on their price into categories: 'Cheap', 'Moderate', and 'Expensive'. This will help the store staff quickly identify the price range of each book.
🎯 Goal: Create a PostgreSQL function that uses IF-ELSIF-ELSE control flow to categorize book prices into 'Cheap' (less than 10), 'Moderate' (between 10 and 20), and 'Expensive' (above 20).
📋 What You'll Learn
Create a table called
books with columns id (integer), title (text), and price (numeric).Insert exactly three books with prices 5, 15, and 25.
Create a function called
price_category that takes a numeric price and returns a text category using IF-ELSIF-ELSE.Use the function in a SELECT query to show each book's title and its price category.
💡 Why This Matters
🌍 Real World
Classifying data based on conditions is common in business databases, such as categorizing products by price or customers by age group.
💼 Career
Understanding IF-ELSIF-ELSE in SQL functions helps database developers write dynamic and conditional logic inside the database, improving data processing efficiency.
Progress0 / 4 steps