MySQL Functions
1
Outline
MySQL functions
Built-in functions example
Syntax of a function in MySQL
MySQL Problem and solve with functions
Solution
2
MySQL Functions
Function is a stored program that you can pass parameters into and
then return a value.
Function has a return type and returns a value always.
Function is not allowed with data manipulation queries, select queries
is the only one available.
To call a function you need to use select statement.
We have to two types of functions built-in and user defined functions.
3
Built-In Functions
ASCII : this function is used to return the ASCII value of a character.
Ex: SELECT ASCII(‘HELLO’);
in this case it will return ASCII for the first character(‘H’)->104
CHAR_LENGTH : this function is used to return the length of a string.
EX: SELECT CHAR_LENGTH(‘sql tutorial’);->12
CONCAT: used to concatenate two strings.
EX: SELECT CONCAT(‘sql ’, ‘tutorial’);
UCASE: used to converts a string to upper-case;
EX: SELECT UCASE(‘SQL Tutorial is FUN!’);
TRIM: used to remove leading and trailing spaces from a string.
EX: SELECT TRIM(' SQL Tutorial ‘);
4
Syntax of a function in MySQL
The syntax used to declare a function is like that:
DELIMITER $$
CREATE DEFINER=`root`@`localhost` FUNCTION function_name( param1,
param2,… ) RETURNS datatype
[NOT] DETERMINISTIC
BEGIN
-- statements
END$$
DELIMITER ;
In order to show all functions in the database use the following syntax
Show function status where Db = ‘name of the Database’;
5
Syntax of a function in MySQL
Remarks:
A deterministic function always returns the same result for the same input
parameters whereas a non-deterministic function returns different results
for the same input parameters.
If you don’t use DETERMINISTIC or NOT DETERMINISTIC, MySQL uses the
NOT DETERMINISTIC option by default.
Datatype: VARCHAR, DECIMAL, INT…….
6
MySQL Problem and solve with
function
Suppose that we have table Customers, how we can see customer
level for each customer from his credit, where customer level is
defined dependent on the range (>100000) PLATINUM, (>=50000,
<=100000) GOLD, (<50000) SILVER
Id Customer Credit Customer
Name Level
1 Ali 120000 PLATINUM
2 Hassan 40000 SILVER
3 Mohamad 52000 GOLD
7
Solution
USE `functions`;
DROP function IF EXISTS `CustomerLevel`;
DELIMITER $$
USE `functions`$$
CREATE DEFINER=`root`@`localhost` FUNCTION `CustomerLevel`(credit DECIMAL(10,2) )
RETURNS varchar(20) CHARSET latin1
DETERMINISTIC
BEGIN
DECLARE customerLevel VARCHAR(20);
IF (credit > 100000) THEN SET customerLevel = 'PLATINUM';
ELSEIF (credit >= 50000 AND credit <= 100000) THEN SET customerLevel = 'GOLD';
ELSEIF (credit < 50000) THEN SET customerLevel = 'SILVER';
END IF;
RETURN (customerLevel);
END$$
8
DELIMITER ;
Solution(contd.)
Run the function in query.
SELECT customerName, CustomerLevel(credit) FROM customers
ORDER BY customerName;
9
Example 2
In Sailors Boats Reserve database we want to add the following
feature
When we select the rating we need to add
Excellent if the rating is greater than 9
Above standard if the rating is greater than 7
Standard if the rating is greater than 5
Below standard if the rating is less than 5
10
DROP function IF EXISTS RatingLevel;
DELIMITER $$
CREATE FUNCTION RatingLevel(rate smallint(3)) RETURNS varchar(20) CHARSET
latin1
DETERMINISTIC
BEGIN
DECLARE R_Level VARCHAR(20);
IF (rate>= 9 AND rate<=10) THEN SET R_Level = 'Excellent';
ELSEIF (rate>=7) THEN SET R_Level = 'Above standard';
ELSEIF (rate>= 5) THEN SET R_Level = 'standard';
ELSEIF (rate< 5) THEN SET R_Level = 'Below standard';
END IF;
RETURN (R_Level);
END $$
DELIMITER ;
11
Example 3
In Sailors Boats Reserve database we want to build a function that
computes the number of reserved boats of a sailor
DROP function IF EXISTS Nb_boats_reserved ;
DELIMITER $$
CREATE FUNCTION Nb_boats_reserved( id_sailors INT) RETURNS INT
DETERMINISTIC
BEGIN
DECLARE Nb_Boats INT;
SET Nb_Boats = 0;
SELECT count(*) INTO Nb_Boats
FROM reserve R
WHERE id_sailors = R.sid;
RETURN (Nb_Boats);
END $$
DELIMITER ; 12
Select S.sname, count(*)
From sailors S, reserve R
Where S.sid = R.sid
GROUP By S.sid;
Run 5 times implies compile 5 times and execute 5 times
5 times Cartesian product is executed
Select S.sname, Nb_Reserved_Boats(S.sid)
From sailors;
Much simpler to compile with the function already compiled
No Cartesian product, in case there exist a Cartesian product compiled
and executed only one time
13
Stored Procedures
A procedure (often called a stored procedure) is a subroutine like a
subprogram in a regular computing language, stored in database. A
procedure has a name, a parameter list, and SQL statement(s).
It is the group of SQL statements that accepts some input in the form
of parameters and performs some task and may or may not returns a
value.
Stored procedure inside it we have the ability to use/run sql
statements and functions.
14
Stored Procedures VS Functions
Stored Procedure Functions
You can use DML queries such as You cannot use a function with
insert, update, select etc… with Data Manipulation queries. Only
procedures. Select queries are allowed in
functions.
A procedure does not have a return A function has a return type and
type. But it returns values using the returns a value.
OUT parameters.
You can call a function from a You cannot call stored procedures
stored procedure. from a function
You cannot call a procedure using You can call a function using a
select statements. select statement.
We can use Transactions in we can't use Transactions in 15
Procedure Function
Stored Procedure Definition
General definition:
DELIMITER //
CREATE PROCEDURE NAME
BEGIN
SQL STATEMENT
END //
DELIMITER ;
Ex:
DELIMITER //
CREATE PROCEDURE GetAllProducts()
BEGIN
SELECT * FROM products;
END //
DELIMITER ;
16
Parameters Stored Procedures
Parameters: IN, OUT, INOUT
IN: The values being copied from the calling stored procedure are calling
arguments. The variables being copied into are called parameters.
Ex:
DELIMITER //
CREATE PROCEDURE GetOfficeByCountry(IN countryName VARCHAR(255))
BEGIN
SELECT * FROM offices WHERE country = countryName;
END //
DELIMITER ;
Run:
Call GetOfficeByCountry('USA')
17
Parameters Stored
Procedures(contd.)
OUT: the value of an OUT parameter can be changed inside the stored
procedure and its new value is passed back to the calling program
DELIMITER //
CREATE PROCEDURE CountOrderByStatus( IN orderStatus VARCHAR(25), OUT
total INT)
BEGIN
SELECT count(orderNumber) INTO total FROM orders WHERE status =
orderStatus;
END//
DELIMITER ;
Run:
CALL CountOrderByStatus('Shipped',@total);
SELECT @total;
18
Parameters Stored
Procedures(contd.)
DROP PROCEDURE IF EXISTS CountSailorsByRating;
DELIMITER $$
CREATE PROCEDURE CountSailorsByRating ( IN p_rating smallint(3), OUT total
INT)
BEGIN
SELECT count(*) INTO total FROM sailors WHERE rating = p_rating;
END $$
DELIMITER ;
Run:
CALL CountSailorsByRating (7,@total);
SELECT @total;
19
Stored Procedures Problem
Suppose that in the table employees the salaries existed in some
currency, and in the Lebanese currency. The manager decides to change
the amount of currency( from 1500 to 3900).
id Exchan
geRate
1 1500
Id EmpName Currency_i Salary SalaryL
d BP 2 2000
1 Adrien 1 1200 You have a table with 100000 records
and you decided to add a new
2 Jean marie 1 2000 column salaryLBP that can be derived
from Salary, what to do?
20
Stored Procedures Solution
DELIMITER $$
DROP PROCEDURE IF EXISTS update_salary;
CREATE PROCEDURE update_salary ()
BEGIN
DECLARE rowCount INT;
DECLARE currentRow INT;
DECLARE newsalary INT;
SET rowCount=(SELECT COUNT(*) FROM employee);
SET currentRow = 1;
WHILE (currentRow <= rowCount) DO
SET newsalary = (SELECT Salary FROM Employee WHERE id =
currentRow)*(select ExchangeRate from currency WHERE Id= (SELECT
currencyID from employee where id = currentRow));
UPDATE employee SET salaryLBP = newsalary WHERE Id = currentRow;
SET currentRow = currentRow + 1;
END WHILE;
END$$
DELIMITER ; 21