User-defined functions let you create your own reusable commands in SQL. They help you do the same task many times without rewriting code.
When you want to calculate a value repeatedly, like tax or discount.
When you need to format or clean data in a consistent way.
When you want to simplify complex calculations into a single command.
When you want to reuse logic across different queries or reports.
When you want to keep your SQL code organized and easier to read.
Syntax
SQL
CREATE FUNCTION function_name (parameters) RETURNS return_type
BEGIN
-- function body
RETURN value;
END;
Functions must return a single value using RETURN.
Parameters are inputs you give to the function to work with.
Examples
This function adds two numbers and returns the result.
SQL
CREATE FUNCTION add_two_numbers(a INT, b INT) RETURNS INT
BEGIN
RETURN a + b;
END;
This function joins first and last names with a space.
SQL
CREATE FUNCTION get_full_name(first_name VARCHAR(50), last_name VARCHAR(50)) RETURNS VARCHAR(100)
BEGIN
RETURN CONCAT(first_name, ' ', last_name);
END;
Sample Program
This function calculates the price after applying a discount rate. The SELECT statement shows how to use it.
SQL
CREATE FUNCTION calculate_discount(price DECIMAL(10,2), discount_rate DECIMAL(5,2)) RETURNS DECIMAL(10,2)
BEGIN
RETURN price - (price * discount_rate / 100);
END;
SELECT calculate_discount(100, 15) AS discounted_price;
OutputSuccess
Important Notes
Not all SQL databases support user-defined functions the same way; check your database documentation.
Functions should be simple and fast because they run inside queries.
Use meaningful names for functions and parameters to keep code clear.
Summary
User-defined functions let you create reusable SQL commands.
They take inputs, do work, and return a single value.
Functions help keep your SQL code clean and efficient.
Practice
(1/5)
1. What is the main purpose of a user-defined function in SQL?
easy
A. To create reusable code that returns a single value
B. To store large amounts of data
C. To create tables automatically
D. To delete records from a table
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 A
Quick Check:
User-defined function = reusable single-value code [OK]
Hint: Functions return one value and reuse code easily [OK]
Common Mistakes:
Confusing functions with tables or data storage
Thinking functions delete or modify data directly
Assuming functions return multiple rows or tables
2. Which of the following is the correct way to start creating a scalar user-defined function in SQL?
easy
A. DROP FUNCTION function_name();
B. CREATE FUNCTION function_name() RETURNS INT AS BEGIN RETURN 1; END;
C. SELECT FUNCTION function_name();
D. CREATE TABLE function_name();
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 B
Quick Check:
CREATE FUNCTION + RETURNS + BEGIN...END = correct syntax [OK]
Hint: Functions start with CREATE FUNCTION and specify RETURNS [OK]
Common Mistakes:
Using CREATE TABLE instead of CREATE FUNCTION
Trying to SELECT a function directly without calling it
Confusing DROP FUNCTION with creation syntax
3. Given the function below, what will be the output of SELECT dbo.AddFive(10);?
CREATE FUNCTION dbo.AddFive(@num INT) RETURNS INT AS BEGIN RETURN @num + 5; END;
medium
A. 5
B. 10
C. 15
D. Syntax Error
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 C
Quick Check:
Input 10 + 5 = 15 [OK]
Hint: Add input to 5 as function returns input + 5 [OK]
Common Mistakes:
Confusing input and output values
Assuming function returns input unchanged
Expecting syntax error due to missing parameters
4. Identify the error in the following user-defined function:
CREATE FUNCTION dbo.MultiplyByTwo(@val INT)
RETURNS INT
BEGIN
SET @val = @val * 2;
RETURN @val;
END;
medium
A. Missing AS keyword before BEGIN
B. Functions cannot modify input parameters
C. RETURN statement is not allowed in functions
D. Function must return VARCHAR, not INT
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 A
Quick Check:
CREATE FUNCTION ... RETURNS ... AS BEGIN ... [OK]
Hint: Always include AS before BEGIN in function syntax [OK]
Common Mistakes:
Trying to modify input parameters inside functions
Omitting AS keyword before BEGIN
Confusing function return types
5. You want to create a user-defined function that returns the length of a string only if the string is not empty; otherwise, it returns 0. Which of the following function definitions correctly implements this logic?
hard
A. CREATE FUNCTION dbo.StringLength(@input VARCHAR(100)) RETURNS INT AS BEGIN RETURN NULL; END;
B. CREATE FUNCTION dbo.StringLength(@input VARCHAR(100)) RETURNS INT AS BEGIN IF @input = '' RETURN 1; ELSE RETURN LEN(@input); END;
C. CREATE FUNCTION dbo.StringLength(@input VARCHAR(100)) RETURNS INT AS BEGIN RETURN CASE WHEN @input = '' THEN 1 ELSE LEN(@input) END; END;
D. CREATE FUNCTION dbo.StringLength(@input VARCHAR(100)) RETURNS INT AS BEGIN RETURN LEN(@input); END;
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 D
Quick Check:
LEN('') = 0 satisfies condition [OK]
Hint: LEN('') returns 0 for empty strings [OK]
Common Mistakes:
Returning incorrect value (like 1) for empty strings
Using overly complex conditional logic unnecessarily
Returning NULL instead of 0 for empty strings
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.