LESSON 60 / 62 · Stored functionsStored functions
Creating and using stored functions in SQL. Syntax, parameters, return types, and practical examples.
Stored functions are a powerful SQL tool that allows you to create reusable code blocks for performing calculations and data transformations. Unlike built-in functions, stored functions are created by developers to solve specific tasks.
A stored function is a named block of SQL code that accepts parameters, performs calculations, and always returns a single value of a specific type.
General Structure of a Stored Function
CREATE FUNCTION function_name([parameter type [, ...]])
RETURNS return_type
BEGIN
-- function logic
RETURN result;
END;- [ ]optional part
- ...can be repeated
The name you use to call the function in queries, for example is_adult.
The name of an input value, used to access it inside the function. You can list several parameters separated by commas, or leave the parentheses empty if you need none.
The type of the value the function returns, for example BOOLEAN or INT.
The value or expression the function returns. It is converted to the type given after RETURNS.
- parameter
- Optional
- type
- The parameter's data type: INT, DATE, VARCHAR(50), and so on.
Simple Function Example
Let's create a function to determine if a person is an adult based on their birth date:
CREATE FUNCTION is_adult(birth_date DATE)
RETURNS BOOLEAN
BEGIN
RETURN TIMESTAMPDIFF(YEAR, birth_date, CURDATE()) >= 18;
END;Now this function can be used in any query:
-- Create the function
CREATE FUNCTION is_adult(birth_date DATE)
RETURNS BOOLEAN
BEGIN
RETURN TIMESTAMPDIFF(YEAR, birth_date, CURDATE()) >= 18;
END;
-- Use the function
SELECT
is_adult('2010-05-15') AS child_status,
is_adult('2000-03-20') AS adult_status;| child_status | adult_status |
|---|---|
| 0 | 1 |
Using Functions in Table Queries
Stored functions are especially useful when working with real data. For example, we can use our function to filter students by age:
-- Create the function
CREATE FUNCTION is_adult(birth_date DATE)
RETURNS BOOLEAN
BEGIN
RETURN TIMESTAMPDIFF(YEAR, birth_date, CURDATE()) >= 18;
END;
-- Use the function in a table query
SELECT
first_name,
last_name,
birthday,
is_adult(birthday) AS is_adult
FROM Student
WHERE is_adult(birthday) = true
LIMIT 5;| first_name | last_name | birthday | is_adult |
|---|---|---|---|
| Nikolaj | Sokolov | 2000-10-01T00:00:00.000Z | 1 |
| Vyacheslav | Eliseev | 2000-11-21T00:00:00.000Z | 1 |
| Ivan | Efremov | 2000-09-19T00:00:00.000Z | 1 |
| Anatolij | ZHdanov | 2007-07-15T00:00:00.000Z | 1 |
| Georgij | Noskov | 2000-03-03T00:00:00.000Z | 1 |
Functions with Database Queries
Stored functions can execute SQL queries inside themselves to retrieve necessary data:
CREATE FUNCTION get_student_lessons_count(student_id INT, target_date DATE)
RETURNS INT
BEGIN
DECLARE lessons_count INT;
SELECT COUNT(*) INTO lessons_count
FROM Schedule s
INNER JOIN Student_in_class sic ON s.class = sic.class
WHERE sic.student = student_id
AND s.date = target_date;
RETURN lessons_count;
END;This function counts the number of lessons for a specific student on a given day:
SELECT get_student_lessons_count(1, '2019-09-01') AS lessons_today;| lessons_today |
|---|
| 3 |
Breaking Down the Example with Variables
Let's analyze the previous example step by step to understand how variables and the INTO construct work:
DECLARE lessons_count INT;This line declares a variable lessons_count of type INT. The variable will store the result of our query.
SELECT COUNT(*) INTO lessons_count
FROM Schedule s
INNER JOIN Student_in_class sic ON s.class = sic.class
WHERE sic.student = student_id
AND s.date = target_date;Here we save the query result into a variable:
- SELECT COUNT(*) — counts the number of records
- INTO lessons_count — saves the result into the lessons_count variable
- The rest — a regular SQL query with JOIN and conditions
RETURN lessons_count;Return the variable value as the function result.
Important: The INTO construct allows you to save the result of a SELECT query into a variable. This is the foundation of working with data inside stored functions.
Managing Stored Functions
Viewing Existing Functions
SHOW FUNCTION STATUS WHERE Db = 'your_database_name';Dropping a Function
DROP FUNCTION IF EXISTS is_adult;Modifying a Function
To modify a function in MySQL, you need to drop the old version first, then create a new one:
DROP FUNCTION IF EXISTS is_adult;
-- Create new version of the function
CREATE FUNCTION is_adult(birth_date DATE) ...Stored functions are a powerful tool for creating reusable business logic directly in the database. They help centralize calculations and ensure data consistency across the entire application! 🚀
Practice
Solve it in the editor. The query runs against a sample database in your browser.
Write a query and run it to see the results.
Write a query and run it to see the results.