0% found this document useful (0 votes)
13 views63 pages

Mysql

Mysql database

Uploaded by

kmyozaw.dev
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
13 views63 pages

Mysql

Mysql database

Uploaded by

kmyozaw.dev
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 63

[Database Programming]

1/63
Contents at a Glance
1. SQL with MySQL ..................................................................................................................4
2. MySQL Functions ...............................................................................................................20
3. MySQL Stored Routines .................................................................................................... 48
Tables and Figures .................................................................................................................63

2/63
Table of Contents
1. SQL with MySQL ..................................................................................................................4
1.1. Standard SQL ................................................................................................................ 4
1.1.1. SQL Keywords ........................................................................................................ 4
1.2. MySQL Dialects ............................................................................................................. 5
1.2.1. Database Management .......................................................................................... 7
1.2.2. Data Types ..............................................................................................................9
1.2.3. SELECT Query ..................................................................................................... 10
1.2.4. Data Manipulation Language (DML) .................................................................... 15
1.2.5. Data Definition Language (DDL) .......................................................................... 17
2. MySQL Functions ...............................................................................................................20
2.1. Mathematic/Arithmetic Functions ................................................................................20
2.2. String Functions ...........................................................................................................30
2.3. Date/Time Functions ................................................................................................... 34
2.4. Control Functions ........................................................................................................ 41
2.5. Cast Functions .............................................................................................................45
2.6. Other Functions ........................................................................................................... 46
3. MySQL Stored Routines .................................................................................................... 48
3.1. Stored Procedure ........................................................................................................ 48
3.1.1. Benefits of using Stored Procedure ..................................................................... 48
3.1.2. Create and Drop Stored Procedure ..................................................................... 49
3.1.3. Variables ............................................................................................................... 51
3.1.4. Cursors ..................................................................................................................53
3.1.5. Condition and Exception Handlers .......................................................................55
3.1.6. Flow Controls ........................................................................................................ 55
3.2. Stored Function ........................................................................................................... 59
3.3. Database Trigger .........................................................................................................60
Tables and Figures .................................................................................................................63
Figures ................................................................................................................................ 63
Tables ................................................................................................................................. 63

3/63
1. SQL with MySQL

1.1. Standard SQL


1.1.1. SQL Keywords
SQL as a set of programming language specially developed for RDBMS, it can be
categorized as following groups and each group consists of several commands or
statements

 Data query group


SELECT is to retrieve data that consists of combination of rows and columns from table
as a result set. SELECT can be used with following keywords:

- FROM is to indicate from which tables the data need to be taken.


- JOIN is to combine tables under certain conditions. INNER, OUTER and FULL are
sub keyword can be used together with JOIN to specify types of joining tables.
- WHERE is a condition to identify which rows to be retrieved from the tables.
- GROUP BY is to combine rows under the same condition with related values.
- HAVING is to identify which of the "combined rows" are to be retrieved.
- ORDER BY is to sort result data set with specified columns.

 Data manipulation group


INSERT is to create a new row in tables.
UPDATE is to change existing data in table.
MERGE is to combine the data of multiple tables. It is something of a combination of the
INSERT and UPDATE.
DELETE is remove existing rows from tables.

 Data definition group


CREATE is to create database objects such as table, index.
DROP is to delete database objects
ALTER is to modify existing database objects
TRUNCATE is similar to DELETE however it destroys entire database object to
re-create. It is not transaction safe.

4/63
 Transaction control group
START TRANSACTION is to declare stating database transaction
SET TRANSACTION ISOLATION LEVEL is to specify four levels of isolation level in
order to avoid undesirable phenomena during database transaction.
COMMIT is to confirm all data changes in a transaction to be made permanent.
ROLLBAK is to cancel database transaction to rolls back status before it begins.

 Access privileges and authorization control group


GRANT is to permit to perform an operation or a set of operations on an object.
REVOKE is to remove permission that was given by GRANT.

1.2. MySQL Dialects


SQL statements discussed in this chapter are based on Standard SQL with MySQL dialects
as can be seen figure below:

MySQL PostgreSQL Oracle SQL Server


Dialects Dialects Dialects Dialects

Standard SQL

Figure 1 - Standard SQL and Dialects

Preparation: Please execute following SQL statements to create sample tables and user,
and insert sample data:
-- Create database
CREATE DATABASE test;

-- Create tables
USE test;
CREATE TABLE DEPT
(
DEPTNO NUMERIC(2) PRIMARY KEY,
DNAME VARCHAR(14) ,
LOC VARCHAR(13)
) ENGINE=InnoDB;

CREATE TABLE EMP


(

5/63
EMPNO NUMERIC(4) PRIMARY KEY,
ENAME VARCHAR(10),
JOB VARCHAR(9),
MGR NUMERIC(4),
HIREDATE DATE,
SAL NUMERIC(7,2),
COMM NUMERIC(7,2),
DEPTNO NUMERIC(2),
FOREIGN KEY(DEPTNO) REFERENCES DEPT(DEPTNO)
)ENGINE=InnoDB;

CREATE TABLE BONUS


(
ENAME VARCHAR(10),
JOB VARCHAR(9),
SAL NUMERIC,
COMM NUMERIC
)ENGINE=InnoDB;

CREATE TABLE SALGRADE


(
GRADE NUMERIC,
LOSAL NUMERIC,
HISAL NUMERIC
)ENGINE=InnoDB;

-- Insert records
INSERT INTO DEPT VALUES (10,'ACCOUNTING','NEW YORK');
INSERT INTO DEPT VALUES (20,'RESEARCH','DALLAS');
INSERT INTO DEPT VALUES (30,'SALES','CHICAGO');
INSERT INTO DEPT VALUES (40,'OPERATIONS','BOSTON');

INSERT INTO EMP VALUES


(7369,'SMITH','CLERK',7902,
str_to_date('17-12-1980','%d-%m-%Y'),800,NULL,20);
INSERT INTO EMP VALUES
(7499,'ALLEN','SALESMAN',7698,str_to_date('20-2-1981','%d-%m-%Y'),
1600,300,30);
INSERT INTO EMP VALUES
(7521,'WARD','SALESMAN',7698,str_to_date('22-2-1981','%d-%m-%Y'),
1250,500,30);
INSERT INTO EMP VALUES
(7566,'JONES','MANAGER',7839,str_to_date('2-4-1981','%d-%m-%Y'),2
975,NULL,20);
INSERT INTO EMP VALUES
(7654,'MARTIN','SALESMAN',7698,str_to_date('28-9-1981','%d-%m-%Y')

6/63
,1250,1400,30);
INSERT INTO EMP VALUES
(7698,'BLAKE','MANAGER',7839,str_to_date('1-5-1981','%d-%m-%Y'),2
850,NULL,30);
INSERT INTO EMP VALUES
(7782,'CLARK','MANAGER',7839,str_to_date('9-6-1981','%d-%m-%Y'),2
450,NULL,10);
INSERT INTO EMP VALUES
(7788,'SCOTT','ANALYST',7566,str_to_date('13-7-1987','%d-%m-%Y'),
3000,NULL,20);
INSERT INTO EMP VALUES
(7839,'KING','PRESIDENT',NULL,str_to_date('17-11-1981','%d-%m-%Y')
,5000,NULL,10);
INSERT INTO EMP VALUES
(7844,'TURNER','SALESMAN',7698,str_to_date('8-9-1981','%d-%m-%Y'),
1500,0,30);
INSERT INTO EMP VALUES
(7876,'ADAMS','CLERK',7788,str_to_date('13-7-1987',
'%d-%m-%Y'),1100,NULL,20);
INSERT INTO EMP VALUES
(7900,'JAMES','CLERK',7698,str_to_date('3-12-1981','%d-%m-%Y'),95
0,NULL,30);
INSERT INTO EMP VALUES
(7902,'FORD','ANALYST',7566,str_to_date('3-12-1981','%d-%m-%Y'),3
000,NULL,20);
INSERT INTO EMP VALUES
(7934,'MILLER','CLERK',7782,str_to_date('23-1-1982','%d-%m-%Y'),1
300,NULL,10);

INSERT INTO SALGRADE VALUES (1,700,1200);


INSERT INTO SALGRADE VALUES (2,1201,1400);
INSERT INTO SALGRADE VALUES (3,1401,2000);
INSERT INTO SALGRADE VALUES (4,2001,3000);
INSERT INTO SALGRADE VALUES (5,3001,9999);

1.2.1. Database Management


 SHOW
It provides various MySQL information as shown in table below:

Table 1 - SHOW Commands


SHOW Command Description
SHOW DATABASES Shows list of database
SHOW TABLES FROM database Shows list of tables from a database

7/63
SHOW CREATE DATABASE database Shows create database schema
SHOW CREATE TABLE table Shows create table schema
SHOW CREATE VIEW view Shows create view schema
SHOW CREATE PROCEDURE sp Shows create stored procedure schema
SHOW CREATE FUNCTION sf Shows create stored function schema
SHOW STATUS Shows status
SHOW TALBE STATUS Shows table status
SHOW ERRORS Shows errors
SHOW WARNINGS Shows warnings
SHOW GRANTS Shows grants
SHOW ENGINES Shows database engines
SHOW VARIABLES Shows variables
SHOW CHARACTER SET Shows character set
SHOW COLLATION Shows collation
SHOW PRIVILEGES Shows privileges
SHOW PROCESSLIST Shows list of MySQL processes and threads

mysql> SHOW DATABASES;


+--------------------+
| Database |
+--------------------+
| information_schema |
| myengine |
| mysql |
| s_sd_b |
| test |
+--------------------+
7 rows in set (0.00 sec)

mysql> SHOW PROCESSLIST;


+----+------+----------------+------+---------+------+-------+---
---------------+
| Id | User | Host | db | Command | Time | State | Info
|
+----+------+----------------+------+---------+------+-------+---
---------------+
| 1 | root | localhost:2867 | NULL | Query | 0 | NULL | SHOW
PROCESSLIST |
| 3 | root | localhost:2874 | NULL | Sleep | 5 | | NULL
|
+----+------+----------------+------+---------+------+-------+---
---------------+
2 rows in set (0.00 sec)

8/63
 USE database
It used to connect or change to specified database:
mysql> USE information_schema;
Database changed

1.2.2. Data Types


Tables below are MySQL data types by category such as Number, String, Date/Time and
BLOB.

 Number
