Variable declaration and assignment in PostgreSQL - Time & Space Complexity
Let's explore how the time needed to run code changes when we declare and assign variables in PostgreSQL.
We want to know how the work grows as we add more variables or assignments.
Analyze the time complexity of the following code snippet.
DO $$
DECLARE
counter INTEGER := 0;
total INTEGER := 100;
BEGIN
counter := total;
END $$;
This code declares two variables and assigns a value to one of them inside a block.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Variable declaration and assignment
- How many times: Each happens once in this code
When you add more variables or assignments, the work grows in a simple way.
| Input Size (number of variables) | Approx. Operations |
|---|---|
| 10 | 10 declarations and assignments |
| 100 | 100 declarations and assignments |
| 1000 | 1000 declarations and assignments |
Pattern observation: The work grows directly with the number of variables.
Time Complexity: O(n)
This means the time grows in a straight line as you add more variables or assignments.
[X] Wrong: "Declaring variables takes no time or is instant no matter how many."
[OK] Correct: Each declaration and assignment takes some time, so more variables mean more work.
Understanding how simple operations like variable assignments scale helps you reason about bigger database tasks confidently.
"What if we declared variables inside a loop that runs n times? How would the time complexity change?"