Why stored procedures centralize logic in MySQL - Performance Analysis
When we use stored procedures, we want to know how the time to run them changes as data grows.
We ask: How does the work inside a stored procedure scale with input size?
Analyze the time complexity of this stored procedure that sums values from a table.
CREATE PROCEDURE SumValues()
BEGIN
DECLARE total INT DEFAULT 0;
DECLARE done BOOLEAN DEFAULT FALSE;
DECLARE val INT;
DECLARE cur CURSOR FOR SELECT value FROM numbers;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN cur;
read_loop: LOOP
FETCH cur INTO val;
IF done THEN
LEAVE read_loop;
END IF;
SET total = total + val;
END LOOP;
CLOSE cur;
SELECT total;
END;
This procedure reads all rows from the 'numbers' table and sums their values.
Look for repeated actions inside the procedure.
- Primary operation: Looping through each row in the 'numbers' table.
- How many times: Once for every row in the table.
The procedure does one addition per row, so more rows mean more additions.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the number of rows.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of rows processed.
[X] Wrong: "Stored procedures always run instantly no matter data size."
[OK] Correct: Stored procedures still do work on data, so bigger data means more time.
Understanding how stored procedures scale helps you explain how database logic handles growing data smoothly.
"What if the stored procedure called another procedure inside the loop? How would that affect time complexity?"