Table 2 - MySQL Number Type
Type Description
TINYINT(length, decimal) 1 byte
SMALLINT(length) 2 byte
MEDIUMINT(length) 3 byte
INT(length) 4 byte
INTEGER(length) Synonym for INT
BIGINT(length) 8 byte
FLOAT(length) Single precision floating-point number
DOUBLE(length, decimal) Double precision floating-point number
REAL(length, decimal) Synonym for DOUBLE
DECIMAL(length, decimal) Fixed-point number
DEC(length, decimal) Synonym for DECIMAL
NUMERIC(length, decimal) Synonym for DECIMAL
FIXED(length, decimal) Synonym for DECIMAL
BOOL | BOOLEAN Synonym for TINYINT

 String
Table 3 - MySQL String Types
Type Description
CHAR(length) Fixed-length string, 0 to 255 character
VARCHAR(length) Variable-length string, 0 to 65525 byte
TINYTEXT 255 byte
TEXT 64 KB
MEDIUM TEXT 16 MB
LONG TEXT 4 GB

9/63
 Date/Time
Table 4 - MySQL Date/Time Type
Type Description
DATETIME YYYY-MM-DD HH:MM:SS
DATE YYYY-MM-DD
TIME HH:MM:SS
TIMESTAMP YYYY-MM-DD HH:MM:SS
YEAR YYYY

 BLOB (Binary Large Object)


Table 5 - MySQL BLOB Type
Type Description
TINYBLOB 255 byte
BLOB 64 KB
MEDIUMBLOB 16 MB
LONGBLOB 4 GB

1.2.3. SELECT Query


MySQL has some dialects to expand standard SELECT statement as listed below:

 SELECT ,,, FROM ,,, LIMIT / OFFSET


It limits number of rows to be retuned as shown in example as follows. LIMIT takes
one or two numeric arguments and those are non-negative integer numbers. The
first argument specifies the offset of the first row to return, and the second specifies
the maximum number of rows to return. The offset of the initial row is 0:
mysql> SELECT empno, ename, job FROM emp;
+-------+--------+-----------+
| empno | ename | job |
+-------+--------+-----------+
| 7369 | SMITH | CLERK |
| 7499 | ALLEN | SALESMAN |
| 7521 | WARD | SALESMAN |
| 7566 | JONES | MANAGER |
| 7654 | MARTIN | SALESMAN |
| 7698 | BLAKE | MANAGER |
| 7782 | CLARK | MANAGER |
| 7788 | SCOTT | ANALYST |

10/63
| 7839 | KING | PRESIDENT |
| 7844 | TURNER | SALESMAN |
| 7876 | ADAMS | CLERK |
| 7900 | JAMES | CLERK |
| 7902 | FORD | ANALYST |
| 7934 | MILLER | CLERK |
+-------+--------+-----------+
14 rows in set (0.00 sec)

mysql> SELECT empno, ename, job FROM emp LIMIT 0, 3;


+-------+-------+----------+
| empno | ename | job |
+-------+-------+----------+
| 7369 | SMITH | CLERK |
| 7499 | ALLEN | SALESMAN |
| 7521 | WARD | SALESMAN |
+-------+-------+----------+
3 rows in set (0.00 sec)

mysql> SELECT empno, ename, job FROM emp LIMIT 3;


+-------+-------+----------+
| empno | ename | job |
+-------+-------+----------+
| 7369 | SMITH | CLERK |
| 7499 | ALLEN | SALESMAN |
| 7521 | WARD | SALESMAN |
+-------+-------+----------+
3 rows in set (0.00 sec)

Note: As can be seen above two SQL with LIMIT, LIMIT 0, 3 and LIMIT
3 returns the same result. That means omitting the first argument is
same as 0.

mysql> SELECT empno, ename, job FROM emp LIMIT 3, 2;


+-------+--------+----------+
| empno | ename | job |
+-------+--------+----------+
| 7566 | JONES | MANAGER |
| 7654 | MARTIN | SALESMAN |
+-------+--------+----------+
2 rows in set (0.00 sec)

mysql> SELECT empno, ename, job FROM emp LIMIT 3 OFFSET 1;


+-------+-------+----------+
| empno | ename | job |
+-------+-------+----------+

11/63
| 7499 | ALLEN | SALESMAN |
| 7521 | WARD | SALESMAN |
| 7566 | JONES | MANAGER |
+-------+-------+----------+
3 rows in set (0.00 sec)

Note: LIMIT, OFFSET can be used for Web page search result navigation
like go to next or previous pages.

 SELECT expression UNION SELECT expression


It combines two SELECT statements with same definition of result set:
mysql> SELECT * FROM t1 UNION SELECT * FROM t2;
Note: MySQL 5.0 does not support FULL OUTER JOIN so that UNION with LEFT
OUTER JOIN and RIGHT OUTER JOIN can be used instead of FULL OUTER JOIN.

 SELECT ,,, FROM ,,, WHERE ,,, EXISTS / NOT EXISTS


EXISTS / NOT EXISTS can be used with sub-query. EXISTS returns TRUE if
Sub-query after EXISTS returns rows, if not EXISTS returns FALSE:
mysql> SELECT ename FROM EMP WHERE EXISTS(SELECT * FROM emp WHERE
ename='KING');
+--------+
| ename |
+--------+
| SMITH |
| ALLEN |
| WARD |
| JONES |
| MARTIN |
| BLAKE |
| CLARK |
| SCOTT |
| KING |
| TURNER |
| ADAMS |
| JAMES |
| FORD |
| MILLER |
+--------+
14 rows in set (0.00 sec)

mysql> SELECT ename FROM EMP WHERE NOT EXISTS(SELECT * FROM emp WHERE
ename='KING');
Empty set (0.00 sec)

12/63
 SELECT ,,, FROM ,,, WHERE ,,, ANY / ALL
ANY / ALL can be used with sub-query and either =,!=,>,<,<= or >=. Sub-query of
first example using ANY returns list of deptno (multiple rows) 10, 20, 40 and 50
hence the result of query returns list of employees except deptno 30. Sub-query of
second example using ALL also returns list of deptno (multiple rows) 10, 20, 40
and 50 hence the result of the query returns

mysql> SELECT * FROM dept;


+--------+------------+----------+
| DEPTNO | DNAME | LOC |
+--------+------------+----------+
| 10 | ACCOUNTING | NEW YORK |
| 20 | RESEARCH | DALLAS |
| 30 | SALES | CHICAGO |
| 40 | OPERATIONS | BOSTON |
| 50 | TRAINING | Yangon |
+--------+------------+----------+
5 rows in set (0.00 sec)

mysql> SELECT * FROM emp WHERE deptno = ANY(SELECT deptno FROM dept
WHERE loc <> 'CHICAGO');
+-------+--------+-----------+------+------------+---------+------+--------+
| EMPNO | ENAME | JOB | MGR | HIREDATE | SAL | COMM | DEPTNO |
+-------+--------+-----------+------+------------+---------+-----
-+--------+
| 7369 | SMITH | CLERK | 7902 | 1980-12-17 | 800.00 | NULL | 20 |
| 7566 | JONES | MANAGER | 7839 | 1981-04-02 | 2975.00 | NULL | 20 |
| 7782 | CLARK | MANAGER | 7839 | 1981-06-09 | 2450.00 | NULL | 10 |
| 7788 | SCOTT | ANALYST | 7566 | 1987-07-13 | 3000.00 | NULL | 20 |
| 7839 | KING | PRESIDENT | NULL | 1981-11-17 | 5000.00 | NULL | 10 |
| 7876 | ADAMS | CLERK | 7788 | 1987-07-13 | 1100.00 | NULL | 20 |
| 7902 | FORD | ANALYST | 7566 | 1981-12-03 | 3000.00 | NULL | 20 |
| 7934 | MILLER | CLERK | 7782 | 1982-01-23 | 1300.00 | NULL | 10 |
+-------+--------+-----------+------+------------+---------+-----
-+--------+
8 rows in set (0.00 sec)

mysql> SELECT * FROM emp WHERE deptno <> ALL(SELECT deptno FROM dept
WHERE loc <> 'CHICAGO');
+-------+--------+----------+------+------------+---------+------
---+--------+
| EMPNO | ENAME | JOB | MGR | HIREDATE | SAL | COMM |

13/63
DEPTNO |
+-------+--------+----------+------+------------+---------+------
---+--------+
| 7499 | ALLEN | SALESMAN | 7698 | 1981-02-20 | 1600.00 | 300.00 | 30 |
| 7521 | WARD | SALESMAN | 7698 | 1981-02-22 | 1250.00 | 500.00 | 30 |
| 7654 | MARTIN | SALESMAN | 7698 | 1981-09-28 | 1250.00 | 1400.00 | 30 |
| 7698 | BLAKE | MANAGER | 7839 | 1981-05-01 | 2850.00 | NULL | 30 |
| 7844 | TURNER | SALESMAN | 7698 | 1981-09-08 | 1500.00 | 0.00 | 30 |
| 7900 | JAMES | CLERK | 7698 | 1981-12-03 | 950.00 | NULL | 30 |
+-------+--------+----------+------+------------+---------+------
---+--------+
6 rows in set (0.00 sec)

 Self-Join statement
We have discussed join statements such as inter join and outer joins (left, right and
full outer) in the Fundamental Database, however there is another join statement
can be used and it is called as self-join. The Self-join statement can join same table
as recursive relationship. The example self-join statement for EMP table joins
empno and mgr columns. This self-join statement returns the result set of
employee and each one of their manager as can be seen below:

Emp

Figure 2 - Self-join (Recursive Relationship)

mysql> SELECT e.empno, e.ename AS 'Employee Name',


m.empno, m.ename AS 'Manager Name'
FROM emp e JOIN emp m
ON (e.mgr = m.empno)
ORDER BY m.ename;
+-------+---------------+-------+--------------+
| empno | Employee Name | empno | Manager Name |
+-------+---------------+-------+--------------+
| 7654 | MARTIN | 7698 | BLAKE |
| 7844 | TURNER | 7698 | BLAKE |
| 7499 | ALLEN | 7698 | BLAKE |
| 7521 | WARD | 7698 | BLAKE |
| 7900 | JAMES | 7698 | BLAKE |

