๐Ÿงฎ MySQL Stored Functions โ€“ Define, Use, and Reuse Computed Logic


๐Ÿงฒ Introduction โ€“ Why Use Stored Functions in MySQL?

Stored functions in MySQL are routines that return a single value and can be used within SQL statements just like built-in functions (NOW(), CONCAT(), etc.). They allow you to:

  • ๐Ÿ” Encapsulate reusable calculations
  • ๐Ÿ“‰ Simplify queries
  • ๐Ÿ”’ Centralize business logic
  • ๐Ÿš€ Improve code readability and maintainability

๐ŸŽฏ In this guide, youโ€™ll learn:

  • How to create and use stored functions
  • Syntax and return types
  • Best practices and use cases
  • How to manage and remove functions

๐Ÿ”ง 1. What Is a Stored Function?

A stored function is a named block of SQL code that:

  • Accepts parameters (IN)
  • Returns a single scalar value
  • Can be used in SELECT, WHERE, ORDER BY, and other clauses

๐Ÿ“ 2. Syntax โ€“ CREATE FUNCTION

DELIMITER //

CREATE FUNCTION function_name(param_name datatype)
RETURNS return_datatype
[DETERMINISTIC | NOT DETERMINISTIC]
BEGIN
  -- Logic
  RETURN value;
END //

DELIMITER ;

๐Ÿงฎ 3. Example โ€“ Simple Discount Calculator

DELIMITER //

CREATE FUNCTION get_discount(price DECIMAL(10,2))
RETURNS DECIMAL(10,2)
DETERMINISTIC
BEGIN
  RETURN price * 0.90;
END //

DELIMITER ;

๐Ÿ”น Usage in a Query

SELECT product_name, price, get_discount(price) AS discounted_price
FROM products;

โœ… Computes 10% discount for every product on the fly.


๐Ÿ”ข 4. Parameter Rules

  • Only IN parameters are allowed
  • You must declare the return type (RETURNS)
  • Use RETURN to return a value
  • Always end with DELIMITER ;

๐Ÿงช 5. Example โ€“ Days Between Dates

DELIMITER //

CREATE FUNCTION days_between(start_date DATE, end_date DATE)
RETURNS INT
DETERMINISTIC
BEGIN
  RETURN DATEDIFF(end_date, start_date);
END //

DELIMITER ;

๐Ÿ”น Example Usage

SELECT days_between(order_date, delivery_date) AS days_waited
FROM orders;

๐Ÿ” 6. View & Drop Functions

๐Ÿ”น View All Stored Functions

SHOW FUNCTION STATUS WHERE Db = 'your_database';

๐Ÿ”น Drop Function

DROP FUNCTION IF EXISTS get_discount;

๐Ÿง  Stored Function vs Stored Procedure

FeatureStored FunctionStored Procedure
Returns a valueโœ… Yes (with RETURN)โŒ No (uses OUT or result sets)
Used in SQL expressionsโœ… YesโŒ No
Used forCalculations, lookupsMulti-step processes
Called withPart of queriesCALL proc_name()

๐Ÿ“˜ Best Practices

โœ… Tip๐Ÿ’ก Why It Matters
Mark functions as DETERMINISTIC if they areHelps with optimizer and replication
Avoid data-changing logic inside functionsFunctions should be read-only
Keep functions short and focusedEncourages reuse and clarity
Return consistent data typesPrevents errors in calculations or joins
Use for logic used across multiple queriesReduces duplication and improves maintainability

๐Ÿš€ Real-World Use Cases

Use CaseFunction NameDescription
Apply percentage discountget_discount(price)Calculates final price based on a rule
Days until duedays_until_due(date)Returns days left before a due date
Convert full name to usernamegenerate_username()Creates lowercase username from names
Validate email domainis_company_email()Checks if email ends with @company.com

๐Ÿ“Œ Summary โ€“ Recap & Next Steps

MySQL stored functions allow you to embed reusable, calculated logic into your SQL queries. They are perfect for centralizing formulas, custom expressions, and on-the-fly transformations.

๐Ÿ” Key Takeaways

  • Stored functions return a single value
  • Use them inside SQL statements (SELECT, WHERE, etc.)
  • Must declare input parameters and return type
  • Use DETERMINISTIC where logic is consistent
  • Avoid side effects (no INSERT, UPDATE, etc.)

โš™๏ธ Real-World Relevance

Stored functions are ideal for e-commerce discounts, analytics formulas, data formatting, and lookup optimizations in production databases.


โ“ FAQ โ€“ MySQL Stored Functions


โ“ Can I use INSERT, UPDATE, or DELETE inside a function?

โŒ No. Functions must be read-only. Use procedures for data changes.


โ“ Can I use a function in a WHERE clause?

โœ… Yes. For example:

SELECT * FROM orders WHERE days_between(order_date, NOW()) > 30;

โ“ What’s the difference between DETERMINISTIC and NOT DETERMINISTIC?

  • DETERMINISTIC: Always returns the same result for the same inputs
  • NOT DETERMINISTIC: May vary due to randomness, time, or data changes

โ“ How many functions can I create in MySQL?

There is no hard limit; limited only by database performance and organization.


โ“ Can I pass multiple arguments to a function?

โœ… Yes, declare as many IN parameters as needed:

CREATE FUNCTION calc_total(p DECIMAL, tax DECIMAL) RETURNS DECIMAL ...

Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

๐Ÿงฎ MySQL Stored Functions

Or Copy Link

CONTENTS
Scroll to Top