MySQL DROP FUNCTION

MySQL DROP FUNCTION

MySQL DROP FUNCTION

The DROP FUNCTION statement in MySQL is used to delete a stored function from the database. It permanently removes the function definition, and any subsequent attempts to call the function will result in an error.


Syntax

DROP FUNCTION [IF EXISTS] function_name;
  • IF EXISTS: Optional. Prevents an error if the function does not exist.
  • function_name: The name of the function to drop.

Prerequisites

  1. Function Ownership: You must have sufficient privileges (ALTER ROUTINE or DROP privilege) to drop a function.
  2. Database Context: Ensure you are in the correct database where the function is defined.

Examples

1. Drop an Existing Function

Suppose you have a function named calculate_discount:

DROP FUNCTION calculate_discount;

Result: The the calculate_discount function is removed from the database.

2. Use IF EXISTS

Using IF EXISTS prevents an error if the function does not exist.

DROP FUNCTION IF EXISTS calculate_tax;

Scenario:

  • If calculate_tax exists, it will be dropped.
  • If calculate_tax does not exist, no error will occur.

3. Attempt to Call a Dropped Function

After dropping a function, any attempt to call it will result in an error.

SELECT calculate_discount(100, 10);

Error:

ERROR 1305 (42000): FUNCTION calculate_discount does not exist

Verify the Deletion

You can confirm whether a function exists in the database by querying the ROUTINES table in the information_schema:

SELECT ROUTINE_NAME FROM information_schema.ROUTINES WHERE ROUTINE_TYPE = 'FUNCTION' AND ROUTINE_NAME = 'calculate_discount';

If the function has been dropped, the query will return no results.

Points to Remember

  1. Dependent Objects:

    • Ensure no applications or objects depend on the function before dropping it to avoid breaking functionality.
  2. Privileges:

    • Dropping a function requires appropriate privileges. A lack of permissions will result in an error.
  3. Irreversible Action:

    • Dropping a function is permanent. If you need it later, you'll have to recreate it.

Recreate a Dropped Function

If you need to use the function again, you must redefine it. For example:

CREATE FUNCTION calculate_discount(price DECIMAL(10, 2), discount_rate DECIMAL(5, 2)) RETURNS DECIMAL(10, 2) DETERMINISTIC BEGIN RETURN price - (price * discount_rate / 100); END;

Conclusion

The DROP FUNCTION statement is a straightforward way to manage and clean up unused or obsolete functions in MySQL. Always ensure that dropping the function won't disrupt your application's workflow. Use IF EXISTS to avoid unnecessary errors when managing database objects.

Let me know if you need further clarification or examples!

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close