Function vs procedure decision in SQL - Performance Comparison
When choosing between a function and a procedure in SQL, it's important to understand how their execution time grows as the data size increases.
We want to know which one might take more time when working with larger inputs.
Analyze the time complexity of these two SQL blocks.
-- Function example
CREATE FUNCTION get_total_sales(customer_id INT) RETURNS DECIMAL LANGUAGE SQL AS $$
SELECT SUM(amount) FROM sales WHERE customer_id = $1;
$$;
-- Procedure example
CREATE PROCEDURE update_customer_sales(customer_id INT) LANGUAGE plpgsql AS $$
BEGIN
UPDATE customers SET total_sales = (SELECT SUM(amount) FROM sales WHERE customers.customer_id = customer_id) WHERE customers.customer_id = customer_id;
END;
$$;
The function calculates total sales for one customer. The procedure updates a customer's total sales in the customers table.
Look at what repeats when these run.
- Primary operation: Scanning the sales table to sum amounts for a customer.
- How many times: Once per call for the function; once per procedure call, but procedure may be called multiple times in a batch.
As the sales table grows, the time to sum sales for one customer grows roughly with the number of sales that customer has.
| Input Size (number of sales for one customer) | Approx. Operations |
|---|---|
| 10 | 10 sums |
| 100 | 100 sums |
| 1000 | 1000 sums |
Pattern observation: The time grows linearly with the number of sales for that customer.
Time Complexity: O(n)
This means the time to calculate or update sales grows directly with the number of sales records for the customer.
[X] Wrong: "Functions always run faster than procedures because they return values."
[OK] Correct: Both run similar queries; speed depends on what they do inside, not just if they return a value.
Understanding how functions and procedures perform helps you choose the right tool for your database tasks, a skill valued in real projects and interviews.
"What if the procedure updated total sales for all customers at once? How would the time complexity change?"
Practice
Solution
Step 1: Understand the purpose of functions
Functions are designed to return a value and can be called within queries like SELECT.Step 2: Compare with procedures
Procedures perform tasks but do not return values directly and cannot be used inside SELECT statements.Final Answer:
Functions return a value and can be used in SELECT queries. -> Option AQuick Check:
Functions return values [OK]
- Thinking procedures return values like functions
- Using procedures inside SELECT queries
- Confusing function usage with procedure usage
Solution
Step 1: Identify function syntax
Functions require specifying RETURNS type and a RETURN statement inside BEGIN...END.Step 2: Check options for correctness
CREATE FUNCTION getCount() RETURNS INT BEGIN RETURN 10; END; correctly declares a function with RETURNS INT and returns a value. Others either use PROCEDURE or miss RETURNS.Final Answer:
CREATE FUNCTION getCount() RETURNS INT BEGIN RETURN 10; END; -> Option DQuick Check:
Functions need RETURNS and RETURN [OK]
- Using PROCEDURE keyword for functions
- Omitting RETURNS clause in function
- Using RETURN in procedures incorrectly
SELECT calculateTax(100); if calculateTax is a function that returns 10% of the input amount?CREATE FUNCTION calculateTax(amount INT) RETURNS INT BEGIN RETURN amount * 0.1; END;
Solution
Step 1: Understand function logic
The function multiplies the input amount by 0.1 to calculate 10% tax.Step 2: Calculate output for input 100
100 * 0.1 = 10, so the function returns 10.Final Answer:
10 -> Option CQuick Check:
100 * 0.1 = 10 [OK]
- Confusing 0.1 with 10
- Expecting decimal output when function returns INT
- Assuming error due to type mismatch
CREATE PROCEDURE updateEmail(userId INT, newEmail VARCHAR(100)) BEGIN UPDATE users SET email = newEmail WHERE id = userId; END;
When you try to call it with
SELECT updateEmail(1, 'test@example.com');, you get an error. What is the problem?Solution
Step 1: Understand procedure usage
Procedures perform actions but do not return values and cannot be called inside SELECT queries.Step 2: Identify error cause
Calling a procedure with SELECT causes error because procedures are invoked with CALL, not SELECT.Final Answer:
Procedures cannot be called inside SELECT statements. -> Option AQuick Check:
Use CALL for procedures, not SELECT [OK]
- Trying to use SELECT to call procedures
- Expecting procedures to return values
- Misunderstanding parameter directions
Solution
Step 1: Separate calculation and action
Functions should be used for calculations returning values; procedures for actions like logging.Step 2: Apply best practice
Use a function to return the discount price, and a procedure to perform the logging task separately.Final Answer:
Use a function to calculate discount and a procedure to log the discount. -> Option BQuick Check:
Functions calculate; procedures perform tasks [OK]
- Trying to do logging inside functions
- Expecting procedures to return values
- Mixing calculation and side effects in one routine
Ready to prove it?
Pass the test and this pattern moves unknown
