RAISE for notices and exceptions in PostgreSQL - Time & Space Complexity
When using RAISE statements in PostgreSQL, it is important to understand how often these messages are triggered during query execution.
We want to know how the number of RAISE calls grows as the input data grows.
Analyze the time complexity of the following PL/pgSQL block using RAISE NOTICE inside a loop.
DO $$
DECLARE
rec RECORD;
BEGIN
FOR rec IN SELECT id FROM users LOOP
RAISE NOTICE 'Processing user id: %', rec.id;
END LOOP;
END $$;
This code loops over all users and raises a notice for each user processed.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each row in the users table.
- How many times: Once for every user in the table.
Each user causes one RAISE NOTICE call, so the total calls grow directly with the number of users.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 RAISE calls |
| 100 | 100 RAISE calls |
| 1000 | 1000 RAISE calls |
Pattern observation: The number of RAISE calls increases one-to-one with the number of users.
Time Complexity: O(n)
This means the time to execute grows linearly as the number of users grows.
[X] Wrong: "RAISE statements run only once regardless of input size."
[OK] Correct: Because RAISE inside a loop runs every time the loop runs, so it scales with the number of rows processed.
Understanding how RAISE statements affect performance helps you write clear and efficient database code, a useful skill in real projects and interviews.
What if we moved the RAISE statement outside the loop? How would the time complexity change?