14/63
| 7934 | MILLER | 7782 | CLARK |
| 7369 | SMITH | 7902 | FORD |
| 7788 | SCOTT | 7566 | JONES |
| 7902 | FORD | 7566 | JONES |
| 7566 | JONES | 7839 | KING |
| 7698 | BLAKE | 7839 | KING |
| 7782 | CLARK | 7839 | KING |
| 7876 | ADAMS | 7788 | SCOTT |
+-------+---------------+-------+--------------+
13 rows in set (0.00 sec)

1.2.4. Data Manipulation Language (DML)

 INSERT ,,, SELECT query


Result of SELECT query can be inserted into the table:
mysql> INSERT INTO t1(id) SELECT id FROM t2;

 INSERT multiple records


MySQL INSERT statement allows to insert multiple records as follows:
mysql> INSERT INTO t1 VALUES(1), (2), (3);

 REPLACE
REPLACE is mixture of INSERT with UPDATE when primary key exists:
mysql> SELECT * FROM dept;
+--------+------------+----------+
| DEPTNO | DNAME | LOC |
+--------+------------+----------+
| 10 | ACCOUNTING | NEW YORK |
| 20 | RESEARCH | DALLAS |
| 30 | SALES | CHICAGO |
| 40 | OPERATIONS | BOSTON |
+--------+------------+----------+
4 rows in set (0.19 sec)

mysql> REPLACE INTO dept VALUES(50, 'IT' ,'Yangon');


Query OK, 1 row affected (0.08 sec)

mysql> SELECT * FROM dept;


+--------+------------+----------+
| DEPTNO | DNAME | LOC |
+--------+------------+----------+

15/63
| 10 | ACCOUNTING | NEW YORK |
| 20 | RESEARCH | DALLAS |
| 30 | SALES | CHICAGO |
| 40 | OPERATIONS | BOSTON |
| 50 | IT | Yangon |
+--------+------------+----------+
5 rows in set (0.00 sec)

Note: A new row of DEPTNO=50 will be inserted because DEPTNO=50 does


not exists.

mysql> REPLACE INTO dept VALUES(50, 'TRAINING' ,'Yangon');


Query OK, 2 rows affected (0.06 sec)

mysql> SELECT * FROM dept;


+--------+------------+----------+
| DEPTNO | DNAME | LOC |
+--------+------------+----------+
| 10 | ACCOUNTING | NEW YORK |
| 20 | RESEARCH | DALLAS |
| 30 | SALES | CHICAGO |
| 40 | OPERATIONS | BOSTON |
| 50 | TRAINING | Yangon |
+--------+------------+----------+
5 rows in set (0.00 sec)

Note: The row of DEPTNO=50 will be updated because DEPTNO=50 has already
been existed.

 TRUNCATE
TRUNCATE drops table and re-create. It is not transaction safe:
mysql> SELECT COUNT(*) FROM t2;
+----------+
| COUNT(*) |
+----------+
| 3000 |
+----------+
1 row in set (0.00 sec)

mysql> TRUNCATE t2;


Query OK, 0 rows affected (0.01 sec)

mysql> SELECT COUNT(*) FROM t2;


+----------+

16/63
| COUNT(*) |
+----------+
| 0 |
+----------+
1 row in set (0.01 sec)

Note:
TRUNCATE is usually much faster than using DELETE however there is
no way to rollback truncated data is because TRUNCATE is not transaction
safe.

1.2.5. Data Definition Language (DDL)

 IF NOT EXISTS
IF NOT EXISTS is a keyword to check existence of same name when MySQL
database objects are created:
mysql> CREATE DATABASE IF NOT EXISTS msis;
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> CREATE DATABASE IF NOT EXISTS msis;


Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> SHOW WARNINGS;


+-------+------+------------------------------------------------+
| Level | Code | Message |
+-------+------+------------------------------------------------+
| Note | 1007 | Can't create database 'msis'; database exists |
+-------+------+------------------------------------------------+
1 row in set (0.00 sec)

Note: SHOW WARNINGS, SHOW ERRORS can display previously happened


warnings and errors.

 AUTO_INCREMENT
AUTO_INCREMENT is a keyword to define auto number:
mysql> CREATE TABLE mytable(id INT AUTO_INCREMENT, name TINYTEXT,
PRIMARY KEY(id));
Query OK, 0 rows affected (0.14 sec)

Note: DESC is short form of DESCRIBE to describe table definition.

mysql> DESC mytable;


+-------+----------+------+-----+---------+----------------+

17/63
| Field | Type | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | tinytext | YES | | NULL | |
+-------+----------+------+-----+---------+----------------+
2 rows in set (0.05 sec)

mysql> INSERT INTO mytable(name) VALUES('New Ni');


Query OK, 1 row affected (0.08 sec)

mysql> INSERT INTO mytable(name) VALUES('Aye');


Query OK, 1 row affected (0.03 sec)

mysql> INSERT INTO mytable(name) VALUES('Chaw');


Query OK, 1 row affected (0.08 sec)

mysql> SELECT * FROM mytable;


+----+--------+
| id | name |
+----+--------+
| 1 | New Ni |
| 2 | Aye |
| 3 | Chaw |
+----+--------+
3 rows in set (0.00 sec)

Note: id as integer, primary key column with AUTO_INCREMENT option


generates running number starting from 1.

 CREATE TABLE ,,, AS SELECT ,,,


It creates a new table based on the result of SELECT statement:
(However keys and keywords such as AUTO_INCREMENT does not copied)
mysql> SELECT * FROM mytable;
+----+--------+
| id | name |
+----+--------+
| 1 | New Ni |
| 2 | Aye |
| 3 | Chaw |
+----+--------+
3 rows in set (0.00 sec)

mysql> CREATE TABLE mytable2 AS SELECT * FROM mytable;


Query OK, 3 rows affected (0.17 sec)

18/63
Records: 3 Duplicates: 0 Warnings: 0

mysql> SELECT * FROM mytable2;


+----+--------+
| id | name |
+----+--------+
| 1 | New Ni |
| 2 | Aye |
| 3 | Chaw |
+----+--------+
3 rows in set (0.00 sec)

mysql> DESC mytable;


+-------+----------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | tinytext | YES | | NULL | |
+-------+----------+------+-----+---------+----------------+
2 rows in set (0.00 sec)

mysql> DESC mytable2;


+-------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id | int(11) | NO | | 0 | |
| name | tinytext | YES | | NULL | |
+-------+----------+------+-----+---------+-------+
2 rows in set (0.00 sec)

Note: mytable2 was created by mytable with the data however PRI (Primary
Key) and auto_increment were not copied from mytable.

19/63
2. MySQL Functions

2.1. Mathematic/Arithmetic Functions


 SUM(exp), AVG(exp)
It returns sum and average of exp. Following example returns total salary and
average salary by department:
mysql> SELECT deptno, SUM(sal), AVG(sal) FROM emp GROUP BY deptno;
+--------+----------+-------------+
| deptno | SUM(sal) | AVG(SAL) |
+--------+----------+-------------+
| 10 | 8750.00 | 2916.666667 |
| 20 | 10875.00 | 2175.000000 |
| 30 | 9400.00 | 1566.666667 |
+--------+----------+-------------+

 MAX(exp), MIN(exp)
It returns maximum and minimum value of exp. Following example returns
maximum and minimum salary from emp table:
mysql> SELECT MAX(sal), MIN(sal) FROM emp;
+----------+----------+
| MAX(sal) | MIN(sal) |
+----------+----------+
| 5000.00 | 800.00 |
+----------+----------+

 COUNT([DISTINCT] exp)
It returns a count of number of rows retrieved exclude NULL. Following example
returns count without DISTINCT and with DISTINCT:
mysql> SELECT COUNT(*) FROM emp;
+----------+
| COUNT(*) |
+----------+
| 14 |
+----------+

mysql> SELECT COUNT(DISTINCT deptno) FROM emp;


+------------------------+
| COUNT(DISTINCT deptno) |

20/63
+------------------------+
| 3 |
+------------------------+

 STD(exp), VARIANCE(exp)
It returns standard deviation and standard variance of exp:
mysql> SELECT deptno, STD(sal), VARIANCE(sal) FROM emp
GROUP BY deptno;
+--------+-------------+----------------+
| deptno | STD(sal) | VARIANCE(sal) |
+--------+-------------+----------------+
| 10 | 1546.142152 | 2390555.555556 |
| 20 | 1004.738772 | 1009500.000000 |
| 30 | 610.100174 | 372222.222222 |
+--------+-------------+----------------+

 GROUP_CONCAT(exp)
It returns a concatenated string from selected values. Following example displays
list of employee name by department:
mysql> SELECT deptno, GROUP_CONCAT(ename) FROM emp GROUP BY deptno;
+--------+--------------------------------------+
| deptno | GROUP_CONCAT(ename) |
+--------+--------------------------------------+
| 10 | CLARK,KING,MILLER |
| 20 | SMITH,JONES,SCOTT,ADAMS,FORD |
| 30 | ALLEN,WARD,MARTIN,BLAKE,TURNER,JAMES |
+--------+--------------------------------------+

 EXP(num), LN(num), LOG([base,] num), LOG2(num), LOG10(num)


It returns exponential function and logarithmic functions:
mysql> SELECT EXP(1);
+----------------+
| EXP(1) |
+----------------+
| 2.718281828459 |
+----------------+

mysql> SELECT LN(10);


+----------------+
| LN(10) |
+----------------+
| 2.302585092994 |

21/63
+----------------+

mysql> SELECT LOG(10, 100);


+--------------+
| LOG(10, 100) |
+--------------+
| 2 |
+--------------+

mysql> SELECT LOG2(100);


+-----------------+
| LOG2(100) |
+-----------------+
| 6.6438561897747 |
+-----------------+

mysql> SELECT LOG10(100);


+------------+
| LOG10(100) |
+------------+
| 2 |
+------------+

 ABS(num)
It returns absolute value of num:
mysql> SELECT ABS(10);
+---------+
| ABS(10) |
+---------+
| 10 |
+---------+

mysql> SELECT ABS(-10);


+----------+
| ABS(-10) |
+----------+
| 10 |
+----------+

 SQRT(num)
It returns square root of num:
mysql> SELECT SQRT(100);
+-----------+
| SQRT(100) |

22/63
+-----------+
| 10 |
+-----------+

mysql> SELECT SQRT(-100);


