Importance of Mysql Functions

Mysql which has already lot of built in function that provides flexibility during writing of SQL Queries.Apart from that mysql allows us to create our own custom functions as well. These custom functions are known as mysql function.

Mysql functions are different than mysql procedures in broadly following sense:
>> Stored function return single value
>> Procedures return value using OUT and INOUT whereas function uses RETURN keyword for that.
>> Unlike stored procedures stored functions can be used directly inside the SQL statements like SELECT, UPDATE, DELETE and INSERT.

Its such a great feature that can encapsulate commonly used business rules and formula. Even you can control the full program within a single mysql function and return your intended result after execution of program.

Here are an example of creating a stored function

CREATE FUNCTION cust_status (in_status CHAR(1))
RETURNS VARCHAR(20)
BEGIN
IF in_status =’N’ THEN
RETURN (‘NEW’);
ELSEIF in_status =’R’ THEN
RETURN (‘ReTURNING’);
ELSEIF in_status =’E’ THEN
RETURN (‘EXPIRED’);
END IF;
END;

Make sure you are using Delimiter $ .

We can use this function directly in our SQL Queries:
SELECT cust_status(‘N’) AS STATUS

To Delete this function from mysql
DROP FUNCTION IF EXISTS cust_status;

The following two tabs change content below.

Chandra Shekhar

GCP Architect
Chandra Shekhar Pandey is Google certified Cloud engineer, I am Magento2 Trained developer. Having huge experience in designing cloud solution. I have around 12 years of experience with world enterprise IT companies and fortune 500 clients. During my architecture design I am always caring about high availability, fast performance and resilient system. From the programmer background I have huge experience in LAMP stack as well. Throughout my carrier I have worked on Retail, E-Learning, Video Conferencing and social media domain. The motive of creating cutehits was just to share the knowledge/solutions I get to know during my day to day life so that if possible I can help someone for same problems/solutions. CuteHits.com is a really a very effort for sharing knowledge to rest of the world. For any query/suggestion about same you can contact me on below details:- Email: shekharmca2005 at gmail.com Phone: +91-9560201363

Latest posts by Chandra Shekhar (see all)

You may also like...