0
0
PostgreSQLquery~5 mins

RAISE for notices and exceptions in PostgreSQL

Choose your learning style9 modes available
Introduction
RAISE helps you send messages or stop your code when something important happens. It tells you about warnings or errors in your database code.
You want to show a message to explain what your code is doing.
You need to warn about a possible problem but keep running the code.
You want to stop the code because something went wrong.
You want to debug by printing values during code execution.
You want to handle errors clearly in your database functions.
Syntax
PostgreSQL
RAISE level 'message';

-- level can be NOTICE, WARNING, EXCEPTION, INFO, LOG
-- message is a text string or expression
RAISE with EXCEPTION stops the code and returns an error.
Other levels like NOTICE or WARNING just show messages but continue running.
Examples
Shows a simple notice message without stopping the code.
PostgreSQL
RAISE NOTICE 'This is a notice message';
Shows a warning message but code keeps running.
PostgreSQL
RAISE WARNING 'This is a warning message';
Stops the code and shows an error message.
PostgreSQL
RAISE EXCEPTION 'This is an error and stops execution';
Shows an info message with a variable value.
PostgreSQL
RAISE INFO 'Current value is %', my_variable;
Sample Program
This code shows a notice at start, a warning because the value is greater than 5, and finishes with a notice. It does not raise an exception because the value is not greater than 20.
PostgreSQL
DO $$
DECLARE
  my_value INT := 10;
BEGIN
  RAISE NOTICE 'Starting the block';
  IF my_value > 5 THEN
    RAISE WARNING 'Value % is greater than 5', my_value;
  END IF;
  IF my_value > 20 THEN
    RAISE EXCEPTION 'Value % is too large', my_value;
  END IF;
  RAISE NOTICE 'Block finished successfully';
END $$;
OutputSuccess
Important Notes
Use RAISE EXCEPTION to stop code when a serious problem happens.
RAISE messages appear in the client or server logs depending on level.
You can include variables in messages using % placeholders.
Summary
RAISE sends messages or errors from database code.
NOTICE and WARNING show messages but continue running.
EXCEPTION stops the code and returns an error.