+------------+
| SQRT(-100) |
+------------+
| NULL |
+------------+

 CEILING(num), FLOOR(num), ROUND(num [,prec]), TRUNCATE(num [,prec])


Those are round up, round off functions. Please refer to Reference Manual for
details:
mysql> SELECT CEILING(4.56);
+---------------+
| CEILING(4.56) |
+---------------+
| 5 |
+---------------+

mysql> SELECT FLOOR(4.56);


+-------------+
| FLOOR(4.56) |
+-------------+
| 4 |
+-------------+

mysql> SELECT ROUND(4.56);


+-------------+
| ROUND(4.56) |
+-------------+
| 5 |
+-------------+

mysql> SELECT ROUND(4.56, 1);


+----------------+
| ROUND(4.56, 1) |
+----------------+
| 4.6 |
+----------------+

mysql> SELECT ROUND(4.56, 2);


+----------------+

23/63
| ROUND(4.56, 2) |
+----------------+
| 4.56 |
+----------------+

mysql> SELECT TRUNCATE(4.56, 0);


+-------------------+
| TRUNCATE(4.56, 0) |
+-------------------+
| 4 |
+-------------------+

mysql> SELECT TRUNCATE(4.56, 1);


+-------------------+
| TRUNCATE(4.56, 1) |
+-------------------+
| 4.5 |
+-------------------+

mysql> SELECT TRUNCATE(4.56, 2);


+-------------------+
| TRUNCATE(4.56, 2) |
+-------------------+
| 4.56 |
+-------------------+

 SIN(rad), COS(rad), TAN(rad), DEGREES(rad), RADIANS(x)


Those are trigonometric functions. Please refer to Reference Manual for details:
mysql> SELECT SIN(1.0);
+-----------------+
| SIN(1.0) |
+-----------------+
| 0.8414709848079 |
+-----------------+

mysql> SELECT COS(1.0);


+------------------+
| COS(1.0) |
+------------------+
| 0.54030230586814 |
+------------------+

mysql> SELECT TAN(1.0);


+-----------------+
| TAN(1.0) |

24/63
+-----------------+
| 1.5574077246549 |
+-----------------+

mysql> SELECT DEGREES(PI());


+---------------+
| DEGREES(PI()) |
+---------------+
| 180 |
+---------------+

mysql> SELECT RADIANS(180);


+-----------------+
| RADIANS(180) |
+-----------------+
| 3.1415926535898 |
+-----------------+

 RAND([seed])
It returns random number in between 0 to 1:
mysql> SELECT RAND();
+------------------+
| RAND() |
+------------------+
| 0.64443232365365 |
+------------------+

mysql> SELECT RAND(10);


+------------------+
| RAND(10) |
+------------------+
| 0.65705152196535 |
+------------------+

mysql> SELECT RAND(10);


+------------------+
| RAND(10) |
+------------------+
| 0.65705152196535 |
+------------------+

 GREATEST(x, …), LEAST(x, …)


It returns maximum, minimum values from parameter list:
mysql> SELECT GREATEST(10, 20, 30, 40);

25/63
+--------------------------+
| GREATEST(10, 20, 30, 40) |
+--------------------------+
| 40 |
+--------------------------+

mysql> SELECT LEAST(10, 20, 30, 40);


+-----------------------+
| LEAST(10, 20, 30, 40) |
+-----------------------+
| 10 |
+-----------------------+

 PI()
It returns the ratio of the circumference of a circle:
mysql> SELECT PI();
+----------+
| PI() |
+----------+
| 3.141593 |
+----------+

 CRC32(exp)
It returns computed cyclic redundancy check with a 32-bit unsigned exp:
mysql> SELECT CRC32('MySQL');
+----------------+
| CRC32('MySQL') |
+----------------+
| 3259397556 |
+----------------+

mysql> SELECT CRC32('MSIS');


+----------------+
| CRC32('MSIS') |
+----------------+
| 4112071447 |
+----------------+

 SIGN(num)
It returns the sign of the argument as -1, 0, or 1 that depend on whether num is
negative, zero, or positive:
mysql> SELECT SIGN(-5);

26/63
+----------+
| SIGN(-5) |
+----------+
| -1 |
+----------+

mysql> SELECT SIGN(5);


+---------+
| SIGN(5) |
+---------+
| 1 |
+---------+

mysql> SELECT SIGN(0);


+---------+
| SIGN(0) |
+---------+
| 0 |
+---------+

 POW(base, num), POWER(base, num)


Those are exponential functions and compute value of base raised to the power of
num:
mysql> SELECT POW(2,3);
+----------+
| POW(2,3) |
+----------+
| 8 |
+----------+

mysql> SELECT POWER(2,3);


+------------+
| POWER(2,3) |
+------------+
| 8 |
+------------+

 MOD(x, y)
It returns surplus of x divided by y:
mysql> SELECT MOD(9,3);
+----------+
| MOD(9,3) |
+----------+

27/63
| 0 |
+----------+

mysql> SELECT MOD(9,2);


+----------+
| MOD(9,2) |
+----------+
| 1 |
+----------+

 FORMAT(num, dec)
It formats num to a format like '#,###,###.##' with round off of dec and returns the
result as a string.
mysql> SELECT FORMAT(12345.6789, 4);
+-----------------------+
| FORMAT(12345.6789, 4) |
+-----------------------+
| 12,345.6789 |
+-----------------------+

mysql> SELECT FORMAT(12345.6789, 2);


+-----------------------+
| FORMAT(12345.6789, 2) |
+-----------------------+
| 12,345.68 |
+-----------------------+

mysql> SELECT FORMAT(12345.6789, 0);


+-----------------------+
| FORMAT(12345.6789, 0) |
+-----------------------+
| 12,346 |
+-----------------------+

 INTERVAL(num, list1, list2, …)


It returns 0 if num < list1, 1 if num < list2 and so on or -1 if num is NULL:
mysql> SELECT INTERVAL(23, 1, 15, 17, 30, 44, 200);
+--------------------------------------+
| INTERVAL(23, 1, 15, 17, 30, 44, 200) |
+--------------------------------------+
| 3 |
+--------------------------------------+

28/63
mysql> SELECT INTERVAL(10, 1, 10, 100, 1000);
+--------------------------------+
| INTERVAL(10, 1, 10, 100, 1000) |
+--------------------------------+
| 2 |
+--------------------------------+

mysql> SELECT INTERVAL(22, 23, 30, 44, 200);


+-------------------------------+
| INTERVAL(22, 23, 30, 44, 200) |
+-------------------------------+
| 0 |
+-------------------------------+

 BIN(num), CONV(num, from, to), HEX(num), OCT(num), UNHEX(str)


Those functions converts numbers between different number bases and returns
string representation of the number:
mysql> SELECT BIN(255);
+----------+
| BIN(255) |
+----------+
| 11111111 |
+----------+

mysql> SELECT CONV(11111111, 2, 10);


+-----------------------+
| CONV(11111111, 2, 10) |
+-----------------------+
| 255 |
+-----------------------+

mysql> SELECT HEX(255);


+----------+
| HEX(255) |
+----------+
| FF |
+----------+

mysql> SELECT UNHEX(41);


+-----------+
| UNHEX(41) |
+-----------+
| A |
+-----------+

29/63
2.2. String Functions
 ASCII(srt), CHAR(num, …), ORD(str)
Those functions are converting character and ASCII code:
mysql> SELECT ASCII('A');
+------------+
| ASCII('A') |
+------------+
| 65 |
+------------+

mysql> SELECT CHAR(65);


+----------+
| CHAR(65) |
+----------+
| A |
+----------+

mysql> SELECT ORD('A');


+----------+
| ORD('A') |
+----------+
| 65 |
+----------+

Note:
ORD returns the code for that character in case if the leftmost
character of the string is a multi-byte character.
If the leftmost character is NOT a multi-byte character, ORD() then
it returns the same value as what ASCII() function returns.

 BIT_LENGTH(str), CHAR_LENGTH(srt), LENGTH(str)


It returns length of string by bit, by character, by byte:
mysql> SELECT BIT_LENGTH('MSIS');
+---------------------+
| BIT_LENGTH('MSIS') |
+---------------------+
| 32 |
+---------------------+

mysql> SELECT CHAR_LENGTH('MSIS');


+----------------------+
| CHAR_LENGTH('MSIS') |

30/63
+----------------------+
| 4 |
+----------------------+

mysql> SELECT LENGTH('MSIS');


+-----------------+
| LENGTH('MSIS') |
+-----------------+
| 4 |
+-----------------+

Note:
If the database uses multi-byte character set, then CHAR_LENGTH and
LENGTH may returns the different numbers.

 STRCOMP(str1, str2)
It returns 0 if str1=str2, -1 if str1 < str2 or 1 if str1>str2:
mysql> SELECT STRCMP('ABC', 'ABC');
+----------------------+
| STRCMP('ABC', 'ABC') |
+----------------------+
| 0 |
+----------------------+

mysql> SELECT STRCMP('ABC', 'DEF');


+----------------------+
| STRCMP('ABC', 'DEF') |
+----------------------+
| -1 |
+----------------------+

mysql> SELECT STRCMP('DEF', 'ABC');


+----------------------+
| STRCMP('DEF', 'ABC') |
+----------------------+
| 1 |
+----------------------+

 CONCAT(str1, str2, …), CONCAT_WS(separator, str1, str2, …)


It returns concatenated string and separator:
mysql> SELECT CONCAT('ABC', 'DEF', 'GHI');
+-----------------------------+
| CONCAT('ABC', 'DEF', 'GHI') |
+-----------------------------+

31/63
| ABCDEFGHI |
+-----------------------------+

mysql> SELECT CONCAT_WS('-', 'ABC', 'DEF', 'GHI');


+-------------------------------------+
| CONCAT_WS('-', 'ABC', 'DEF', 'GHI') |
+-------------------------------------+
| ABC-DEF-GHI |
+-------------------------------------+

 INSERT (str, start, len, to), REPLACE(str, from, to)


It returns replaced str based on condition of replacement:
mysql> SELECT INSERT('Welcome to MSIS', 1, 10, 'Min ga la ba');
+---------------------------------------------------+
| INSERT('Welcome to MSIS', 1, 10, 'Min ga la ba') |
+---------------------------------------------------+
| Min ga la ba MSIS |
+---------------------------------------------------+

