Functions in MySQL
CREATION AND WORKING OF
USER-DEFINED FUNCTIONS IN MYSQL
1. AIM
To understand Functions in MySQL and implement User-Defined Functions (UDFs) with suitable examples.
2. THEORY
✔ What is a Function?
A function in MySQL is a stored program that:
-
Accepts parameters
-
Performs an operation
-
Returns exactly one value
-
Can be used inside SQL queries like builtin functions (e.g., SUM, AVG)
Functions are commonly used for:
-
Calculations
-
Data formatting
-
Reusable business logic
-
Returning single computed values
3. TYPES OF FUNCTIONS IN MYSQL
A. Built-in Functions
MySQL provides many built-in functions:
✔ String Functions
-
UPPER(str) -
LOWER(str) -
CONCAT(str1, str2) -
LENGTH(str)
✔ Numeric Functions
-
ROUND(num) -
CEIL(num) -
FLOOR(num) -
ABS(num)
✔ Date Functions
-
NOW() -
CURDATE() -
DATEDIFF(date1, date2) -
DATE_ADD(date, INTERVAL x DAY)
✔ Aggregate Functions
-
SUM() -
AVG() -
COUNT() -
MIN() -
MAX()
4. USER-DEFINED FUNCTIONS (UDFs)
MySQL allows users to create their own reusable functions.
5. SYNTAX FOR CREATING FUNCTIONS
Important Keywords:
-
RETURNS datatype → type of returned value
-
DETERMINISTIC → always returns same output for same input
-
RETURN → value must be returned
6. EXAMPLES FOR LAB
Example 1: Simple Function to Add Two Numbers
✔ Call:
Example 2: Function to Return Employee Annual Salary
Suppose table:
Create Function:
✔ Call:
Example 3: Function to Check Even or Odd
✔ Call:
Example 4: Function to Count Total Employees
This uses data from the existing table.
✔ Call:
Example 5: Function to Compute Grade Based on Marks
✔ Call:
Example 6: Function to Apply Discount
✔ Call:
7. HOW TO VIEW AND DROP FUNCTIONS
✔ View functions:
✔ View function code:
✔ Drop a function:
8. LAB PRACTICE QUESTIONS
-
Create a function to return the square of a number.
-
Create a function to calculate age using date of birth.
-
Create a function to return the highest salary from the employees table.
-
Create a function that returns the reverse of a string.
-
Create a function to calculate simple interest.
-
Create a function to return number of students in a class.
9. RESULT
User-defined functions were successfully created, executed, and tested in MySQL.
Comments
Post a Comment