MySQL Comprehensive Guide and Tutorials
MySQL Comprehensive Guide and Tutorials
By Priti Dalvi
1
Index
Module Topic Page No
Module 1 : Getting Started with MySQL 4
Module 2 : Editing SQL Commands 17
Module 3 : Data Retrieval & Ordering Output 25
Module 4 : Regular Expressions 45
Module 5 : Creating Tables 48
Module 6: Inserting, Modifying & Deleting Data 57
Module 7 : Modifying Table Structure 65
Module 8 : Integrity Constraints 71
Module 9 : Built-In Functions 86
Module 10 : Indexes 99
Module 11 : Advanced Queries 105
2
Index
Module Topic Page No
Module 12 : Views 119
Module 13 : Transaction Processing 127
Module 14 : Miscellaneous function 133
Module 15: Introduction to programming 139
Module 16 : Temporary tables 151
Module 17 : Cursors 155
Module 18 : Stored Procedure and Functions 169
Module 19 : Triggers 185
Module 20: MySQL Prepared Statement 200
Module 21: Exception Handling 208
3
Module 1. Getting Started with MySQL
• Overview
➢ Introduction to Databases
➢ Introducing MySQL
➢ Main Components of MySQL
➢ Starting MySQL commands
➢ Exiting MySQL
4
Introduction to Databases
EMPLOYEE
COMMISSI
EMPNO ENAME JOB MANAGER HIREDATE SALARY DEPTNO
ON
17-DEC-
7369 SMITH CLERK 7902 800 20
1980
7499 ALLEN SALESMAN 7698 20-FEB-1981 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-1981 1250 500 30
7566 JONES MANAGER 7839 02-APR-1981 2975 20
7654 MARTIN SALESMAN 7698 28-SEP-1981 1250 1400 30
01-MAY-
7698 BLAKE MANAGER 7839 2850 30
1981
7782 CLARK MANAGER 7839 09-JUN-1981 2450 0 10
7788 SCOTT ANALYST 7566 19-APR-1987 3000 20
5
Introducing SQL
Database
Data is displayed
6
What is MySQL?
7
Why MySQL?
• MySQL database has become the word’s most popular open
source database.
• It has high performance, high reliability, and easy to use.
• It runs on more than 20 platforms.
• It offers comprehensive range of database tools.
• Source code is available under the terms of GNU General
public Licenses.
8
The application which uses MySQL
9
Features
• Web applications
• Open-source support
• Available large table size
• Stability
10
Comparison
11
Platforms and Interfaces
• Many programming languages with language specific APIs
includes libraries for accessing MySQL database.
• MySQL connector-net is used for integration with Microsoft
Visual Studio.
• MySQL connector-java for Java
• An ODBC interface called MYODBC allows interface with
programming languages such as ASP and Coldfusion.
12
Main Components of MySQL
13
Main Components of MySQL
14
Exiting MySQL
mysql> EXIT
15
MySQL Workbench
16
Module 2. Editing SQL Commands
• Overview
➢ Entering SQL commands
➢ Editing SQL commands
➢ Managing SQL files
17
Entering and Editing SQL Commands
• Viewing databases:
➢ mysql>Show databases;
➢ mysql>Show databases like ‘test%’;
18
Entering and Editing SQL Commands
mysql >Show databases(LIKE <wildcard>);
mysql> Show databases;
mysql > Connect databasename;
or
mysql > use databasename
mysql > desc emp;
mysql > desc emp 'e%';
mysql > Show columns from emp;
mysql > Show columns from emp like ‘e%’;
mysql > Show tables;
mysql > Show tables (from<databasename>) (LIKE wildcard>);
mysql > Show table status like ‘emp’;
mysql > Tee c:\[Link];
19
Entering and Editing SQL Commands
mysql > SHOW CREATE TABLE emp;
mysql > explain select * from emp;
mysql > explain select empno, ename from emp;
mysql > check table emp;
20
Executing SQL files
21
Show the Structure of the table
22
Entering and Editing SQL Commands
mysql>help;
mysql> \c
mysql> Show variables;
mysql > Prompt
mysql > Prompt Priti
mysql > Create database Pragati;
mysql > Create database if not exists Pragati;
mysql > drop database Pragati;
mysql > drop database IF EXISTS Pragati;
23
Entering and Editing SQL Commands
mysql>Select version(), current_date();
mysql> select now();
mysql> select user();
24
Module 3. Data Retrieval & Ordering Output
• Overview
➢ Simple Data Retrieval
➢ Describing Table Structure
➢ Conditional Retrieval using Arithmetic, Relational, Logical
and Special Operators
➢ The ORDER BY clause.
➢ Aggregate functions
➢ The GROUP BY and HAVING clause
25
Data Retrieval
26
Data Retrieval
mysql> SHOW TABLES;
mysql >SELECT * FROM emp;
28
Description
|| or operator
29
Relational Operators
= equal to
!= not equal to
<> not equal to
> greater than
< less than
>= greater than or equal to
<= less than or equal to
30
Relational Operators
31
Logical Operators
NOT,! not
OR, || or
AND, && and
32
Logical Operators
The AND Operator
mysql > SELECT * FROM employee
WHERE dept_code = 'MKTG' AND sex = 'F';
The OR Operator
mysql > SELECT * FROM employee
WHERE dept_code = 'MKTG' OR dept_code = 'FIN';
34
Special Operators
The IN operator
mysql > SELECT * FROM employee WHERE dept_code IN ('MKTG',
'FIN');
36
Special Operators
37
Arithmetic Operators
+ addition
- subtraction
* multiplication
/ division
38
Ordering the SELECT Query Output
Ordering on single column
mysql> SELECT * FROM employee ORDER BY emp_code;
mysql> SELECT * FROM employee ORDER BY 1;
40
The GROUP BY clause
41
The HAVING Clause
42
Counting and Identifying Duplicates
43
Eliminating Duplicates
44
Module 4. Regular Expressions
• Overview
➢ using regular expressions
45
Regular expressions
46
Regular expressions
47
Module 5. Creating Tables
• Overview
➢ Creating a Table
➢ Data Types
48
Creating Tables
49
Creating Tables
mysql> CREATE TABLE dept (
dept_code varchar (4),
dept_name varchar (20) );
50
Creating Tables
51
Numeric Data Types:
Data Type Range Stores
53
Numeric Data Types:
Data Type Range Stores
54
String Types:
Data Type Range Stores
CHAR(M) - n characters where n can be 1 to 255 Fixed-length character
data.
56
Module 6. Inserting, Modifying & Deleting Data
• Overview
➢ Inserting Data into a Table
➢ Inserting Data into a Table using Sub query
➢ Modifying Data in a Table
➢ Deleting Data from a Table
57
Insert records
Syntax:
INSERT [ low_priority | delayed ] [ ignore ] [ into ]
<tablename>
[ ( <columnname>, ...) ] VALUES (<insert expression>,)
58
Inserting Data into Table
59
Insert records
60
Inserting Data into a Table
Mysql> desc dept;
Field Type Null? Key Default Extra
------------- ------ ----- ----- --------- -------
DEPT_CODE varchar(4) yes null
DEPT_NAME varchar(20)yes null
61
Counting and Identifying Duplicates:
62
Modifying and Deleting Data
63
Modifying and Deleting Data
64
Modifying and Deleting Data
65
Module 7. Modifying Table Structure
• Overview
➢ Altering Table structure
➢ Dropping Column from a Table
➢ Dropping a Table
66
Modifying a Table Structure
67
Modifying a Table Structure
Mysql> ALTER table emp
drop comm;
Mysql> ALTER table emp
Add email varchar(20);
or
Mysql> ALTER table emp
Add email varchar(20) first;
or
Mysql> ALTER table emp
Add email varchar(20) after sal;
Mysql>ALTER table emp
modify ename varchar(40);
68
Modifying a Table Structure
69
Dropping a Table
70
Module 8. Integrity Constraints
• Overview
➢ Understanding Table and Column Constraints
➢ Creating, Modifying and Dropping Column level constraints
➢ Creating, Modifying and Dropping Table level constraints
71
Integrity Constraints
• Not Null
• Unique
• Check
• Primary Key
• Foreign Key
72
Column Constraints
73
Column Constraints
74
The UNIQUE Constraint
mysql> CREATE TABLE supplier (
supp_code int(4) PRIMARY KEY,
supp_name varchar (30) UNIQUE);
75
The CHECK Constraint
76
The PRIMARY KEY Constraint
77
The REFERENCES Constraint
78
The REFERENCES Constraint
79
Table Constraints
80
The PRIMARY KEY and CHECK Constraint
81
The FOREIGN KEY Constraint
83
Removing Duplicates, Table Replacement:
85
Module 9. Built-In Functions
• Overview
➢String functions
➢Numeric functions
➢Date functions
➢Special formats with Date data types
➢Conversion functions
86
String functions
Function Returns Example Result
lcase (x) Converts the entire string to SELECT lcase inder kumar
lowercase. ( 'Inder Kumar Gujral' ) gujral
FROM dual;
ucase(x) Converts the entire string to SELECT ucase INDER
uppercase. ( 'Inder' ) FROM dual;
ascii(c) ASCII value of the given SELECT ascii(‘ARTI’); 65
character, C
replace (char, Every occurrence of str1 in char is SELECT replace( ‘Cap' , 'C', Map
str1, str2) replaced with str2. 'M' ) ;
ADDTIME(expr1 adds expr2 to expr1 and returns the SELECT ADDTIME('1997-12-31 1998-01-02
,expr2) result 23:59:59.999999','1 01:01:01.00000
1:1:1.000002'); 1
CURDATE() current date as a value in 'YYYY-MM- SELECT CURDATE(); 2013-03-30
DD'
91
Format specifier characters
Specifier Description
%a Abbreviated weekday name (Sun..Sat)
%f Microseconds (000000..999999)
%H Hour (00..23)
%h Hour (01..12)
92
Format specifier characters
Specifier Description
%i Minutes, numeric (00..59)
%j Day of year (001..366)
%l Hour (1..12)
%M Month name (January..December)
%m Month, numeric (00..12)
%p AM or PM
%r Time, 12-hour (hh:mm:ss followed by AM or PM)
%S Seconds (00..59)
%s Seconds (00..59)
%T Time, 24-hour (hh:mm:ss)
%U Week (00..53), where Sunday is the first day of
the week
%u Week (00..53), where Monday is the first day of
the week
93
Format specifier characters
Specifier Description
%W Weekday name (Sunday..Saturday)
%w Day of the week (0=Sunday..6=Saturday)
%X Year for the week where Sunday is the first day of
the week, numeric, four digits; used with %V
94
Date Functions
Function Returns Example Result
HOUR(time) the hour for time. The range of the SELECT HOUR('10:05:03'); 10
return value is 0 to 23
LAST_DAY(dat value for the last day of the month. SELECT LAST_DAY('2003- 2003-02-28
e) 02-05');
95
Date Functions
Function Returns Example Result
MONTH(date the month for date, in the SELECT MONTH('1998- 2
) range 0 to 12 02-03')
1
WEEKDAY(d weekday index for date (0 = SELECT
ate) Monday, 1 = Tuesday, . 6 = WEEKDAY('1998-02-03
Sunday). 22:23:00');
8
WEEKOFYE calendar week of the date as a SELECT
AR(date) number in the range from 1 to WEEKOFYEAR('1998-02-
53. 20');
YEAR(date) year for date, in the range 1000 SELECT YEAR('98-02- 1998
to 9999 03');
97
Conversion Functions
98
Module 10. Indexes
• Overview
➢ Understanding Indexes
➢ Unique , Simple Indexes, Partial index
99
Indexes
• Are database objects used to improve the performance of the
database.
100
Simple Indexes
101
Partial index
or
102
ALTER command to add INDEX:
103
Querying the Data Dictionary
104
Module 11. Advanced Queries
• Overview
➢ Table joins
➢ Sub queries
➢ Set operators
➢ MERGE statement
105
JOINS
Cross Join
106
JOINS
Inner Join
107
JOINS
Equi Join
108
JOINS
109
JOINS
110
JOINS
111
JOINS
Self Join
112
SUBQUERIES
114
SET Operators
mysql> SELECT prod_code, prod_name FROM product
UNION
SELECT prod_code, prod_name FROM old_products;
115
SET Operators
The result wise UNIO, UNION ALL, DISTINCT is same.
116
MERGE statement
• Meaning
➢ Mysql Merge Statement is used to merge the two sql statement using
UNION clause..
➢ The UNION clause is used to combine the result set of any two sql
queries.
117
MERGE statement
• Example
118
Module 12. Views
• Overview
➢ Understanding Views
➢ Creating views
➢ Altering & dropping views
119
Views
121
Views
122
Views
mysql> CREATE VIEW fin_emp AS
SELECT * FROM employee WHERE dept_code = 'FIN';
123
Views
124
Views
➢Restriction:
We can not use order by clause
125
Viewing the Details
126
Module 13. Transaction Processing
• Overview
➢ ACID
127
Properties of Transactions(ACID):
• Atomicity
• Consistency
• Isolation
• Durability
128
Transaction Processing
• COMMIT
• ROLLBACK
129
Commit
130
Transaction Processing
mysql> SAVEPOINT savepointname;
mysql> SAVEPOINT stage1;
mysql> ROLLBACK TO savepointname;
mysql> ROLLBACK TO stage1;
131
Transaction Processing
lock table table_reference_list lock_type ;
Lock_type:
write or read
132
Module 14. Miscellaneous function
• Overview
➢ if()
➢ isnull()
➢ nullif()
➢ case
133
Logical and Conditional Functions
If() function
134
Logical and Conditional Functions
Isnull() function
To determine whether the value of the argument given in
parentheses is NULL.
It returns
➢ 1 if the value is NULL
➢ 0 if it is not NULL.
mysql> select ename, comm from emp
where isnull(comm);
135
Logical and Conditional Functions
null()if function
This MySQL function returns NULL if the two arguments given
are equal. Otherwise, it returns the value or results of the first
argument.
Syntax
NULLIF(condition1, condition2)
136
Cases
137
Loading the data from text file
138
Module 15. Introduction to programming
• Overview
139
User-Defined variables
Mysql>set @name=‘Anuradha’;
Mysql>set @tel_no=5432487;
Mysql>select @name, @tel_no;
140
User-Defined variables
Mysql>select @max_sal:=max(sal)
From emp
Mysql>select * from emp
Where sal=@max_sal;
141
Compound-Statement
begin
update employee
set salary = salary + 111
where dept_code = 'MKTG';
delete from employee
where dept_code = ‘operation’;
end;
142
Example
143
Repeat loop
delimiter //
CREATE PROCEDURE dorepeat1(p1 INT)
BEGIN
SET @x = 0;
REPEAT
SET @x = @x + 1;
select @x;
UNTIL @x > p1
END REPEAT;
end
//
delimiter ;
call dorepeat1(20);
144
IF-ELSE Statements
145
IF-ELSE Statements
146
Example
Mysql>create function total (a int, b int) returns varchar(50)
begin
declare c int;
declare s varchar(50);
set c = a + b;
if c < 10 THEN
set s = 'add is less then 10';
ELSE
set s = 'add is equal or greater then 10';
END IF;
RETURN s;
END $$
147
Example else-if
Mysql>create function check1(a int, b int) returns varchar(50)
begin
declare c int;
declare s varchar(50);
if a < b THEN
set s = 'a is less than b';
ELSEif a > b THEN
set s ='add is greater than b';
else
set s='a is equal to b';
END IF;
RETURN s;
END $$
148
Example else-if
DELIMITER ;
select check1 (10, 20);
149
Example loop … end loop
Mysql> create procedure proce2()
BEGIN
DECLARE count INT default 0;
DECLARE in_count int;
set in_count =20;
increment: LOOP
SET count = count + 1;
select count;
IF count < 20 THEN ITERATE increment; END IF;
IF count > in_count THEN LEAVE increment;
END IF;
END LOOP increment;
SELECT count;
END
150
Module 16. Temporary tables
• Overview
➢ Table Cloning
151
Usage of temporary table
152
Dropping Temporary Tables:
153
MySQL Clone Tables
Step 1
mysql > SHOW CREATE TABLE emp \G;
Step 2
Rename this table and create another table
mysql >CREATE TABLE clone_EMP
(
154
MySQL Clone Tables
Step 3
Mysql>insert into
clone_emp1(empno,ename,job,mgr,hiredate,sal,
comm, deptno)
select empno,ename,job,mgr,hiredate,sal,
comm, deptno from emp;
155
Getting Server Metadata( in MySQL)
Command Description
156
Module 17. Cursors
• Overview
➢ Understanding Cursors
➢ Types of cursors
➢ Cursor operations
157
Cursors
• so with cursor you can fetch the result set and then perform the
additional processing only on the rows that require it.
159
Types of Cursors
1. Asensitive
2. Read Only
160
Types of Cursors
1. Asensitive
2. Read Only
161
Steps of Cursors
1. Declare a cursor
2. Open a cursor statement
3. Fetch the cursor
4. Close the cursor
5. Handler
162
Steps of Cursors
1. Declare..
➢ To declare a cursor
164
Cursors
Mysql> declare
sales cursor for
SELECT
a.salesman_id,a.salesman_name, [Link], [Link]
FROM salesman a, target b, sales c
WHERE a.salesman_id=b.salesman_id
and [Link]=[Link];
begin
..............
end;
165
Cursors
mysql>CREATE PROCEDURE curdemo()
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE v_roll int(11) DEFAULT 0;
DECLARE t1_cur CURSOR FOR SELECT * from t1;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN t1_cur;
read_loop: LOOP
FETCH t1_cur INTO v_roll;
IF done THEN
LEAVE read_loop;
END IF;
select concat('the roll number is ', v_roll);
END LOOP;
CLOSE t1_cur;
END;
166
Cursors
➢The DECLARE ... HANDLER statement specifies a handler that deals with
one or more conditions.
167
Cursors
168
Cursors
Mysql>CREATE PROCEDURE curdemo()
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE v_deptno decimal(2,0);
DECLARE v_dname varchar(14);
DECLARE v_loc varchar(13);
DECLARE cur1 CURSOR FOR SELECT * from dept;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN cur1;
read_loop: LOOP
FETCH cur1 INTO v_deptno,v_dname,v_loc;
IF done THEN
LEAVE read_loop;
END IF;
INSERT INTO dept1 VALUES (v_deptno,v_dname,v_loc);
END LOOP;
CLOSE cur1;
END;
169
Cursors
Advantages of cursor:
➢Best used when you want each row or more than one row one by
one.
➢Its efficient because with Cursor we are doing operations so there is
no need to write complex queries(like joins)
Disadvantages:
➢Cursor is faster than a while loop but it create more overhead in
database.
➢Cursor fetching one by one data from database so if data is more,
its take more execution time.
170
Module 18. Stored Procedure and Functions
• Overview
➢ Parameter modes
➢ Transaction
➢ Function
171
Stored Procedures
172
Stored Procedures
173
Stored procedure
174
Stored Procedures
175
Stored Procedure
176
Stored Procedure
Mysql>delimiter //
Mysql>delimiter ;
Mysql>CALL myProc ();
177
Stored Procedure : in parameter
mysql> DELIMITER //
mysql> CREATE PROCEDURE myProc (IN in_count INT)
BEGIN
DECLARE count INT default 0;
increment: LOOP
SET count = count + 1;
IF count < 20 THEN ITERATE increment; END IF;
IF count > in_count THEN LEAVE increment;
END IF;
END LOOP increment;
SELECT count;
END
//
mysql> DELIMITER ;
mysql> call myProc(5);
178
Stored Procedure : out parameter
mysql> delimiter //
mysql>
mysql> CREATE PROCEDURE procout (OUT p_tot_sal
INT)
BEGIN
SELECT sum(sal) INTO p_tot_sal FROM emp;
END;
//
mysql> delimiter ;
mysql>
mysql> CALL procout(@sal);
Query OK, 0 rows affected (0.00 sec)
179
Procedure
Creating procedure:
180
Stored Procedure : in out parameter
mysql> delimiter //
mysql> CREATE PROCEDURE update_sal (INOUT
in_increment INT)
BEGIN
update emp
set sal= sal+ in_increment where empno=700;
SELECT sal INTO in_increment FROM emp
where empno=700;
END;
//
mysql> delimiter ;
Mysql>set @up_sal=1000;
mysql> CALL update_sal(@up_sal);
mysql> SELECT @up_sal;
181
Stored Procedure :
To see information about Stored Procedure like:
• name of database
• type of procedure
• language
• code writtern
• date of creation
182
Stored Procedure :
In case you would want to view all the stored procedures in a
Database then we can use :
mysql>SELECT ROUTINE_NAME
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_TYPE="PROCEDURE"
AND ROUTINE_SCHEMA="dbname";
183
Stored Functions
• Stored Functions
➢ Is similar to stored procedures except that a function returns
only a single values.
Syntax:
CREATE FUNCTION f_name ([parameter(s)])
RETURNS data type
DETERMINISTIC
STATEMENTS
184
Stored Functions
mysql>delimiter //
mysql>create function hello (s char(20))
returns char(50)
deterministic
return CONCAT('Hello',space(1),s);
//
mysql>delimiter ;
mysql>select hello('world');
185
Stored Functions
Mysql>DELIMITER //
Mysql>CREATE FUNCTION join_date_ck(return_date DATE)
RETURNS VARCHAR(3)
deterministic
BEGIN
DECLARE sf_value VARCHAR(3);
IF curdate() > return_date
THEN SET sf_value = 'Yes';
ELSEIF curdate() <= return_date
THEN SET sf_value = 'No';
END IF;
RETURN sf_value;
END//
186
Stored Functions
To run the function:
Mysql>DELIMITER ;
Mysql>select empno, hiredate, curdate(), join_date_ck(hiredate)
from emp;
187
Module 19. Triggers
• Overview
➢ Understanding Triggers
➢ Applying Triggers
➢ Types of Triggers
➢ Dropping Triggers
188
Database Triggers
189
Database Triggers
190
Database Triggers
Triggername Is the name of the trigger to be created
BEFORE engine fires the trigger before executing the triggering statement.
AFTER engine fires the trigger after executing the triggering statement.
DELETE engine fires the trigger whenever a DELETE statement removes a row
FROM the table.
INSERT Indicates that the engine fires the trigger whenever a INSERT statement
adds a row to table.
UPDATE Indicates that the engine fires the trigger whenever an UPDATE statement
changes a value in one of the columns specified in the OF clause. If the OF
clause is omitted, the engine fires the trigger whenever a UPDATE statement
changes a value in any column of the table.
191
Database Triggers
ON Specifies the schema and name of the table, which the trigger is to be created.
If schema is omitted, the engine assumes the table is in the user's own schema.
A trigger cannot be created on a table in the schema SYS.
REFERENCI- Specifies correlation names. Correlation names can be used in the block and
NG WHEN clause of a row trigger to refer specifically to old and new values of the
current row. The default correlation names are OLD and NEW. If the row
trigger is associated with a table named OLD or NEW, this clause can be
used to specify different correlation names to avoid confusion between
table name and he correlation name.
FOR EACH Designates the trigger to be a row trigger. The engine fires a row trigger once
ROW for each row that is affected by the triggering statement and meets the optional
trigger constraint defined in the when clause. If this clause is omitted the
trigger is a statement trigger
WHEN Specifies the trigger restriction. The trigger restriction contains a SQL
condition that must be satisfied for the engine to fir the trigger. This condition
must contain correlation names and cannot contain a query. Trigger restriction
can be specified only for the row triggers. The engine evaluates this
condition for each row affected by the triggering statement.
192
Database Triggers
MySQL triggers cannot:
• Applying Triggers
➢ Triggering Event
➢It can be Insert, Update or Delete statement for a table
➢ Trigger Constraint (Optional)
➢A boolean expression for each row trigger specified
using a WHEN clause
➢ Trigger Action
➢code to be executed when a triggering statement is
encountered
194
Database Triggers
• Types of Triggers
➢ The 'time' when the trigger fires
• BEFORE trigger (before the triggering action).
• AFTER trigger (after the triggering action)
195
Database Triggers
196
Database Triggers
• Expressions in Triggers
197
Database Triggers
• Conditional Predicates
➢ Useful when the trigger fires more than one type of DML operation.
➢ Need to use the INSERTING, UPDATING or DELETING clause.
➢ These are pre – defined PL/SQL Boolean type variables which
evaluate to either true or false.
198
Database Triggers
Mysql>delimiter $$
Mysql>CREATE TRIGGER myTrigger
BEFORE DELETE ON emp
FOR EACH ROW
BEGIN
INSERT into transaction_log (user_id, description)
VALUES (user(), 'Employee deleted ');
END$$
Mysql>delimiter ;
199
Database Triggers
To check ;
Mysql> select * from transaction_log
200
Database Triggers
mysql> delimiter $$
mysql> CREATE TRIGGER myTrigger
BEFORE INSERT ON emp
FOR EACH ROW
BEGIN
IF [Link] < 600 THEN
SET [Link]='Y';
ELSE
SET [Link]='N';
END IF;
END$$
201
Database Triggers
Mysql>Delimiter //
mysql> create trigger tr1
-> before insert on dept
-> for each row
-> begin
-> set @name=‘insert trigger ';
-> end;
-> //
202
Database Triggers
To execute
Mysql>delimiter ;
Insert into dept values(50,’new,’new’);
Select @name;
203
Dropping Triggers, View Details
• Dropping a trigger
➢ delimiter //
➢ drop trigger if exists trigger name ;
204
Module 20. MySQL Prepared Statement
• Overview
➢ Transactions
➢ use of Prepared Statements
➢ Benefits of Prepared Statements
➢ Syntax
205
Transactions
206
MySQL prepared statement
207
MySQL prepare statement
209
MySQL prepare statement
210
MySQL prepare statement
211
Prepare statement …
212
Module 21. Exception Handling
• Overview
213
Exception Handling
➢Handled by using
➢DECLARE CONTINUE HANDLER
➢Need to declare the handler
214
Exception Handling
Syntax
DECLARE handler_action HANDLER
FOR condition_value [, condition_value] ...
statement
handler_action:
CONTINUE
| EXIT
| UNDO
215
Exception Handling
216
Exception Handling
Error code Message
1240 Key reference and table
reference don't match
1062 Duplicate key in index
1005 Can't create table
1006 Can't create database
1008 Can't drop database
1016 Can't open file
1036 Table is read only
217