mysql> SELECT REPLACE('Welcome to MSIS', 'Welcome to', 'Min ga la ba');


+-----------------------------------------------------------+
| REPLACE('Welcome to MSIS', 'Welcome to', 'Min ga la ba') |
+-----------------------------------------------------------+
| Min ga la ba MSIS |
+-----------------------------------------------------------+

 INSTR(str, substr), POSITION(substr IN str)


It returns position of first occurrence of substr in str:
mysql> SELECT INSTR('MSIS', 'I');
+---------------------+
| INSTR('MSIS', 'I') |
+---------------------+
| 3 |
+---------------------+

mysql> SELECT POSITION('I' IN 'MSIS');


+--------------------------+
| POSITION('I' IN 'MSIS') |
+--------------------------+
| 3 |
+--------------------------+

 LOWER(str), UPPER(str)

32/63
It returns lower case str, upper case str:
mysql> SELECT LOWER('MSIS');
+----------------+
| LOWER('MSIS') |
+----------------+
| msis |
+----------------+

mysql> SELECT UPPER('msis');


+----------------+
| UPPER('msis') |
+----------------+
| MSIS |
+----------------+

 LEFT(str, len), RIGHT(str, len), MID(str, pos, len)


It returns leftmost, rightmost, midmost len of characters:
mysql> SELECT LEFT('MSIS', 3);
+------------------+
| LEFT('MSIS', 3) |
+------------------+
| MSI |
+------------------+

mysql> SELECT RIGHT('MSIS', 3);


+-------------------+
| RIGHT('MSIS', 3) |
+-------------------+
| SIS |
+-------------------+

mysql> SELECT MID('MSIS', 2, 3);


+--------------------+
| MID('MSIS', 2, 3) |
+--------------------+
| SIS |
+--------------------+

 LTRIM (str), RTRIM (str), TRIM(str)


It returns str without space characters (leading, trailing, both):
mysql> SELECT LTRIM(' MSIS ');
+----------------------+
| LTRIM(' MSIS ') |

33/63
+----------------------+
| MSIS |
+----------------------+

mysql> SELECT RTRIM(' MSIS ');


+----------------------+
| RTRIM(' MSIS ') |
+----------------------+
| MSIS |
+----------------------+

mysql> SELECT TRIM(' MSIS ');


+---------------------+
| TRIM(' MSIS ') |
+---------------------+
| MSIS |
+---------------------+

2.3. Date/Time Functions


Table below is a list of parameters can be used for following date and time functions:

Table 6 - List of parameters for Date and Time functions


Parameter type Parameter var format
SECOND Second
MINUTE Minute
HOUR Hour
DAY Day
MONTH Month
YEAR Year
MINUTE_SECOND ‘Minute:Second’
HOUR_MINUTE ‘Hour:Minute’
DAY_HOUR ‘Day Hour’
YEAR_MONTH ‘Year-Month’
HOUR_SECOND ‘Hour.Minute.Second’
DAY_MINUTE ‘Day.Minute’
DAY_SECOND ‘Day Hour:Minute:Second’
DAY_MICROSECOND ‘Day.Microsecond’
HOUR_MICROSECOND ‘Hour.Microsecond’
MINUTE_MICROSECOND ‘Minute.Microsecond’
SECOND_MICROSECOND ‘Second.Microsecond’

34/63
MICROSECOND ‘Microsecond’

 ADDDATE(dat, days | INTERVAL var type),


SUBDATE(dat, days | INTERVAL var type)
Add, subtract date with specified conditions:
mysql> SELECT ADDDATE('1962-05-30', INTERVAL '44 11' YEAR_MONTH);
+----------------------------------------------------+
| ADDDATE('1962-05-30', INTERVAL '44 11' YEAR_MONTH) |
+----------------------------------------------------+
| 2007-04-30 |
+----------------------------------------------------+

mysql> SELECT SUBDATE('2007-04-30', INTERVAL '44 11' YEAR_MONTH);


+----------------------------------------------------+
| SUBDATE('2007-04-30', INTERVAL '44 11' YEAR_MONTH) |
+----------------------------------------------------+
| 1962-05-30 |
+----------------------------------------------------+

 ADDTIME(day, time), SUBTIME(day, time)


Add, subtract time with specified conditions:
mysql> SELECT ADDTIME('2007-05-22 11:30:00', '00:30:00');
+--------------------------------------------+
| ADDTIME('2007-05-22 11:30:00', '00:30:00') |
+--------------------------------------------+
| 2007-05-22 12:00:00 |
+--------------------------------------------+

mysql> SELECT SUBTIME('2007-05-22 11:30:00', '00:30:00');


+--------------------------------------------+
| SUBTIME('2007-05-22 11:30:00', '00:30:00') |
+--------------------------------------------+
| 2007-05-22 11:00:00 |
+--------------------------------------------+

 CURDATE(), UTC_DATE(), CURTIME(), UTC_TIME(),


NOW(), UTC_TIMESTAMP()
It returns current date, Coordinated Universal Time (UTC) date, current time and
Coordinated Universal Time (UTC) time:
mysql> SELECT CURDATE();
+------------+
| CURDATE() |

35/63
+------------+
| 2007-05-20 |
+------------+

mysql> SELECT UTC_DATE();


+------------+
| UTC_DATE() |
+------------+
| 2007-05-20 |
+------------+

mysql> SELECT CURTIME();


+-----------+
| CURTIME() |
+-----------+
| 15:28:32 |
+-----------+

mysql> SELECT UTC_TIME();


+------------+
| UTC_TIME() |
+------------+
| 08:58:39 |
+------------+

mysql> SELECT NOW();


+---------------------+
| NOW() |
+---------------------+
| 2007-05-20 15:28:45 |
+---------------------+

mysql> SELECT UTC_TIMESTAMP();


+---------------------+
| UTC_TIMESTAMP() |
+---------------------+
| 2007-05-20 08:58:55 |
+---------------------+

 DATE(dat), DAYNAME(dat), DAYOFMONTH(dat), DAYOFWEEK(dat),


DAYOFYEAR(dat), LAST_DAY(dat)
It returns specific element of date:
mysql> SELECT DATE(NOW());
+-------------+

36/63
| DATE(NOW()) |
+-------------+
| 2007-05-20 |
+-------------+

mysql> SELECT DAYNAME(NOW());


+----------------+
| DAYNAME(NOW()) |
+----------------+
| Sunday |
+----------------+

mysql> SELECT DAYOFWEEK(NOW());


+------------------+
| DAYOFWEEK(NOW()) |
+------------------+
| 1 |
+------------------+

mysql> SELECT DAYOFMONTH(NOW());


+-------------------+
| DAYOFMONTH(NOW()) |
+-------------------+
| 20 |
+-------------------+

mysql> SELECT DAYOFYEAR(NOW());


+------------------+
| DAYOFYEAR(NOW()) |
+------------------+
| 140 |
+------------------+

mysql> SELECT LAST_DAY(NOW());


+-----------------+
| LAST_DAY(NOW()) |
+-----------------+
| 2007-05-31 |
+-----------------+

 YEAR(dat), YEARWEEK(dat), QUARTER(dat), MONTH(dat),


WEEK(dat), WEEKDAY(dat), WEEKOFYEAR(dat)
It returns specific element of year, quarter, month, week:
mysql> SELECT YEAR(NOW());

37/63
+-------------+
| YEAR(NOW()) |
+-------------+
| 2007 |
+-------------+

mysql> SELECT YEARWEEK(NOW());


+-----------------+
| YEARWEEK(NOW()) |
+-----------------+
| 200720 |
+-----------------+

mysql> SELECT QUARTER(NOW());


+----------------+
| QUARTER(NOW()) |
+----------------+
| 2 |
+----------------+

mysql> SELECT MONTH(NOW());


+--------------+
| MONTH(NOW()) |
+--------------+
| 5 |
+--------------+

mysql> SELECT WEEK(NOW());


+-------------+
| WEEK(NOW()) |
+-------------+
| 20 |
+-------------+

mysql> SELECT WEEKDAY(NOW());


+----------------+
| WEEKDAY(NOW()) |
+----------------+
| 6 |
+----------------+

mysql> SELECT WEEKOFYEAR(NOW());


+-------------------+
| WEEKOFYEAR(NOW()) |
+-------------------+
| 20 |

38/63
+-------------------+

 TIME(dat), MINUTE(dat), SECOND(dat)


It returns specific element of time:
mysql> SELECT TIME(NOW());
+-------------+
| TIME(NOW()) |
+-------------+
| 15:55:20 |
+-------------+

mysql> SELECT MINUTE(NOW());


+---------------+
| MINUTE(NOW()) |
+---------------+
| 55 |
+---------------+

mysql> SELECT SECOND(NOW());


+---------------+
| SECOND(NOW()) |
+---------------+
| 41 |
+---------------+

 DATE_FORMAT(dat, format), TIME_FORMAT(tim, format)


It formats and returns dat according to format:
mysql> SELECT DATE_FORMAT(NOW(), '%d-%b-%Y');
+--------------------------------+
| DATE_FORMAT(NOW(), '%d-%b-%Y') |
+--------------------------------+
| 20-May-2007 |
+--------------------------------+

mysql> SELECT TIME_FORMAT(NOW(), '%r');


+--------------------------+
| TIME_FORMAT(NOW(), '%r') |
+--------------------------+
| 04:30:58 PM |
+--------------------------+

39/63
Table 7 - Format type for Date/Time Functions
Format type Description
%a Day (Sun - Sat)
%b Month (Jan - Dec)
%c Month (0 - 12)
%D Day (1sr, 2nd, 3rd ,,,)
%d Day (00 -31)
%e Day (0 - 31)
%f Microsecond
%H Time (00 - 23)
%h Time (01 - 12)
%l Time (01 - 12)
%i Minute (00 - 59)
%j Days of Year (001 - 336)
%k Time (0 - 23)
%l Time (1 - 12)
%M Month (January - December)
%m Month (00 - 12)
%p AM | PM
%r hh:mm:ss AM/PM
%S Second (00 - 59)
%s Second (00 - 59)
%T hh:mm:ss
%U Week of Year (00 – 53, Start at Sunday)
%u Week of Year (00 - 53, Start at Monday)
%V Together with %X
%v Together with %X
%W Day (Sunday - Saturday)
%w Day (0 - 6)
%X Together with %V
%x Together with %V
%Y Year (4digits)
%y Year (2 digits)
%% ‘%’ Literal

 STR_TO_DATE(str, format)
