</>
Skip to content
MySQL lessons (42/48)

MySQL — Functions

Basic Function

DELIMITER //
CREATE FUNCTION FullName(first_name VARCHAR(50), last_name VARCHAR(50))
RETURNS VARCHAR(100)
DETERMINISTIC
BEGIN
    RETURN CONCAT(first_name, ' ', last_name);
END //
DELIMITER ;

SELECT FullName('John', 'Doe');

Scalar Function

DELIMITER //
CREATE FUNCTION CalculateTax(amount DECIMAL(10,2), rate DECIMAL(5,2))
RETURNS DECIMAL(10,2)
DETERMINISTIC
BEGIN
    RETURN amount * rate / 100;
END //
DELIMITER ;

SELECT CalculateTax(100.00, 8.5);

DETERMINISTIC vs NOT DETERMINISTIC

KeywordMeaning
DETERMINISTICSame input = same output
NOT DETERMINISTICOutput may vary (e.g., uses NOW())
DELIMITER //
CREATE FUNCTION CurrentYear()
RETURNS INT
NOT DETERMINISTIC
BEGIN
    RETURN YEAR(CURDATE());
END //
DELIMITER ;

Function with SQL Statements

DELIMITER //
CREATE FUNCTION CustomerOrderCount(cust_id INT)
RETURNS INT
DETERMINISTIC
BEGIN
    DECLARE order_count INT;
    SELECT COUNT(*) INTO order_count FROM orders WHERE customer_id = cust_id;
    RETURN order_count;
END //
DELIMITER ;

SELECT name, CustomerOrderCount(id) AS orders FROM customers;

Dropping Functions

DROP FUNCTION IF EXISTS FullName;

Functions vs Procedures

FeatureFunctionProcedure
ReturnSingle valueMultiple result sets
Call in SQLYes (SELECT)No (CALL)
ParametersIN onlyIN, OUT, INOUT
Side effectsNot recommendedAllowed

Mini Practice

Write SQL code that:

  1. Creates a scalar function with parameters
  2. Creates a DETERMINISTIC function
  3. Uses a function in a SELECT statement
  4. Drops a function

Up Next

Continue with Triggers — automatic actions on table events.

Related Topics

Frequently Asked Questions about Functions

What is Functions in MySQL?

Functions is a fundamental concept in MySQL. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Functions?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Functions.

Why is Functions important in MySQL?

Functions is essential for MySQL development. Understanding this concept will help you write better code and solve real-world problems more effectively.