0
0
PostgreSQLquery~3 mins

Why RAISE for notices and exceptions in PostgreSQL? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your database could talk back and warn you before things go wrong?

The Scenario

Imagine you are writing a long script to update many records in a database. You want to know if something unexpected happens or if a certain condition is met, but you have no easy way to get messages or stop the script when needed.

The Problem

Without a way to send messages or stop execution, you must guess if your script worked correctly. You might miss important warnings or errors, leading to wrong data or wasted time fixing problems later.

The Solution

The RAISE command lets you send notices, warnings, or errors directly from your database code. It helps you see messages immediately or stop the process when something goes wrong, making your scripts safer and easier to debug.

Before vs After
Before
/* No way to show messages or stop on error */
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
After
DO $$
BEGIN
  RAISE NOTICE 'Starting update for account %', 1;
  UPDATE accounts SET balance = balance - 100 WHERE id = 1;
  IF NOT FOUND THEN
    RAISE EXCEPTION 'Account % not found', 1;
  END IF;
END
$$;
What It Enables

You can now communicate important information or stop execution exactly when needed, making your database scripts more reliable and easier to maintain.

Real Life Example

When processing payments, you can use RAISE to warn if a payment amount is suspicious or stop the process if the account does not exist, preventing wrong transactions.

Key Takeaways

Manual scripts lack clear feedback and error control.

RAISE sends messages or stops execution inside database code.

This improves debugging, safety, and clarity in database operations.