It is inverse of DATE_FORMAT function:
mysql> SELECT STR_TO_DATE('07 May 20th', '%y %M %D');

40/63
+----------------------------------------+
| STR_TO_DATE('07 May 20th', '%y %M %D') |
+----------------------------------------+
| 2007-05-20 |
+----------------------------------------+

 DATEDIFF( expr1, expr2)


It returns expr1 - expr2 difference of the date in days from one date to the other.
expr1 and expr2 must be date type or date-and-time type:
mysql> SELECT DATEDIFF('2007/07/05', '2007/07/03');
+--------------------------------------+
| DATEDIFF('2007/07/05', '2007/07/03') |
+--------------------------------------+
| 2 |
+--------------------------------------+
1 row in set (0.00 sec)

Note: Difference from '2007/07/05' to '2007/07/03' is 2.

mysql> SELECT DATEDIFF('2007/07/05', '2007/07/05');


+--------------------------------------+
| DATEDIFF('2007/07/05', '2007/07/05') |
+--------------------------------------+
| 0 |
+--------------------------------------+
1 row in set (0.00 sec)

Note: Difference from '2007/07/05' to '2007/07/05' is 0.

2.4. Control Functions


 IF(exp, var1, var2)
It returns var1 if exp is TRUE and returns var2 if exp is FALSE:
mysql> SELECT IF(2>1, 'Correct', 'Wrong');
+-----------------------------+
| IF(2>1, 'Correct', 'Wrong') |
+-----------------------------+
| Correct |
+-----------------------------+

mysql> SELECT IF(2<1, 'Correct', 'Wrong');


+-----------------------------+
| IF(2<1, 'Correct', 'Wrong') |

41/63
+-----------------------------+
| Wrong |
+-----------------------------+

mysql> SELECT ename, comm FROM emp WHERE deptno = 30;


+--------+---------+
| ename | comm |
+--------+---------+
| ALLEN | 300.00 |
| WARD | 500.00 |
| MARTIN | 1400.00 |
| BLAKE | NULL |
| TURNER | 0.00 |
| JAMES | NULL |
+--------+---------+

mysql> SELECT ename, IF(comm IS NOT NULL, comm, 0.00) AS Commission


FROM emp WHERE deptno=30;
+--------+------------+
| ename | Commission |
+--------+------------+
| ALLEN | 300.00 |
| WARD | 500.00 |
| MARTIN | 1400.00 |
| BLAKE | 0.00 |
| TURNER | 0.00 |
| JAMES | 0.00 |
+--------+------------+

 CASE
CASE function execute statements that matches with specified value or condition
after WHEN. There are two types of CASE conditional function such as Value type
and Condition type as stated in following table:

Table 8 - CASE syntax


Type Syntax
Value Type CASE var
WHEN value1 THEN result1
WHEN value2 THEN result2
ELSE resultElse
END
Condition Type CASE
WHEN condition1 THEN result1

42/63
WHEN condition2 THEN result2
ELSE resultElse
END

mysql> SELECT empno, ename, job, sal, comm FROM emp;


+-------+--------+-----------+---------+---------+
| empno | ename | job | sal | comm |
+-------+--------+-----------+---------+---------+
| 7369 | SMITH | CLERK | 800.00 | NULL |
| 7499 | ALLEN | SALESMAN | 1600.00 | 300.00 |
| 7521 | WARD | SALESMAN | 1250.00 | 500.00 |
| 7566 | JONES | MANAGER | 2975.00 | NULL |
| 7654 | MARTIN | SALESMAN | 1250.00 | 1400.00 |
| 7698 | BLAKE | MANAGER | 2850.00 | NULL |
| 7782 | CLARK | MANAGER | 2450.00 | NULL |
| 7788 | SCOTT | ANALYST | 3000.00 | NULL |
| 7839 | KING | PRESIDENT | 5000.00 | NULL |
| 7844 | TURNER | SALESMAN | 1500.00 | 0.00 |
| 7876 | ADAMS | CLERK | 1100.00 | NULL |
| 7900 | JAMES | CLERK | 950.00 | NULL |
| 7902 | FORD | ANALYST | 3000.00 | NULL |
| 7934 | MILLER | CLERK | 1300.00 | NULL |
+-------+--------+-----------+---------+---------+

mysql> SELECT empno, ename, job,


CASE job
WHEN 'CLERK' THEN 'LEVEL 1'
WHEN 'SALESMAN' THEN 'LEVEL 2'
WHEN 'ANALYST' THEN 'LEVEL 2'
WHEN 'MANAGER' THEN 'LEVEL 3'
ELSE 'LEVEL 4'
END AS Grade FROM emp;
+-------+--------+-----------+---------+
| empno | ename | job | Grade |
+-------+--------+-----------+---------+
| 7369 | SMITH | CLERK | LEVEL 1 |
| 7499 | ALLEN | SALESMAN | LEVEL 2 |
| 7521 | WARD | SALESMAN | LEVEL 2 |
| 7566 | JONES | MANAGER | LEVEL 3 |
| 7654 | MARTIN | SALESMAN | LEVEL 2 |
| 7698 | BLAKE | MANAGER | LEVEL 3 |
| 7782 | CLARK | MANAGER | LEVEL 3 |
| 7788 | SCOTT | ANALYST | LEVEL 2 |
| 7839 | KING | PRESIDENT | LEVEL 4 |
| 7844 | TURNER | SALESMAN | LEVEL 2 |

43/63
| 7876 | ADAMS | CLERK | LEVEL 1 |
| 7900 | JAMES | CLERK | LEVEL 1 |
| 7902 | FORD | ANALYST | LEVEL 2 |
| 7934 | MILLER | CLERK | LEVEL 1 |
+-------+--------+-----------+---------+

Note: Job Grade can be categorized by CASE.

mysql> SELECT empno, ename,


CASE
WHEN comm >= 1000 THEN '20%'
WHEN comm < 1000 THEN '10%'
ELSE ' 0%'
END AS tax FROM emp;
+-------+--------+------+
| empno | ename | tax |
+-------+--------+------+
| 7369 | SMITH | 0% |
| 7499 | ALLEN | 10% |
| 7521 | WARD | 10% |
| 7566 | JONES | 0% |
| 7654 | MARTIN | 20% |
| 7698 | BLAKE | 0% |
| 7782 | CLARK | 0% |
| 7788 | SCOTT | 0% |
| 7839 | KING | 0% |
| 7844 | TURNER | 10% |
| 7876 | ADAMS | 0% |
| 7900 | JAMES | 0% |
| 7902 | FORD | 0% |
| 7934 | MILLER | 0% |
+-------+--------+------+

Note: Tax can be categorized based on commission by CASE.

mysql> SELECT
SUM(CASE WHEN deptno = 10 THEN 1 ELSE 0 END) AS DEPT10,
SUM(CASE WHEN deptno = 20 THEN 1 ELSE 0 END) AS DEPT20,
SUM(CASE WHEN deptno = 30 THEN 1 ELSE 0 END) AS DEPT30,
SUM(CASE WHEN deptno = 40 THEN 1 ELSE 0 END) AS DEPT40
FROM emp;
+--------+--------+--------+--------+
| DEPT10 | DEPT20 | DEPT30 | DEPT40 |
+--------+--------+--------+--------+
| 3 | 5 | 6 | 0 |
+--------+--------+--------+--------+

44/63
1 row in set (0.00 sec)

Note: Number of employee by department calculated by CASE.

2.5. Cast Functions


 CAST(exp AS type)
It convert to another type that specified as parameter such as BINARY, CHAR,
DATE, DATETIME, TIME, SIGNED INTEGER, UNSIGNED INTEGER:
mysql> SELECT CAST(NOW() AS DATE);
+---------------------+
| CAST(NOW() AS DATE) |
+---------------------+
| 2007-05-20 |
+---------------------+

mysql> SELECT CAST(NOW() AS TIME);


+---------------------+
| CAST(NOW() AS TIME) |
+---------------------+
| 20:01:04 |
+---------------------+

mysql> SELECT CAST(12.345 AS UNSIGNED INTEGER);


+----------------------------------+
| CAST(12.345 AS UNSIGNED INTEGER) |
+----------------------------------+
| 12 |
+----------------------------------+

mysql> SELECT CAST(-12.345 AS SIGNED INTEGER);


+---------------------------------+
| CAST(-12.345 AS SIGNED INTEGER) |
+---------------------------------+
| -12 |
+---------------------------------+

 BINARY(str)
It converts and returns binary byte string from non-binary string:
mysql> SELECT ename FROM emp WHERE ename = 'scott';
+-------+
| ename |
+-------+

45/63
| SCOTT |
+-------+
1 row in set (0.00 sec)

mysql> SELECT ename FROM emp WHERE BINARY(ename) = 'scott';


Empty set (0.00 sec)

2.6. Other Functions

 COALESCE(value1, value2, …)
COALESCE returns first non-NUL value from value list or returns NULL if there are
no non-NULL values:
mysql> SELECT COALESCE(NULL, NULL, 2, NULL);
+-------------------------------+
| COALESCE(NULL, NULL, 2, NULL) |
+-------------------------------+
| 2 |
+-------------------------------+

mysql> SELECT COALESCE(NULL, NULL, NULL, NULL);


+----------------------------------+
| COALESCE(NULL, NULL, NULL, NULL) |
+----------------------------------+
| NULL |
+----------------------------------+

mysql> SELECT ename, sal, comm, sal + COALESCE(comm, 0) AS total FROM


emp;
+--------+---------+---------+---------+
| ename | sal | comm | total |
+--------+---------+---------+---------+
| SMITH | 800.00 | NULL | 800.00 |
| ALLEN | 1600.00 | 300.00 | 1900.00 |
| WARD | 1250.00 | 500.00 | 1750.00 |
| JONES | 2975.00 | NULL | 2975.00 |
| MARTIN | 1250.00 | 1400.00 | 2650.00 |
| BLAKE | 2850.00 | NULL | 2850.00 |
| CLARK | 2450.00 | NULL | 2450.00 |
| SCOTT | 3000.00 | NULL | 3000.00 |
| KING | 5000.00 | NULL | 5000.00 |
| TURNER | 1500.00 | 0.00 | 1500.00 |
| ADAMS | 1100.00 | NULL | 1100.00 |

