User-defined functions in SQL - Time & Space Complexity
When we use user-defined functions in SQL, it is important to know how their execution time changes as the data grows.
We want to understand how the function's running time scales with input size.
Analyze the time complexity of the following SQL user-defined function and its usage.
CREATE FUNCTION GetDiscount(price DECIMAL) RETURNS DECIMAL LANGUAGE plpgsql AS $$
BEGIN
IF price > 100 THEN
RETURN price * 0.1;
ELSE
RETURN price * 0.05;
END IF;
END;
$$;
SELECT product_id, GetDiscount(price) FROM products;
This function calculates a discount based on price and is called for each product in the products table.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The function GetDiscount is called once for each row in the products table.
- How many times: The number of times equals the number of rows in products, say n.
As the number of products grows, the total work grows proportionally because the function runs once per product.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 function calls |
| 100 | 100 function calls |
| 1000 | 1000 function calls |
Pattern observation: The total execution time grows linearly with the number of rows.
Time Complexity: O(n)
This means the total time grows directly in proportion to the number of rows processed.
[X] Wrong: "The function runs just once, so its time does not depend on the number of rows."
[OK] Correct: The function is called for each row, so total time adds up with more rows.
Understanding how user-defined functions affect query time helps you write efficient database code and explain performance clearly.
"What if the function called another function inside it that also runs in constant time? How would the overall time complexity change?"
Practice
Solution
Step 1: Understand what user-defined functions do
User-defined functions are designed to perform specific tasks and return a single value.Step 2: Compare options with the function's purpose
Only To create reusable code that returns a single value describes creating reusable code that returns a single value, which matches the function's role.Final Answer:
To create reusable code that returns a single value -> Option AQuick Check:
User-defined function = reusable single-value code [OK]
- Confusing functions with tables or data storage
- Thinking functions delete or modify data directly
- Assuming functions return multiple rows or tables
Solution
Step 1: Identify the correct syntax for creating a function
The correct syntax starts with CREATE FUNCTION, specifies the return type, and includes a BEGIN...END block.Step 2: Check each option's validity
CREATE FUNCTION function_name() RETURNS INT AS BEGIN RETURN 1; END; matches the correct syntax. Options A, B, and C are for other SQL commands (dropping, table creation, and selection).Final Answer:
CREATE FUNCTION function_name() RETURNS INT AS BEGIN RETURN 1; END; -> Option BQuick Check:
CREATE FUNCTION + RETURNS + BEGIN...END = correct syntax [OK]
- Using CREATE TABLE instead of CREATE FUNCTION
- Trying to SELECT a function directly without calling it
- Confusing DROP FUNCTION with creation syntax
SELECT dbo.AddFive(10);?
CREATE FUNCTION dbo.AddFive(@num INT) RETURNS INT AS BEGIN RETURN @num + 5; END;
Solution
Step 1: Understand the function logic
The function takes an integer input and returns the input plus 5.Step 2: Calculate the output for input 10
10 + 5 = 15, so the function returns 15.Final Answer:
15 -> Option CQuick Check:
Input 10 + 5 = 15 [OK]
- Confusing input and output values
- Assuming function returns input unchanged
- Expecting syntax error due to missing parameters
CREATE FUNCTION dbo.MultiplyByTwo(@val INT) RETURNS INT BEGIN SET @val = @val * 2; RETURN @val; END;
Solution
Step 1: Review function syntax rules
In SQL, the AS keyword is required before the BEGIN block in function definitions.Step 2: Check the given function
The function is missing AS before BEGIN, causing a syntax error.Final Answer:
Missing AS keyword before BEGIN -> Option AQuick Check:
CREATE FUNCTION ... RETURNS ... AS BEGIN ... [OK]
- Trying to modify input parameters inside functions
- Omitting AS keyword before BEGIN
- Confusing function return types
Solution
Step 1: Understand the requirement
The function must return 0 if the string is empty, otherwise return its length.Step 2: Analyze each option
CREATE FUNCTION dbo.StringLength(@input VARCHAR(100)) RETURNS INT AS BEGIN RETURN LEN(@input); END; correctly returns LEN(@input), and since LEN('')=0 it satisfies the logic. CREATE FUNCTION dbo.StringLength(@input VARCHAR(100)) RETURNS INT AS BEGIN IF @input = '' RETURN 1; ELSE RETURN LEN(@input); END; returns 1 for empty strings, incorrect. CREATE FUNCTION dbo.StringLength(@input VARCHAR(100)) RETURNS INT AS BEGIN RETURN CASE WHEN @input = '' THEN 1 ELSE LEN(@input) END; END; returns 1 for empty strings using CASE, incorrect. CREATE FUNCTION dbo.StringLength(@input VARCHAR(100)) RETURNS INT AS BEGIN RETURN NULL; END; always returns NULL, which is incorrect.Final Answer:
CREATE FUNCTION dbo.StringLength(@input VARCHAR(100)) RETURNS INT AS BEGIN RETURN LEN(@input); END; -> Option DQuick Check:
LEN('') = 0 satisfies condition [OK]
- Returning incorrect value (like 1) for empty strings
- Using overly complex conditional logic unnecessarily
- Returning NULL instead of 0 for empty strings
Ready to prove it?
Pass the test and this pattern moves unknown
