Creating stored functions in MySQL - Performance & Efficiency
When we create stored functions in MySQL, it's important to understand how their execution time changes as the input grows.
We want to know how the work inside the function scales when called with different input sizes.
Analyze the time complexity of the following stored function.
CREATE FUNCTION sum_to_n(n INT) RETURNS INT
BEGIN
DECLARE total INT DEFAULT 0;
DECLARE i INT DEFAULT 1;
WHILE i <= n DO
SET total = total + i;
SET i = i + 1;
END WHILE;
RETURN total;
END
This function adds all numbers from 1 up to n and returns the total sum.
Look for loops or repeated steps inside the function.
- Primary operation: The WHILE loop that adds numbers from 1 to n.
- How many times: The loop runs exactly n times, once for each number.
As n grows, the function does more additions, one for each number up to n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The number of operations grows directly with n; doubling n doubles the work.
Time Complexity: O(n)
This means the time to run the function grows in a straight line with the input size n.
[X] Wrong: "The function runs in constant time because it just returns a sum."
[OK] Correct: The function actually adds each number one by one, so the time depends on how big n is.
Understanding how loops inside stored functions affect performance helps you write efficient database code and answer questions about scaling.
"What if we changed the function to use a mathematical formula instead of a loop? How would the time complexity change?"
Practice
Solution
Step 1: Understand stored function purpose
Stored functions are designed to hold reusable code inside the database.Step 2: Identify key feature
They must return a value using RETURN, which distinguishes them from procedures.Final Answer:
To save reusable code that returns a value -> Option AQuick Check:
Stored function = reusable code + return value [OK]
- Confusing stored functions with procedures
- Thinking stored functions do not return values
- Using stored functions to delete data
- Assuming stored functions create tables
Solution
Step 1: Check syntax for stored function
MySQL stored functions start with CREATE FUNCTION, include parentheses for parameters, and specify RETURNS type.Step 2: Identify correct syntax
CREATE FUNCTION funcName() RETURNS INT BEGIN ... END uses correct syntax with parentheses and RETURNS INT, followed by BEGIN ... END block.Final Answer:
CREATE FUNCTION funcName() RETURNS INT BEGIN ... END -> Option CQuick Check:
CREATE FUNCTION + RETURNS + BEGIN/END = correct syntax [OK]
- Using PROCEDURE instead of FUNCTION
- Omitting parentheses after function name
- Using curly braces instead of BEGIN/END
- Missing RETURNS keyword
SELECT addFive(10);?
DELIMITER $$ CREATE FUNCTION addFive(num INT) RETURNS INT BEGIN RETURN num + 5; END$$ DELIMITER ;
Solution
Step 1: Understand function logic
The function addFive takes an integer input and returns the input plus 5.Step 2: Calculate output for input 10
Input 10 plus 5 equals 15, so the function returns 15.Final Answer:
15 -> Option AQuick Check:
10 + 5 = 15 [OK]
- Confusing input and output values
- Ignoring RETURN statement
- Assuming syntax error due to DELIMITER
- Forgetting to add 5
DELIMITER $$ CREATE FUNCTION multiplyByTwo(num INT) RETURNS INT BEGIN SET result = num * 2; RETURN result; END$$ DELIMITER ;
Solution
Step 1: Check variable usage inside function
The variable 'result' is used but not declared with DECLARE inside the function.Step 2: Understand MySQL variable rules
Local variables must be declared before use; missing DECLARE causes error.Final Answer:
Missing variable declaration for 'result' -> Option DQuick Check:
Variables must be declared before use [OK]
- Not declaring variables before SET
- Misusing DELIMITER keyword
- Forgetting RETURN statement
- Using invalid function names
isEven that returns 1 if a number is even and 0 if odd. Which of the following is the correct complete function definition?Solution
Step 1: Check logic for even number
Even numbers have zero remainder when divided by 2, so usenum % 2 = 0.Step 2: Verify correct syntax and return values
Uses IF with correct conditionnum % 2 = 0and returns 1 or 0 accordingly, with proper BEGIN/END block, END IF, and DELIMITER.Final Answer:
DELIMITER $$ CREATE FUNCTION isEven(num INT) RETURNS INT BEGIN IF num % 2 = 0 THEN RETURN 1; ELSE RETURN 0; END IF; END$$ DELIMITER ; -> Option BQuick Check:
Use modulo operator and IF for even check [OK]
- Using division instead of modulo for condition
- Returning wrong data types
- Omitting END IF statement
- Returning num % 2 without comparing to 0
Ready to prove it?
Pass the test and this pattern moves unknown