46/63
| JAMES | 950.00 | NULL | 950.00 |
| FORD | 3000.00 | NULL | 3000.00 |
| MILLER | 1300.00 | NULL | 1300.00 |
+--------+---------+---------+---------+
14 rows in set (0.00 sec)

Note: COALESCE(comm, 0) returns value of commission if comm is not


null or returns 0 if comm is null.

 MD5(string), SHA1(string)
Those functions compute hash value and return. MD5 (Message Digest Algorithm)
returns 128-bit checksum in 32-bit hexadecimal notation and SHA1 (Secure Hash
Algorithm) returns 160-bit checksum in 40-bit hexadecimal notation:

mysql> SELECT MD5('ono');


+----------------------------------+
| MD5('ono') |
+----------------------------------+
| c722afe23409c2d50a32c93fc709e861 |
+----------------------------------+
1 row in set (0.00 sec)

mysql> SELECT SHA1('ono');


+------------------------------------------+
| SHA1('ono') |
+------------------------------------------+
| 1fb10f267c25634a7530695349b995f13045be36 |
+------------------------------------------+
1 row in set (0.00 sec)

47/63
3. MySQL Stored Routines

3.1. Stored Procedure

3.1.1. Benefits of using Stored Procedure


Stored Procedure is a procedural language program with a set of SQL which is physically
stored within a database server. The advantage of using stored procedures is its
performance because of the procedure as pre-compiled program that executed in the
database server. This is to reduce communication cost between client applications and
provide better security environment. MySQL 5.0 supports SQL:2003 standard syntax.

Table 9 - RDBMS and Stored Procedure


RDBMS Provided by Stored Procedure Language
Oracle Oracle PL/SQL
SQL Server Microsoft Transact-SQL
DB2 IBM SQL:2003
PostgreSQL PostgreSQL Global Development Group PL/pgSQL
MySQL(5.0) MySQL AB SQL:2003

Client send SQL statements individually

INSERT

UPDATE

DELETE

Client calls a stored procedure (SP)


SP
Call SP INSERT

Return result of the SP UPDATE


DELETE

Figure 3 - SQL and Stored Procedure (SP)

48/63
3.1.2. Create and Drop Stored Procedure
CREATE PROCEDURE statement creates a stored procedure and body of the stored
procedure starts with BEGIN and end with END. The stored procedure can be deleted by
DROP PROCEDURE statement. The stored procedure takes parameters and each
parameter has own direction such as stated in table below:

Table 10 - Parameter Direction


Direct Description
IN Input Parameter
OUT Output Parameter
INOUT Input/Output Parameter

Following access privileges are required for MySQL user who need to create, amend and
execute stored procedures:

Table 11 - Access Privileges needed for Stored Procedure


Privilege Description
CREATE ROUTINE To create a stored procedure
ALTER ROUTINE To amend the stored procedure
EXECUTE To execute the stored procedure

mysql> GRANT CREATE ROUTINE, ALTER ROUTINE, EXECUTE ON sp.* TO


scott@localhost;
Query OK, 0 rows affected (0.03 sec)

Syntax of create a stored procedure is as follows:


CREATE PROCEDURE name ([direct] parameter type, …) [characteristic]
BEGIN body END

Syntax of drop the stored procedure is as follows. [IF EXISTS] is an option to drop when
stored procedure is already existed:
DROP PROCEDURE [IF EXISTS] name;

The stored procedure will be invoked by CALL statement with name of the stored procedure
and parameters according to definition as following syntax:
CALL name(parameter[, ...])

49/63
The following is an example of a simple stored procedure with IN parameter. The example
takes price as for WHERE condition and execute SELECT statement. The example uses the
mysql client DELIMITER command to change the statement delimiter from ; to // while the
procedure is being defined. This allows the ; delimiter used in the procedure body to be
passed through to the server rather than being interpreted by mysql itself. The // changes
back to ; after creation of the stored procedure with DELIMTER ; command.

