Using RAISE for Notices and Exceptions in PostgreSQL
📖 Scenario: You are managing a PostgreSQL database for a small online store. You want to create a simple stored procedure that checks the stock of a product before processing an order. If the stock is low, you want to notify the user with a notice. If the stock is zero or less, you want to stop the process with an exception.
🎯 Goal: Create a PostgreSQL function that uses RAISE NOTICE to warn when stock is low and RAISE EXCEPTION to stop when stock is unavailable.
📋 What You'll Learn
Create a table called
products with columns product_id (integer) and stock (integer).Insert a product with
product_id 1 and stock 5.Create a function called
check_stock that takes p_product_id as an integer parameter.Inside the function, get the stock for the given product.
If stock is less than 3 but greater than 0, use
RAISE NOTICE to warn 'Stock is low'.If stock is 0 or less, use
RAISE EXCEPTION to stop with message 'Out of stock'.If stock is sufficient, return the stock value.
💡 Why This Matters
🌍 Real World
Using RAISE statements helps database developers communicate important information or errors during stored procedure execution, improving debugging and user feedback.
💼 Career
Database developers and administrators often write stored procedures that need to handle errors and warnings gracefully. Knowing how to use RAISE is essential for robust database programming.
Progress0 / 4 steps