Following SQL is for preparation to create sample tables during this chapter:
DROP TABLE IF EXISTS `book`;
CREATE TABLE `book` (
`id` int(11) NOT NULL,
`title` varchar(50) default NULL,
`isbn` varchar(50) default NULL,
`price` int(11) default '0',
`author_id` varchar(50) default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

DROP TABLE IF EXISTS `book_history`;


CREATE TABLE `book_history` (
`id` int(11) NOT NULL auto_increment,
`book_id` int(11) default NULL,
`title` varchar(50) default NULL,
`price_before` int(11) default NULL,
`price_after` int(11) default NULL,
`updated` datetime default NULL,
`event` varchar(50) default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `book` VALUES (1,'Introduction to


MySQL','1-1111-1111-1',285,'01'),(2,'Introduction to
PostgreSQL','1-1111-1111-2',300,'01'),(3,'Introduction to
Database','1-1111-1111-3',500,'01'),(4,'Introduction to
Java','1-1111-1111-4',750,'02');

mysql> DELIMITER //
mysql> CREATE PROCEDURE sp01 (IN p INT)
BEGIN
SELECT id, title, price FROM BOOK WHERE price > p;
END
//
Query OK, 0 rows affected (0.09 sec)

50/63
Note: DELIMITER ; is to set back the delimiter as ;. You can not execute
subsequence SQL commands if you have forgotten this command.

mysql> DELIMITER ;
mysql> CALL sp01(400);
+----+--------------------------+-------+
| id | title | price |
+----+--------------------------+-------+
| 3 | Introduction to Database | 500 |
| 4 | Introduction to Java | 750 |
+----+--------------------------+-------+
2 rows in set (0.11 sec)

Note: Stored Procedure sp01 selects books from book table with the
price more than 400.

3.1.3. Variables
Local variables can be used in Stored Procedure with following expressions:
SELECT column[,...] INTO variable[,...] FROM table WHERE conditions

SELECT title, price

INTO , FROM book;

Variable Variable

Figure 4 - SELECT INTO and Local Variable

Example of local variables which takes IN and OUT parameter is as follows. The example
takes price as input parameter and set output parameter as number of books that price is
higher than input parameter using SELECT INTO statement:

mysql> DELIMITER //
mysql> CREATE PROCEDURE sp02(IN p INT, OUT count INT)
BEGIN
SELECT COUNT(*) INTO count FROM book WHERE price >= p;
END
//
Query OK, 0 rows affected (0.11 sec)

mysql> DELIMITER ;
mysql> CALL sp02(300, @count);
Query OK, 0 rows affected (0.00 sec)

51/63
mysql> SELECT @count;
+--------+
| @count |
+--------+
| 3 |
+--------+
1 row in set (0.00 sec)

@count is local variable of MySQL session that is available within the session established
by mysql client. As can be seen, SELECT @count returns value of the local variables as 2
that is number of books price more than input parameter.

Another type of local variables such as DECLARE/SET has following expressions:


DECLARE var_name [,...] type [DEFAULT value]
SET var_name = expr [, var_name = expr] ...

Another example of following stored procedure using SELECT ,,, INTO displays list of books
with price more than average. The local variable average sets average price and copy to
avg OUT parameter:

mysql> DELIMITER //
mysql> CREATE PROCEDURE sp03(OUT avg INT)
BEGIN
DECLARE average INT;
SELECT AVG(price) INTO average FROM book;
SELECT id, title, price FROM book WHERE price > average;
SET avg = average;
END
//
Query OK, 0 rows affected (0.03 sec)

mysql> DELIMITER ;
mysql> call sp03(@avg);
+----+--------------------------+-------+
| id | title | price |
+----+--------------------------+-------+
| 3 | Introduction to Database | 500 |
| 4 | Introduction to Java | 750 |
+----+--------------------------+-------+
2 rows in set (0.02 sec)

52/63
Query OK, 0 rows affected (0.02 sec)

mysql> select @avg;


+------+
| @avg |
+------+
| 450 |
+------+
1 row in set (0.00 sec)

3.1.4. Cursors
Cursor is a control structure used for processing individual rows returned by a query. The
cursor enable to fetch a record from record set in stored procedure one by one to process.

DECLARE name CURSOR FOR select statement


OPEN name
FETCH name,,, INTO variable,,,
CLOSE name

v_id v_title v_price

1 MySQL 750

Fetch a column and assign to variables

Result set from book table

Figure 5 - CURSOR and Result Set

Figure below shows how to use cursor in stored procedure. The cursor can be opened after
the declaration and cursor can fetch variable by row until the loop condition ends. The cursor
must be closed after processing that is usually just before the stored procedure ends.

53/63
Figure 6 – Sample (sp04) Flowchart

Example using cursor below sets total price from book table that is same value as what
SUM function returns:
CREATE PROCEDURE sp04(OUT total INT)
BEGIN
DECLARE flag BIT DEFAULT 0;
DECLARE p INT DEFAULT 0;
DECLARE cur CURSOR FOR SELECT price FROM book;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET flag=1;
SET total =0;
OPEN cur;
WHILE flag != 1 DO
FETCH cur INTO p;

54/63
IF flag=0 THEN
SET total = total + p;
END IF;
END WHILE;
CLOSE cur;
END

3.1.5. Condition and Exception Handlers


DECLARE ... HANDLER FOR statement specifies handlers that deal with conditions
specified. If one of these conditions occurs, the specified statement will be executed.
Syntax:
DECLARE [CONTINUE|EXIT|UNDO] HANDLER FOR condition[,...] statement

Example below is an exception handler that occurs when cursor crosses last row of the table.
(No more rows can be found). Then statement of SET done = 1 execute to set done
valuable as 1. done as a flag to be used for such as WHILE loop condition to be continued:

DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

WHILE done != 1 DO
END WHILE;

3.1.6. Flow Controls


Flow control statements such as IF, CASE, LOOP, WHILE, REPLACE ITERATE, and
LEAVE constructs are fully implemented.

IF implements a basic conditional construct as syntax stated below:


IF condition THEN statement
[ELSEIF condition THEN statement ...]
[ELSE statement]
END IF

CASE implements a complex conditional construct as syntax stated below (Two types):
CASE variable
WHEN value THEN statement [...]
[ELSE] statement [...]
END CASE
Or
CASE

55/63
WHEN condition THEN statement [...]
[ELSE] statement [...]
END CASE

Example of CASE in stored procedure to display EMP table with Job Level depends on the
job title as follows:
Note : SET GLOBAL log_bin_trust_function_creators = 1;

mysql> DELIMITER //
mysql> CREATE FUNCTION sf_case(job VARCHAR(10)) RETURNS VARCHAR(10)
BEGIN
DECLARE level VARCHAR(10);
CASE job
WHEN 'CLERK' THEN SET level = 'Level 1';
WHEN 'SALESMAN' THEN SET level = 'Level 1';
WHEN 'MANAGER' THEN SET level = 'Level 2';
WHEN 'ANALYST' THEN SET level = 'Level 2';
WHEN 'PRESIDENT' THEN SET level = 'Level 3';
ELSE SET level = 'N/A';
END CASE;
RETURN level;
END
//
Query OK, 0 rows affected (0.02 sec)

mysql> DELIMITER ;
mysql> SELECT ename, job, sf_case(job) FROM emp;
+--------+-----------+--------------+
| ename | job | sf_case(job) |
+--------+-----------+--------------+
| SMITH | CLERK | Level 1 |
| ALLEN | SALESMAN | Level 1 |
| WARD | SALESMAN | Level 1 |
| JONES | MANAGER | Level 2 |
| MARTIN | SALESMAN | Level 1 |
| BLAKE | MANAGER | Level 2 |
| CLARK | MANAGER | Level 2 |
| SCOTT | ANALYST | Level 2 |
| KING | PRESIDENT | Level 3 |
| TURNER | SALESMAN | Level 1 |
| ADAMS | CLERK | Level 1 |
| JAMES | CLERK | Level 1 |
| FORD | ANALYST | Level 2 |
| MILLER | CLERK | Level 1 |

56/63
+--------+-----------+--------------+
14 rows in set (0.19 sec)

LOOP implements a simple loop construct that enables repeated execution of the
statements as syntax stated below:
[label:]LOOP
Statement
END LOOP[label]

LEAVE is used to exit any labeled flow control construct and it can be used within BEGIN ...
END or loop constructs such as LOOP, REPEAT and WHILE as syntax stated below:
LEAVE[label]

Example of LOOP and LEAVE in stored function is as follows. The stored function takes
seed and repeat max times to concatenate seed to be returned:

mysql> DELIMITER //
CREATE FUNCTION sf_loop(seed VARCHAR(5), max INT) RETURNS
VARCHAR(255)
BEGIN
DECLARE cnt INT DEFAULT 0;
DECLARE result VARCHAR(255) DEFAULT seed;
label1 : LOOP
SET cnt = cnt + 1;
IF cnt >= max THEN
LEAVE label1;
ELSE
SET result = CONCAT_WS('', result, seed);
END IF;
END LOOP label1;
RETURN result;
END
//
mysql> select sf_loop('Msis', 10);
+--------------------------------+
| sf_loop('Msis', 10) |
+--------------------------------+
| MsisMsisMsisMsisMsisMsisMsisMsisMsisMsis |
+--------------------------------+

ITERATE repeats loop goes back to the place stated in label and can be used for LOOP,
REPEAT, and WHILE statements as syntax stated below:

57/63
ITERATE label

The statement inside REPEAT is repeated until the condition becomes true as syntax stated
below. REPEAT always enters the loop at least one time:
[label:]REPEAT
Statement
UNTIL condition END REPEAT[label]

The statement inside WHILE is repeated as long as the condition is true as syntax stated
below:
[label:]WHILE condition DO
Statement
END WHILE[label]

Example of WHILE with sum up 1 to input parameter is as follows:


mysql> delimiter //
mysql> CREATE FUNCTION sf_while(seed INT) RETURNS INT
BEGIN
DECLARE count INT DEFAULT 0;
DECLARE result INT DEFAULT 0;
label1 : WHILE count <= seed DO
SET result = result + count;
SET count = count + 1;
END WHILE label1;
RETURN result;
END

//
Query OK, 0 rows affected (0.23 sec)

mysql> delimiter ;
mysql> SELECT sf_while(10);
+--------------+
| sf_while(10) |
+--------------+
| 55 |
+--------------+
1 row in set (0.00 sec)

58/63
3.2. Stored Function
Stored Function is also one of the stored routines and it has similar syntax as what stored
procedure has. The stored function returns value to where it was called. The stored function
can be called from DML statements such as SELECT, INSERT, UPDATE and DELETE
directly without using CALL. However the stored function does not support transaction such
as START TRANSACTION, SET AUTOCOMMIT, COMMIT and ROLLBACK statements
and the stored function locks tables that have been accessed by the function while function
is executed. Following table highlights the differences in between stored procedure and
stored function:

Table 12 - Stored Procedure and Stored Function


Type Return value Transaction support How to invoke
Stored Procedure No Yes CALL statement
Stored Function Yes No SQL statements

Syntax of create a stored function is as follows:


CREATE FUNCTION name ([direct] parameter type, …) RETURNS type
[characteristic] BEGIN body END

Syntax of drop the stored function is as follows. [IF EXISTS] is an option to drop when stored
function is already existed:
DROP FUNCTION [IF EXISTS] name;

Example of stored function that returns area of triangle based on weight and height input
parameters as follows:

mysql> DELIMITER //
mysql> CREATE FUNCTION my_triangle(width INT, height INT) RETURNS INT
BEGIN
DECLARE result INT;
SET result = width * height / 2;
RETURN result;
END
//
Query OK, 0 rows affected (0.02 sec)

mysql> DELIMITER ;
mysql> SELECT sf01(10, 20);
+--------------+

59/63
| sf01(10, 20) |
+--------------+
| 100 |
+--------------+
1 row in set (0.03 sec)

Another example of stored function is with simple SQL statement. The function takes Author
ID (VARCHAR type) as input parameter and returns number of books belongs to the author:
mysql> DELIMITER //
mysql> CREATE FUNCTION sf02(author VARCHAR(10)) RETURNS INT
BEGIN
DECLARE result INT DEFAULT 0;
SELECT COUNT(*) INTO result FROM book WHERE author_id =
author;
RETURN result;
END
//
Query OK, 0 rows affected (0.00 sec)

mysql> DELIMITER ;
mysql> SELECT sf02('01');
+------------+
| sf02('01') |
+------------+
| 3 |
+------------+
1 row in set (0.00 sec)

3.3. Database Trigger


A trigger is special procedural program that is automatically executed in response to
specified events such as INSERT, UPDATE and DELETE on a particular table in a
database. The trigger can be used for database event logging or data modification audit
purposes and it can be set to activate either BEFORE or AFTER the triggering statement.
For example, a trigger will be activated before each row that is deleted from a table or after
each row that is updated.

60/63
1. Client execute DML to book table

INSERT
UPDATE
DELETE

2. DML fires trigger automatically (BEFORE or AFTER)

3. Trigger inserts a record with OLD and New values before or after DML is executed

Figure 7 - Transaction and Database Trigger

Syntax of create a trigger is as follows. Trigger event as DML statements such as INSERT,
UPDATE and DELETE and timing of the event such as BEFORE and AFTER.
CREATE TRIGGER name event ON table FOR EACH ROW

Syntax of drop the trigger is as follows.


DROP TRIGGER name

Keywords NEW and OLD can be used in the body of trigger with column name such as
NEW.price and OLD.price. OLD.price refers to the value of price field before event occurs
and NEW.price refers to the same field after event occurs. Events that can use those
keywords are stated in two tables below:

Table 13 - Trigger event and keyword


Event Keyword
INSERT NEW
UPDATE NEW, OLD
DELETE OLD

61/63
Table 14 - Trigger timing with event matrix
Timing INSERT UPDATE DELETE
BEFORE NEW (Editable) NEW (Editable), OLD OLD
AFTER NEW NEW, OLD OLD

Example below is the trigger to insert a row into book_history table before updating of book
table. Upon update on book table (Just before update exactly), trigger tr01 invokes to insert
a row into book_history table with OLD (price_before) and NEW (price_after).

Example of creating a trigger and update book table to invoke the trigger
mysql> delimiter //
mysql> CREATE TRIGGER tr_update
BEFORE UPDATE ON book FOR EACH ROW
BEGIN
INSERT INTO book_history(book_id, title, price_before, price_after,
updated, event) VALUES(OLD.id, OLD.title, OLD.price, NEW.price,
CURRENT_TIMESTAMP(), 'UPDATE');
END
//

Query OK, 0 rows affected (0.11 sec)

mysql> UPDATE book SET price = 285 WHERE id = 1;


Query OK, 1 row affected (0.03 sec)

mysql> SELECT id, title, price_before, price_after FROM book_history;


+----+-----------------------+--------------+-------------+
| id | title | price_before | price_after |
+----+-----------------------+--------------+-------------+
| 1 | Introduction to MySQL | 250 | 285 |
+----+-----------------------+--------------+-------------+
1 row in set (0.00 sec)

62/63
Tables and Figures

Figures

Figure 1 - Standard SQL and Dialects ...........................................................................5


Figure 2 - Self-join (Recursive Relationship) ...............................................................14
Figure 3 - SQL and Stored Procedure (SP) ................................................................ 48
Figure 4 - SELECT INTO and Local Variable ..............................................................51
Figure 5 - CURSOR and Result Set ............................................................................ 53
Figure 6 – Sample (sp04) Flowchart ............................................................................54
Figure 7 - Transaction and Database Trigger ............................................................. 61

Tables

Table 1 - SHOW Commands ......................................................................................... 7


Table 2 - MySQL Number Type ..................................................................................... 9
Table 3 - MySQL String Types .......................................................................................9
Table 4 - MySQL Date/Time Type ............................................................................... 10
Table 5 - MySQL BLOB Type ...................................................................................... 10
Table 6 - List of parameters for Date and Time functions ...........................................34
Table 7 - Format type for Date/Time Functions ...........................................................40
Table 8 - CASE syntax .................................................................................................42
Table 9 - RDBMS and Stored Procedure .................................................................... 48
Table 10 - Parameter Direction ....................................................................................49
Table 11 - Access Privileges needed for Stored Procedure ....................................... 49
Table 12 - Stored Procedure and Stored Function ..................................................... 59
Table 13 - Trigger event and keyword ......................................................................... 61
Table 14 - Trigger timing with event matrix ................................................................. 62

63/63

You might also like