0% found this document useful (0 votes)
81 views

SQL PPT

Data integrity refers to completeness, accuracy, and consistency of data. There are three main integrity rules enforced in relational databases to achieve data integrity: 1. Entity integrity ensures that each table has a primary key that is unique and not null. 2. Referential integrity defines how foreign keys reference primary keys in other tables or can be null. 3. Domain integrity specifies that columns must be of a defined domain or type. Normalizing data through various normal forms like 1NF, 2NF, and 3NF reduces data redundancy and anomalies like inconsistent updates that occur when data is not logically stored.

Uploaded by

prasad ghate
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
81 views

SQL PPT

Data integrity refers to completeness, accuracy, and consistency of data. There are three main integrity rules enforced in relational databases to achieve data integrity: 1. Entity integrity ensures that each table has a primary key that is unique and not null. 2. Referential integrity defines how foreign keys reference primary keys in other tables or can be null. 3. Domain integrity specifies that columns must be of a defined domain or type. Normalizing data through various normal forms like 1NF, 2NF, and 3NF reduces data redundancy and anomalies like inconsistent updates that occur when data is not logically stored.

Uploaded by

prasad ghate
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 210

DATA INTEGRITY

Data integrity refers to completeness,accuracy and consistency.Data integrity is enforced in


relational database models. The following three integrity constraints are used in a relational
database structure to achieve data integrity.
INTEGRITY RULES :-
● Entity Integrity: This is concerned with the concept of primary keys. The rule states that
every table must have its own primary key and that each has to be unique and not null.

Eg :- In employee table landline number cannot be a key since some people may not
have phone.
● Referential Integrity: This is the concept of foreign keys. The rule states that the foreign
key value can be in two states. The first state is that the foreign key value would refer to a
primary key value of another table, or it can be null
● Domain Integrity: This states that all columns in a relational database are in a defined
domain.
Foreign Key Rules
Additional foreign key rules may be added, such as what to do with the child rows (Orders
table) when the record with the PK – the parent (Customer) is deleted or changed (updated).
The relationship window in Access shows two additional options for foreign keys rules.
Cascade Update and Cascade Delete. If they are not selected, the system would prevent
the deletion or update of PK values in the parent table (Customer) if a child record exists.
The child record is any record with a matching PK.
CASCADE DELETE
– RESTRICT-not deleting if the child row exists
– CASCADE-delete the child with the parent deletion
– SET TO NULL-during deletion of parent the child is set to NULL
CASCADE UPDATE
– RESTRICT-not updating the parent while child row exists
– CASCADE-updating the child when parent row is updated
In some databases, an additional option exists when selecting the Delete option. That is ‘Set
to Null’. In these situations, the PK row is deleted, but the FK in the child table is set to Null.
Though this creates an orphan row, it is acceptable.
CODD’s Rules
Codd is the father of relational databases.He published 12 rules that define the
ideal database.

Rule 1 :- (The Information Rule)

All data should be presented to the user in the table form.Even if a query
returns single row it should be in table format.

Rule 2 :-(The Guaranteed Access Rule)

All data should be accessible without ambiguity. Each item of data in an


RDBMS is guaranteed to be logically accessible by resorting to a combination of
table name, primary key value, and column name.
Rule 3 :- (The Systematic Treatment of Null Values Rule)

Any values can be allowed to remain empty and be recognized as NULL.Null


values (distinct from an empty character string or a string of blank characters and
distinct from zero) are supported in a fully relational DBMS for representing
missing information and inapplicable information in a systematic way, independent
of the data type.

Rule 4 :-(The Dynamic Online Catalog Based on the Relational Model rule)

A relational database must provide access to its structures through the same tools
that are used to access the data.

Eg :- Tables are accessed using SQL,Likewise metadata should also be able


to access through SQL .system tables are created for each individual database
from which the metadata can be fetched
Rule 5 :-(The Comprehensive Data Sublanguage rule)

There must be at least one language whose statements are expressible with
well defined syntax as character strings and should support the following.
● Data definition
● View definition
● Data manipulation
● Integrity constraints
● Transaction boundaries
Rule 6 :- (The View Updating rule)

Representation of data can be done using different logical combination called


views.All views of the data which are theoretically updatable must be updatable in
practice by the DBMS.
Rule 7 :-(The High-level Insert, Update, and Delete rule)
The capability of handling a base relation or a derived relation as a single operand
applies not only to the retrieval of data but also to the insertion, update, and
deletion of data.
Adding,changing or deleting data should be available at the same level that
retrieval is.
Eg :- select * from employee (Batch retrieval),update college set salary =60000
where designation=’Asst prof’ (Batch update)

Rule 8 :- (The Physical Data Independence rule)


Application programs and terminal activities remain logically unimpaired whenever
any changes are made in either storage representations or access methods.
Meaning changes made in the physical level must not impact and require a
change to be made in the application program
Rule 9 :- (The Logical Data Independence rule)
Application programs and terminal activities remain logically unimpaired when
information preserving changes of any kind that theoretically permit un impairment
are made to the base tables.
Meaning user’s view of the data should not change if the table structure
changes.changes made in the logical level must not impact and require a change
to be made in the application program.
Rule 10 :- (The Integrity Independence rule)
Integrity constraints must be definable in the RDBMS sublanguage and stored in
the system catalogue and not within individual application programs.
Meaning integrity contraint must be defined and separated from the application
program .changing constraints must be allowed without affecting the application
Rule 11 :-(The Distribution Independence rule)

An RDBMS has distribution independence. Distribution independence implies that


users should not have to be aware of whether a database is distributed.

Meaning user should be unaware about the database location that is whether or
not the database is distributed in multiple locations.

Rule 12 :-( The Non subversion rule)

If the database has any means of handling a single record at a time, that low-level
language must not be able to subvert or avoid the integrity rules which are
expressed in a higher-level language that handles multiple records at a time.

Meaning the only way to modify database structure should be database language
Normalisation of database
Normalization is a process of organizing the data in database to avoid

● data redundancy
● insertion anomaly
● update anomaly
● deletion anomaly
● to ensure that the data is logically stored
Need for Normalisation
● Difficult to handle and update the database
● Insertion,updation and deletion anomalies are very frequent if the database is
not normalized.

Anomalies in DBMS

● Insertion
● Updation
● Deletion
Updation anomaly
To update address of a student who occurs twice or more than twice in a table,

we will have to update S_Address column in all the rows,

else data will become inconsistent.


Insertion anomaly :-

Suppose for a new admission, we have a Student id(S_id), name and address of a
student but if student has not opted for any subjects yet then we have to insert
NULL there, leading to Insertion Anamoly.

Eg :- student and course form composite key .student cannot be enrolled in the
same course more than once that is combination should be unique.student and
course form the composite key and their combination should be unique

Deletion anomaly :-

If (S_id) 402 has only one subject and temporarily he drops it, when we delete that
row, entire student record will be deleted along with it.
Normalization Rule

Normalization rule are divided into following normal form.

1. First Normal Form

2. Second Normal Form

3. Third Normal Form

4. BCNF
First Normal Form

The Primary key is usually a single column, but sometimes more than one

column can be combined to create a single primary key. For example consider a

table which is not in First normal form


In First Normal Form, any row must not have a column in which more than one
value is saved, like separated with commas. Rather than that, we must separate
such data into multiple rows.

Using the First Normal Form, data redundancy increases, as there will be many
columns with same data in multiple rows but each row as a whole will be unique.
Second Normal Form (2NF)
As per the Second Normal Form there must not be any partial dependency of any column on
primary key. It means that for a table that has concatenated primary key, each column in the
table that is not part of the primary key must depend upon the entire concatenated key for its
existence. If any column depends only on one part of the concatenated key, then the table
fails Second normal form.

In example of First Normal Form there are two rows for Adam, to include multiple subjects
that he has opted for. While this is searchable, and follows First normal form, it is an
inefficient use of space. Also in the above Table in First Normal Form, while the candidate
key is {Student, Subject}, Age of Student only depends on Student column, which is
incorrect as per Second Normal Form. To achieve second normal form, it would be helpful to
split out the subjects into an independent table, and match them up using the student names
as foreign keys.
In Subject Table the candidate key will be {Student, Subject} column. Now, both the above tables qualifies
Third Normal Form (3NF)

Third Normal form applies that every non-prime attribute of table must be dependent on
primary key, or we can say that, there should not be the case that a non-prime attribute is
determined by another non-prime attribute. So this transitive functional dependency should
be removed from the table and also the table must be in Second Normal form

The advantage of removing transitive dependency is,

● Amount of data duplication is reduced.

● Data integrity achieved.


Third normal form contd ..
Boyce and Codd Normal Form (BCNF)

Super key :-
A super key is a set or one of more columns (attributes) to uniquely identify rows in a
table.
Candidate key :-
Candidate keys are selected from the set of super keys, the only thing we take care while
selecting candidate key is: It should not have any redundant attribute.
BCNF contd ..
It is an advance version of 3NF that’s why it is also referred as 3.5NF. BCNF is stricter than
3NF. A table complies with BCNF if it is in 3NF and for every functional dependency X->Y,
X should be the super key of the table.
To satisfy BCNF that table should be split into 3 tables
SQL Constraints
SQL constraints are used to specify rules for the data in a table.
If there is any violation between the constraint and the data action, the action is aborted by the constraint.
Constraints can be specified when the table is created (inside the CREATE TABLE statement) or after the
table is created (inside the ALTER TABLE statement).
In SQL, we have the following constraints:
● NOT NULL - Indicates that a column cannot store NULL value
● UNIQUE - Ensures that each row for a column must have a unique value
● PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Ensures that a column (or
combination of two or more columns) have a unique identity which helps to find a particular record in
a table more easily and quickly
● FOREIGN KEY - Ensure the referential integrity of the data in one table to match values in another
table
● CHECK - Ensures that the value in a column meets a specific condition
● DEFAULT - Specifies a default value for a column
NOT NULL
❖ The NOT NULL constraint enforces a column to NOT accept NULL values.
❖ The NOT NULL constraint enforces a field to always contain a value.
❖ This means that you cannot insert a new record, or update a record without adding a value to this
field.

Example :-
CREATE TABLE PersonsNotNull
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
Unique
❖ UNIQUE constraint ensures that a field or column will only have unique values.
❖ A UNIQUE constraint field will not have duplicate data
Example :-
CREATE TABLE Persons
(
P_Id int UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
Unique contd ..
To allow naming of a UNIQUE constraint, and for defining a UNIQUE constraint on multiple columns, use
the following SQL syntax:
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CONSTRAINT uc_PersonID UNIQUE (P_Id,LastName)
)
Unique contd .. (in alter statement)
To add constraint after the table is created

ALTER TABLE Persons

ADD UNIQUE (P_Id);

ALTER TABLE Persons

ADD CONSTRAINT uc_PersonID UNIQUE (P_Id,LastName);

To drop the constraint after the table is created

ALTER TABLE Persons

DROP CONSTRAINT uc_PersonID


PRIMARY KEY
❖ The PRIMARY KEY constraint uniquely identifies each record in a database table.
❖ Primary keys must contain UNIQUE values.
❖ A primary key column cannot contain NULL values.
Example :-
CREATE TABLE Persons
(
P_Id int PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
Primary key contd ..
CREATE TABLE Persons
(
P_Id int,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)
)
In the example above there is only ONE PRIMARY KEY (pk_PersonID). However, the VALUE of the
primary key is made up of TWO COLUMNS (P_Id + LastName).
Primary key contd .. (in alter statement)
To add constraint after the table is created

ALTER TABLE Persons

ADD PRIMARY KEY (P_Id);

ALTER TABLE Persons

ADD CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName);

To drop the constraint after the table is created

ALTER TABLE Persons

DROP CONSTRAINT pk_PersonID


FOREIGN KEY
Person (table)

Orders (table)
FOREIGN KEY contd ..
❖ Note that the "P_Id" column in the "Orders" table points to the "P_Id" column
in the "Persons" table.
❖ The "P_Id" column in the "Persons" table is the PRIMARY KEY in the
"Persons" table.
❖ The "P_Id" column in the "Orders" table is a FOREIGN KEY in the "Orders"
table.
❖ The FOREIGN KEY constraint is used to prevent actions that would destroy
links between tables.
❖ The FOREIGN KEY constraint also prevents invalid data from being inserted
into the foreign key column, because it has to be one of the values contained
in the table it points to.
Foreign key contd ..
CREATE TABLE Persons
(
P_Id int PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
CREATE TABLE Orders
(
O_Id int PRIMARY KEY,
OrderNo int NOT NULL,
P_Id int FOREIGN KEY REFERENCES Persons(P_Id)
)
Foreign key contd .. (in alter statement)
To add a primary key

ALTER TABLE Orders

ADD FOREIGN KEY (P_Id)

REFERENCES Persons(P_Id)

To drop a foreign key

ALTER TABLE Orders

DROP FOREIGN KEY fk_PerOrders


CHECK
❖ The CHECK constraint is used to limit the value range that can be placed in a column.
❖ If you define a CHECK constraint on a single column it allows only certain values for this column.
Example :-
➔ The following SQL creates a CHECK constraint on the "P_Id" column when the "Persons" table is
created. The CHECK constraint specifies that the column "P_Id" must only include integers greater
than 0.
CREATE TABLE Persons
(
P_Id int NOT NULL CHECK (P_Id>0),
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
To allow check constraint on multiple columns
CREATE TABLE Persons

P_Id int NOT NULL,

LastName varchar(255) NOT NULL,

FirstName varchar(255),

Address varchar(255),

City varchar(255),

CONSTRAINT chk_Person CHECK (P_Id>0 AND City='Sandnes')

)
CHECK Constraint on ALTER TABLE
To add constraint

ALTER TABLE Persons

ADD CHECK (P_Id>0)

ALTER TABLE Persons

ADD CONSTRAINT chk_Person CHECK (P_Id>0 AND City='Sandnes')

To drop constraint

ALTER TABLE Persons

DROP CONSTRAINT chk_Person


DEFAULT
The DEFAULT constraint is used to insert a default value into a column.
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255) DEFAULT 'Sandnes'
);
CREATE TABLE Orders
(
O_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
OrderDate date DEFAULT GETDATE()
)
DEFAULT Constraint on ALTER TABLE
To add default constraint:-

ALTER TABLE Persons

MODIFY City DEFAULT 'SANDNES'

To drop default constraint :-

ALTER TABLE Persons

ALTER COLUMN City DROP DEFAULT


DISTINCT
SELECT DISTINCT column_name,column_name
FROM table_name;
SELECT DISTINCT city FROM Customers;

Result :-
Where clause
It is used to apply filter condition

Syntax :-

SELECT column_name,column_name

FROM table_name

WHERE column_name operator value;


SELECT * FROM Customers
WHERE Country=’Germany’;
Result :-
AND & OR Operators
The AND operator displays a record if both the first condition AND the second
condition are true.
The OR operator displays a record if either the first condition OR the second
condition is true.

SELECT * FROM Customers


WHERE Country='Germany'
AND City='Berlin';
TCL (Transaction Control Statement)

1)Commit

2)Rollback

3)Save
1)Commit

Commit command is used to permanently save any transaction in the database.


Commit;

2)Rollback

This command restores the database to last commited state. It is also use with
savepoint command to jump to a savepoint in a transaction.

rollback;
rollback to savepoint_name;

3)Savepoint

savepoint savepoint_name;
Not included DDL and DML statements
Kindly refer your notes
TCL example :-
TCL example

INSERT into class values(5,'Rahul');


commit;
UPDATE class set name='abhijit' where id='5';
Savepoint A;
INSERT into class values(6,'Chris');
Savepoint B;
INSERT into class values(7,'Bravo');
Savepoint C;

SELECT * from class;


TCL contd..
Now rollback to savepoint B
Rollback to B;
SELECT * from class;
TCL contd...

Rollback to A;

Select * from class;


DCL (Data Control Language) :-
DCL is used to provide access to data stored in a database (Authorization)

DCL defines two commands,

● Grant : Gives user access privileges to database.

● Revoke : Take back permissions from user.


DCL example :-
To Grant permission to Create any Table :-
example
grant create any table to username

To Grant permission to Drop any Table :-


example
grant drop any table to username

To take back Permissions :-


example
revoke create table from username
Aggregate Functions
Aggregate functions
SQL aggregate functions return a single value, calculated from values in a column.

Useful aggregate functions:

AVG() - Returns the average value

COUNT() - Returns the number of rows

MAX() - Returns the largest value

MIN() - Returns the smallest value

SUM() - Returns the sum


Avg()
The AVG() function returns the average value of a numeric column.

SQL AVG() Syntax :-

SELECT AVG(column_name) FROM table_name


SELECT AVG(Price) AS PriceAverage FROM Products;

Products table :-
Count()
SQL COUNT(column_name) Syntax

The COUNT(column_name) function returns the number of values (NULL values


will not be counted) of the specified column

SELECT COUNT(column_name) FROM table_name;

SELECT COUNT(ProductID) FROM Products


DISTINCT keyword

SQL COUNT(DISTINCT column_name) Syntax


The COUNT(DISTINCT column_name) function returns the number of distinct
values of the specified column:

SELECT COUNT(DISTINCT column_name) FROM table_name;

SELECT COUNT(DISTINCT SupplierID) FROM Products;


SQL COUNT(*) Syntax

The COUNT(*) function returns the number of records in a table:

SELECT COUNT(*) FROM table_name;

SELECT COUNT(*) FROM Products;


Max()
The MAX() function returns the largest value of the selected column.

MAX() Syntax

SELECT MAX(column_name) FROM table_name;

SELECT MAX(Price) FROM Products;


Min()
The MIN() function returns the smallest value of the selected column.

MIN() Syntax

SELECT MIN(column_name) FROM table_name;

SELECT MIN(Price) from Products;


Sum()
The SUM() function returns the total sum of a numeric column.

SQL SUM() Syntax

SELECT SUM(column_name) FROM table_name;

SELECT SUM(Quantity) AS TotalItemsOrdered FROM OrderDetails;


GROUP BY statement
Syntax :-

SELECT column_name, aggregate_function(column_name)

FROM table_name WHERE column_name operator value

GROUP BY column_name;
Example :-
SELECT dept_id, SUM(SALARY) FROM employee

GROUP BY dept_id;
HAVING Clause

The HAVING clause is added to SQL because the WHERE keyword could not be
used with aggregate functions.
SQL HAVING Syntax

SELECT column_name, aggregate_function(column_name)

FROM table_name

WHERE column_name operator value

GROUP BY column_name

HAVING aggregate_function(column_name) operator value;


Syntax :-
SELECT dept_id, SUM(SALARY) FROM employee

GROUP BY dept_id

having count(dept_id)>=1;
UCASE()
The UCASE() function converts the value of a field to uppercase.
UCASE() Syntax

SELECT UCASE(column_name) FROM table_name;

Syntax for SQL Server

SELECT UPPER(column_name) FROM table_name;


SELECT UCASE(CustomerName) AS Customer, City
FROM Customers;
Result :- SELECT UCASE(CustomerName) AS Customer, City
FROM Customers;
LCASE() Function

The LCASE() function converts the value of a field to lowercase

SQL LCASE() Syntax

SELECT LCASE(column_name) FROM table_name;

Syntax for SQL Server

SELECT LOWER(column_name) FROM table_name;


SELECT LCASE(CustomerName) AS Customer, City
FROM Customers;
Result :-SELECT LCASE(CustomerName) AS Customer, City
FROM Customers;
SUBSTR()

SELECT substr(column_name,start,length) AS some_name FROM table_name;


SELECT substr(City,1,4) AS ShortCity
FROM Customers;
SELECT substr(City,1,4) AS ShortCity
FROM Customers;
LEN() Function

The LEN() function returns the length of the value in a text field

SQL LEN() Syntax

SELECT LEN(column_name) FROM table_name;

Syntax for Oracle

SELECT LENGTH(column_name) FROM table_name;


SELECT LEN(Address) as LengthOfAddress
FROM Customers;
NOW() Function

The NOW() function returns the current system date and time.

SQL NOW() Syntax

SELECT NOW() FROM table_name;


SELECT ProductName, Price, Now() AS PerDate
FROM Products;
SELECT ProductName, Price, Now() AS PerDate
FROM Products;
NVL
The Oracle/PLSQL NVL function lets you substitute a value when a null value is
encountered

SYNTAX :-

NVL( string1, replace_with )


Parameters or Arguments
string1

The string to test for a null value.

replace_with

The value returned if string1 is null.


Example :-
SELECT NVL(supplier_city, 'n/a') FROM suppliers;

The SQL statement above would return 'n/a' if the supplier_city field contained a null value. Otherwise, it would return the
supplier_city value.

SELECT supplier_id,NVL(supplier_desc, supplier_name)


FROM suppliers;

This SQL statement would return the supplier_name field if the supplier_desccontained a null value. Otherwise, it would
return the supplier_desc.

SELECT NVL(commission, 0) FROM sales;

This SQL statement would return 0 if the commission field contained a null value.Otherwise, it would return the commission
field.

Exercise Lab :- Try applying aggregate or group value functions to the column containing null value.

And apply AVG and COUNT.what will happen ?


DUAL table

The DUAL table is a special one-row, one-column table (Dummy table)

Example :-
SELECT 1+1
from dual;

SELECT SYSDATE
from dual;
SQL Arithmetic functions :-
ABS()

The SQL ABS() returns the absolute value of a number passed as argument.

SELECT ABS(-17.36)
FROM dual;

Output

ABS(-17.36)
-----------
17.36
ceil()

SQL CEIL() will rounded up any positive or negative decimal value to next greater integer value

Example

SELECT(CEIL(17.36)) FROM dual;

(CEIL(17.36))
--------------------
18

SELECT CEIL(-17.36) FROM dual;

CEIL(-17.36)
------------------
exp()

EXP() returns e raised to the n-th power(n is the numeric expression), where e is the base of natural
algorithm and the value of e is approximately 2.71828183

Example :-

1. SELECT EXP(2) AS E_TO_2S_power


2. FROM dual;

E_TO_2S_POWER
---------------------------
7.3890561
floor()

The SQL FLOOR() rounded up any positive or negative decimal value down to the next least integer value.

Example :-
SELECT FLOOR(17.36) FROM dual;

FLOOR(17.36)
---------------------
17

SELECT FLOOR(-17.36) FROM dual;

FLOOR(-17.36)
----------------------
-18
LN()

The SQL LN() function returns the natural logarithm of n

Example :-

SELECT LN(65) "natural_log of 65"


FROM dual;

natural_log of 65
---------------------------
4.17438727
MOD()

The SQL MOD() function returns the remainder from a division

MOD( dividend, divider )

1. SELECT MOD(25,7)
2. FROM dual;
Output

MOD(25,7)
-----------------
4
POWER()

The SQL POWER() function returns the value of a number raised to another

Syntax

POWER( base, exponent )

1. SELECT POWER(2,3)
2. FROM dual;
Output

POWER(2,3)
-------------------
8
SQRT()

SQRT() returns the square root of given value in the argument.

Example :-

SELECT SQRT(36) FROM dual;

Output

SQRT(36)
------------------
6
Order of execution
FROM

ON

JOIN

WHERE

GROUP BY

HAVING

SELECT

DISTINCT

ORDER BY
Set Operation in SQL

SQL supports few Set operations to be performed on table data

Set operators :-

1)UNION

2)UNION ALL

3)INTERSECT

4)MINUS
UNION
● UNION is used to combine the results of two or more Select statements.
● However it will eliminate duplicate rows from its result set.
● In case of union, number of columns and datatype must be same in both the
tables.
Tables :-

first :-

Second :-
Result :-

select * from first


UNION
select * from second
UNION ALL
This operation is similar to Union.
But it also shows the duplicate rows.
Tables :-
first

second
Result :-
select * from First
UNION ALL
select * from second
INTERSECT
● Intersect operation is used to combine two SELECT statements, but it only returns the records which
are common from both SELECT statements.
● In case of Intersect the number of columns and datatype must be same.
● MySQL does not support INTERSECT operator.
Tables :-
first :-

Second :-
Result :-

select * from First


INTERSECT
select * from second
MINUS :-
● Minus operation combines result of two Select statements and return only those result which

belongs to first set of result.

● MySQL does not support INTERSECT operator.


Tables :-
first :-

Second :-
Result :-
select * from First
MINUS
select * from second
SQL Join Types:
There are different types of joins available in SQL:

● INNER JOIN

● LEFT JOIN

● RIGHT JOIN

● FULL JOIN

● SELF JOIN

● CARTESIAN JOIN
Inner Join
The INNER JOIN selects all rows from both tables when there occurs match between columns from both
the tables.
Syntax :-
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name=table2.column_name;
INNER OR EQUI JOIN
Orders (table1)

Customers (table2)
Inner join contd...
SELECT Customers.CustomerID,Orders.OrderID, Customers.CustomerName,
Orders.OrderDate
FROM Orders
INNER JOIN Customers
ON Orders.CustomerID=Customers.CustomerID;
Output :-
Left join
The LEFT JOIN returns all rows from the left table (table1), with the matching rows in the
right table (table2). The result is NULL in the right side when there is no match

Syntax :-

SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name=table2.column_name;
or:
SELECT column_name(s)
FROM table1
LEFT OUTER JOIN table2
ON table1.column_name=table2.column_name;
Left join contd ...
CUSTOMERS (table 1)

ORDERS (table2)
Left join contd ...
SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
LEFT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;

output:-
RIGHT JOIN :-
The RIGHT JOIN returns all rows from the right table (table2), with the matching rows in the left table
(table1). The result is NULL in the left side when there is no match.
Syntax :-

SELECT column_name(s)

FROM table1

RIGHT JOIN table2

ON table1.column_name=table2.column_name;
or:

SELECT column_name(s)

FROM table1

RIGHT OUTER JOIN table2

ON table1.column_name=table2.column_name;
Right join contd ..
Class (table1)

Class_info (table2)
Right outer join contd ...
SELECT * FROM class

RIGHT OUTER JOIN class_info

on (class.id=class_info.id);

Output :-
FULL OUTER JOIN
The FULL OUTER JOIN returns all rows from the left table (table1) and from the right table (table2).
The FULL OUTER JOIN combines the result of both LEFT and RIGHT joins.

Syntax :-

SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name=table2.column_name;
Full outer join contd ..
Class (table1)

Class_info (table2)
Full outer join example
SELECT * FROM class

FULL OUTER JOIN class_info

on (class.id=class_info.id);

Output :-
Self join
A self join is a join in which a table is joined with itself , specially when the table has a FOREIGN KEY
which references its own PRIMARY KEY.
To join a table itself means that each row of the table is combined with itself and with every other row of
the table.
To distinguish the column names from one another, aliases for the actual table name are used, since both
the tables have same name.

SELECT a.column_name, b.column_name...


FROM table1 a, table1 b
WHERE a.common_filed = b.common_field;
Self join example
CREATE TABLE employee(emp_id varchar(5) NOT NULL,
emp_name varchar(20) ,
dt_of_join date ,
emp_supv varchar(5) ,
CONSTRAINT emp_id PRIMARY KEY(emp_id) ,
CONSTRAINT emp_supv FOREIGN KEY(emp_supv)
REFERENCESemployee(emp_id));

In the EMPLOYEE table displayed above, emp_id is the primary key.


emp_supv is the foreign key (this is the supervisor’s employee id).
How the employees are related :-

● An employee may report to another employee (supervisor).


● An employee may supervise himself (i.e. zero) to many employee (subordinates).
Result :-
SELECT a.emp_id AS "Emp_ID",a.emp_name AS "Employee Name",
b.emp_id AS "Supervisor ID",b.emp_name AS "Supervisor Name"
FROM employee a, employee b
WHERE a.emp_supv = b.emp_id;
CROSS JOIN :-

This type of JOIN returns the cartesian product of rows from the tables in Join.
It will return a table which consists of records which combines each row from the first table with each row
of the second table
Cross join Example :-
Foods (table 1)

Company (table 2)
Example contd ..

SELECT foods.item_name,foods.item_unit,
company.company_name,company.company_city
FROM foods
CROSS JOIN company;
or
SELECT foods.item_name,foods.item_unit,
company.company_name,company.company_city
FROM foods,company;
What is subquery in SQL?
A subquery is a SQL query nested inside a larger query.
● A subquery may occur in :
- A SELECT clause
- A FROM clause
- A WHERE clause
● The subquery can be nested inside a SELECT, INSERT, UPDATE, or DELETE statement or inside another
subquery.
● A subquery is usually added within the WHERE Clause of another SQL SELECT statement.
● You can use the comparison operators, such as >, <, or =. The comparison operator can also be a multiple-row
operator, such as IN, ANY, or ALL.
● A subquery is also called an inner query or inner select, while the statement containing a subquery is also called
an outer query or outer select.
● The inner query executes first before its parent query so that the results of inner query can be passed to the outer
query.
You can use a subquery in a SELECT, INSERT, DELETE, or UPDATE statement to perform the following tasks :
● Compare an expression to the result of the query.
● Determine if an expression is included in the results of the query.
● Check whether the query selects any rows.
SQL Subqueries Example

★ We have the following two tables 'student' and 'marks' with common field 'StudentID'
★ Now we want to write a query to identify all students who get better marks than that of the student
who's StudentID is 'V002', but we do not know the marks of 'V002'.
★ To solve the problem, we require two queries. One query returns the marks (stored in Total_marks
field) of 'V002' and a second query identifies the students who get better marks than the result of the
first query.
Splitting into 2 queries
SELECT *
FROM `marks`
WHERE studentid = 'V002';

SELECT a.studentid, a.name, b.total_marks


FROM student a, marks b
WHERE a.studentid = b.studentid
AND b.total_marks >80;
Combining in a single query
You can combine the above two queries by placing one query inside the other. The subquery (also called
the 'inner query') is the query inside the parentheses.

SELECT a.studentid, a.name, b.total_marks


FROM student a, marks b
WHERE a.studentid = b.studentid AND b.total_marks >
(SELECT total_marks
FROM marks
WHERE studentid = 'V002');
Subqueries with INSERT statement

Orders table

INSERT INTO neworder


SELECT * FROM orders
WHERE advance_amount in(2500,1500);

Note :- neworder table should contain same number of columns with same datatype ;
Subqueries with UPDATE statement

Orders table

UPDATE neworder
SET ord_date='15-JAN-10'
WHERE ord_amount-advance_amount<
(SELECT MIN(ord_amount) FROM orders);
Subqueries with DELETE statement

Orders table

DELETE FROM neworder


WHERE advance_amount<
(SELECT MAX(advance_amount) FROM orders);
Type of Subqueries :-

● Single row subquery : Returns zero or one row.


● Multiple row subquery : Returns one or more rows.
● Correlated subqueries : Reference one or more columns in the outer SQL statement. The subquery is known as a correlated
subquery because the subquery is related to the outer SQL statement.
● Nested subqueries : Subqueries are placed within another subqueries.
Single Row Subqueries

Single Row Subqueries


A single row subquery returns zero or one row to the outer SQL statement. You can place a subquery in a
WHERE clause, a HAVING clause, or a FROM clause of a SELECT statement.

Contents:

● Single Row SubQueries in WHERE clause


● Using comparison operators in Single Row subqueries
● Subqueries in a HAVING clause
● Subqueries in a FROM clause
● Error in Single Row Subqueries
Single Row Subqueries in WHERE clause

Example - Find
SELECT agent_name, agent_code, phone_no
FROM agents
WHERE agent_code =
(SELECT employee_code
FROM employees
WHERE id =5 );
Query -how many orders amount are greater than average amount on 20-april-2008 ?
Orders table

SELECT ord_num,ord_amount,ord_date,cust_code, agent_code


FROM orders
WHERE ord_amount>
(SELECT AVG(ord_amount)
FROM orders
WHERE ord_date='20-APR-08');
Subqueries in a HAVING clause

Orders table

Query :- Find the average order amount for each agent_code who is having average amount greater than the average
amount of the agent code ‘A008’

SELECT AVG(ord_amount),agent_code
FROM orders
GROUP BY agent_code
HAVING AVG(ord_amount)=
(SELECT AVG(ord_amount)
FROM orders
WHERE agent_code='A008');
Subqueries in a FROM clause

Foods

SELECT item_id
FROM
(SELECT item_id,company_id
FROM FOODS
WHERE item_id<4)
Where company_id>15
Error in Single Row Subqueries

Inner subquery should return only one row if we are using =,>,< operator in the
where clause

SELECT item_id, item_name


FROM foods WHERE item_id =
(SELECT item_id
FROM foods
WHERE item_name LIKE '%a%');

Oracle gives this error


ORA-01427: single-row subquery returns more than one row
Multiple Row and Column Subqueries

Multiple Row Subqueries


Multiple row subquery returns one or more rows to the outer SQL statement.

You may use the IN, ANY, or ALL operator in outer query to handle

a subquery that returns multiple rows.


Using IN operator with a Multiple Row Subquery

Agent

Orders
Example :-
Using IN operator with a Multiple Row Subquery
SELECT ord_num,
cust_code, agent_code
FROM orders
WHERE agent_code IN(
SELECT agent_code FROM agents
WHERE working_area='Bangalore'
or working_area=Chennai);
Using NOT IN operator

Example :-

SELECT ord_num,ord_amount,ord_date,
cust_code, agent_code
FROM orders
WHERE agent_code NOT IN(
SELECT agent_code FROM agents
WHERE working_area='Bangalore');
Using ANY with a Multiple Row Subquery

SELECT agent_code,agent_name,working_area,commission
FROM agents
WHERE agent_code=ANY(
SELECT agent_code FROM customer
WHERE cust_country='UK');
USING ANY operator (SOME operator can also be
used)
ANY operator should be satisfied for atleast one of the values mentioned or returned by the inner query

SELECT agent_code,agent_name,working_area,commission
FROM agents
WHERE agent_code=ANY(
SELECT agent_code FROM customer
WHERE agent_code =ANY
(SELECT agent_code FROM orders
WHERE advance_amount>600));
USING ALL operator
SELECT des_date,des_amount,ord_amount
FROM despatch
WHERE des_amount>ALL(
SELECT ord_amount FROM orders
WHERE ord_amount>1000);

SELECT des_date,des_amount,ord_amount FROM despatch


WHERE des_amount > ALL (2000, 3000, 4000);
USING EXISTS
SELECT cust_code,cust_name,cust_city,grade
FROM customer
WHERE grade=2 AND
EXISTS(
SELECT COUNT(*) FROM customer
WHERE grade=2
GROUP BY grade
HAVING COUNT(*)>2);
Correlated subqueries
❖ SQL Correlated Subqueries are used to select data from a table referenced in
the outer query.
❖ The subquery is known as a correlated because the inner query is related to
the outer query.
Corelated subqueries
Market table stock table

SELECT m.NAME FROM Market m WHERE m.RIC = (SELECT s.LISTED_ON_EXCHANGE FROM


Stock s WHERE s.LISTED_ON_EXCHANGE=m.RIC);
Using Exists in correlated subquery
SELECT employee_id, manager_id, first_name, last_name
FROM employees a
WHERE EXISTS
(SELECT employee_id
FROM employees b
WHERE b.manager_id = a.employee_id)
Views
A view is nothing more than a SQL statement that is stored in the database with an associated name.
View is good way to present data in particular users from accessing the table directly.
The database system stores database views as a SQL SELECT statement
Syntax :-
CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition
You can include multiple tables in your SELECT statement in very similar way as you use them in normal
SQL SELECT query.
Note if the table in your view is updated then your view will also be updated.
Use of view :-
1. Views can hide complexity

If you have a query that requires joining several tables, or has complex logic or calculations, you can code
all that logic into a view, then select from the view just like you would a table.

2. Views can be used as a security mechanism

A view can select certain columns and/or rows from a table, and permissions set on the view instead of
the underlying tables. This allows surfacing only the data that a user needs to see.

Difference between table and view:-

A table contains data, a view is just a SELECT statement which is been saved in the database
TEMPORARY TABLES

❏ A temporary table is created by using CREATE TEMPORARY TABLE statement. Notice that the
TEMPORARY keyword is added between CREATE and TABLE keywords.
❏ MySQL drops the temporary table automatically when the session ends or connection is terminated.
you can use the DROP TEMPORARY TABLE statement to drop a temporary table explicitly when
you are no longer use it.
❏ A temporary table is only available and accessible by the client who creates the table.
Syntax :-
CREATE TEMPORARY TABLE SalesSummary (
product_name VARCHAR(50) NOT NULL,
total_sales DECIMAL(12,2) NOT NULL DEFAULT 0.00,
avg_unit_price DECIMAL(7,2) NOT NULL DEFAULT 0.00,
total_units_sold INT UNSIGNED NOT NULL DEFAULT 0
);
Dropping Temporary Tables:

Syntax

Drop TEMPORARY TABLE tablename;


● You can use the DROP TABLE statement to remove temporary tables however it is good practice to use the DROP
TEMPORARY TABLE statement instead.
● Because the DROP TEMPORARY TABLE removes only temporary tables, not the permanent tables.
● In addition, the DROP TEMPORARY TABLE statement helps you avoid the mistake of removing a permanent table
when you name your temporary table the same as the name of the permanent table.
Family trees and connect by clause
Let’s analyze it: the CONNECT BY clause, mandatory to make a hierarchical query, is used to define how
each record is connected to the hierarchical superior.

● On the other hand, given a record with EMPNO=x, all the records having MGR=x are his sons.
● The unary operator PRIOR indicates “the father of”.
● START WITH clause is used to start from which records we want to start the hierarchy, in our
example we want to start from the root of the hierarchy, the employee that has no manager.

❖ The LEVEL pseudocolumn indicates at which level each record stays in the hierarchy, starting from
the root that has level=1.
❖ Once understood the quey, we can read our resulting tree: KING is the root and has level=1.
❖ Under KING there are three employees at level 2(JONES,BLAKE e CLARK). Then the others.
❖ How does it make the hierarchy? First of all it reads the records.
❖ Then it determines the roots applying the START WITH clause.
❖ Then, starting from each root, it determines the first-level sons applying the CONNECT BY clause
and so on…
Employee table

EMPNO ENAME MANAGERNO


---------- ---------- ----------
7369 SMITH 7902
7499 ALLEN 7698
7521 WARD 7698
7566 JONES 7839
7654 MARTIN 7698
7698 BLAKE 7839
7782 CLARK 7839
7788 SCOTT 7566
7839 KING
7844 TURNER 7698
7876 ADAMS 7788
7900 JAMES 7698
7902 FORD 7566
7934 MILLER 7782
Example
Syntax :-
CONNECT BY <child_value> = <parent_value>

Example :-
select empno, ename, mgr, prior ename, level
from emp
connect by prior empno = managerno
start with mgr is null;
Example 2 :-
select empno,lpad(' ',level*3,' ')||ename name,
mgr, prior ename, level
from emp
connect by prior empno = mgr
start with mgr is null;

Lpad syntax :-

lpad(string to padded with


,padded length,padded character)
PL/SQL
PL/SQL stands for Procedural Language extension of SQL.

PL/SQL is a combination of SQL along with the procedural features of


programming languages.

PL/SQL Block consists of three sections:


● The Declaration section (optional).

● The Execution section (mandatory).

● The Exception Handling (or Error) section (optional).


Major types of MYSQL stored programs
Stored functions
● Stored functions are similar to stored procedures , but their execution returns a single value.
● A stored function can be used within a standard SQL statement, allowing the programmer to
effectively extend the capabilities of the SQL language.
Stored procedures
● Stored procedures are the most common type of stored program.
● A stored procedure is a generic program unit that is executed on request and that can accept
multiple input and output parameters.
Triggers
● Triggers are stored programs that are activated in response to, or are triggered by, an activity within
the database.
● Typically, a trigger will be invoked in response to a DML operation (INSERT, UPDATE, DELETE)
against a database table. Triggers can be used for data validation.
USER DEFINED FUNCTIONS :-
● You can write user-defined functions in PL/SQL to provide functionality that is
not available in SQL or SQL built-in functions.
● User-defined functions can appear in a SQL statement anywhere SQL
functions can appear
FUNCTIONS
The syntax to create a function in MySQL is:

CREATE FUNCTION function_name (parameter datatype , parameter datatype)


RETURNS return_datatype
BEGIN
declaration_section
executable_section
END;
Example :-
DELIMITER //
CREATE FUNCTION CalcIncome ( starting_value INT )
RETURNS INT
BEGIN
DECLARE income INT;
SET income = 0;
WHILE income <= 3000 DO
SET income = income + starting_value;
END WHILE ;

RETURN income;
END; //

DELIMITER ;
Function contd ..
Call a function :-

SELECT functionname();

SELECT CalcIncome (1000);

Drop Function :-

DROP FUNCTION functionname;

DROP FUNCTION CalcIncome;


Example :-
DELIMITER $$
CREATE FUNCTION CustomerLevel(p_creditLimit double)
RETURNS VARCHAR(10)
BEGIN
DECLARE lvl varchar(10);
IF p_creditLimit > 50000 THEN
SET lvl = 'PLATINUM';
ELSEIF (p_creditLimit <= 50000 AND p_creditLimit >= 10000) THEN
SET lvl = 'GOLD';
ELSEIF p_creditLimit < 10000 THEN
SET lvl = 'SILVER';
END IF;
RETURN (lvl);
END
Calling function :-
SELECT
customerName, CustomerLevel(creditLimit)
FROM
customers
ORDER BY customerName;
Example :-
CREATE FUNCTION isodd(input_number int)
RETURNS int
BEGIN
DECLARE v_isodd INT;
IF MOD(input_number,2)=0 THEN
SET v_isodd=FALSE;
ELSE
SET v_isodd=TRUE;
END IF;
RETURN (v_isodd);
END ;
PROCEDURES
● A stored procedure is a named PL/SQL block which performs one or more specific
task.
● This is similar to a procedure in other programming languages.
● A procedure has a header and a body.
● The header consists of the name of the procedure and the parameters or variables
passed to the procedure.
● The body consists of declaration section, execution section and exception section
similar to a general PL/SQL Block.
● A procedure is similar to an anonymous PL/SQL Block but it is named for repeated
usage
Parameter type
IN -Send values to the stored procedures.

OUT-Get values from the stored procedures.

INOUT-Send and get values from stored procedures


Example 1 :-
DELIMITER //
CREATE PROCEDURE GetAllProducts()
BEGIN
SELECT * FROM products;
END //
DELIMITER ;
● The first command is DELIMITER // , which is not related to the function procedure syntax. The
DELIMITER statement changes the standard delimiter which is semicolon ( ; ) to another. In
this case, the delimiter is changed from the semicolon( ; ) to double-slashes // Why do we have
to change the delimiter? Because we want to pass the stored procedure to the server as a
whole rather than letting mysql tool interpret each statement at a time. Following the END
keyword, we use the delimiter // to indicate the end of the stored procedure. The last command
( DELIMITER; ) changes the delimiter back to the semicolon (;).
Example 2 :-

Calling procedure:-

CALL GetOfficeByCountry('USA');
Example 3 :-
Example 3 contd ...
To get the number of shipped orders, we call the CountOrderByStatus stored procedure

and pass the order status as Shipped,

and also pass an argument ( @total ) to get the return value.


Example 4 :-
Result :-
CURSORS
● Database creates a memory area, known as context area, for processing an
SQL statement, which contains all information needed for processing the
statement, for example, number of rows processed, etc.
● A cursor is a pointer to this context area.
● System controls the context area through a cursor.
● A cursor holds the rows (one or more) returned by a SQL statement.
● The set of rows the cursor holds is referred to as the active set.
IMPLICIT CURSORS
● It is automatically created whenever SQL statement is executed.
● Whenever a DML statement (Insert,update,delete) is issued , implicit cursor is
associated with this system.
● For insert - cursor holds the data to be inserted.
● For update and delete - cursor identifies the rows that would be affected
Oracle provides few implicit cursor attributes to check the status of DML
operation.
In PL/SQL, you can refer to the most recent implicit cursor as the SQL cursor, which always has the
attributes like %FOUND, %ISOPEN, %NOTFOUND, and %ROWCOUNT
Example
DECLARE
total_rows number(2);
BEGIN
UPDATE customers
SET salary = salary + 500;
IF sql%notfound THEN
dbms_output.put_line('no customers selected');
ELSEIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' customers selected ');
END IF;
END;
/
Explicit cursors :-
Explicit cursors are programmer defined cursors for gaining more control over the context area.
An explicit cursor should be defined in the declaration section of the Block.
It is created on a SELECT Statement which returns more than one row

Working with an explicit cursor involves four steps:

● Declaring the cursor for initializing in the memory

● Opening the cursor for allocating memory

● Fetching the cursor for retrieving data

● Closing the cursor to release allocated memory


Working with MySQL cursor

1)Declaring the cursor

First, you have to declare a cursor by using the DECLARE statement:

The cursor declaration must be after any variable declaration.

If you declare a cursor before variables declaration, MySQL will issue an error.

A cursor must always be associated with a SELECT statement.


2)Opening the cursor

● Next, you open the cursor by using the OPEN statement.


● The OPEN statement initializes the result set for the cursor

3)Fetching the cursor


● Then, you use the FETCH statement to retrieve the next row pointed by the cursor and move the
cursor to the next row in the result set.
4)closing the cursor
Finally, you call the CLOSE statement to deactivate the cursor and release the memory associated with it
as follows:

Handling not found :-When working with MySQL cursor, you must also declare a NOT FOUND handler
to handle the situation when the cursor could not find any row. Because each time you call the FETCH
statement, the cursor attempts to read the next row in the result set. When the cursor reaches the end of
the result set, it will not be able to get the data, and a condition is raised. The handler is used to handle
this condition.To declare a NOT FOUND handler, you use the following syntax:
Working of MYSQL cursor
MySQL Cursor Example :-
We are going to develop a stored procedure that builds an email list of all employees in employees table.
First, we declare some variables, a cursor for looping over the emails of employees, and a NOT FOUND handler:
Example :-
Example contd ..
Calling procedure
You can test the build_email_list stored procedure using the following script:
Triggers :-
In MYSQL trigger is a set of SQL statements that is invoked automatically when a change is made to the data on the
associated table.

A trigger can be defined to be invoked either before or after the data is changed by INSERT, UPDATE or DELETE
statement.

● BEFORE INSERT – activated before data is inserted into the table.


● AFTER INSERT – activated after data is inserted into the table.
● BEFORE UPDATE – activated before data in the table is updated.
● AFTER UPDATE – activated after data in the table is updated.
● BEFORE DELETE – activated before data is removed from the table.
● AFTER DELETE – activated after data is removed from the table.
Naming convention
You should name the triggers using the following naming convention:

Example :-
Example contd ..
First create a new table named employees_audit to keep the changes of the employee table.
The following statement creates the employee_audit table.
Example contd ..
Next, create a BEFORE UPDATE trigger that is invoked before a change is made to the employees table.
OLD and NEW keyword
Inside the body of the trigger, we used the OLD keyword to access employeeNumber and lastname column of the row
affected by the trigger.

Notice that in a trigger defined for INSERT, you can use NEW keyword only. You cannot use the OLD keyword. However,
in the trigger defined for DELETE, there is no new row so you can use the OLD keyword only. In the UPDATE trigger,
OLD refers to the row before it is updated and NEW refers to the row after it is updated.

Then, to view all triggers in the current database,

SHOW TRIGGERS;
Viewing triggers in the database
employees > triggers, you will see the before_employee_update trigger as shown in the screenshot below:
After that, update the employees table to check whether the trigger is invoked.
Create Multiple Triggers For The Same Trigger Event
The syntax for creating the first trigger remains the same. In case you have multiple triggers for the same
event in a table, MySQL will invoke the triggers in the order that they were created. To change the order of
triggers, you need to specify FOLLOWS or PRECEDES after the FOR EACH ROW clause.

● The FOLLOWS option allows the new trigger to activate after the existing trigger.
● The PRECEDES option allows the new trigger to activate before the existing trigger.
MySQL Multiple Triggers Example
Suppose, whenever we change the price of a product (column MSRP ),
we want to log the old price in a separate table named price_logs
First, we create a new price_logs table using the CREATE TABLE statement as follows:
Second, we create a new trigger that activates when the BEFORE UPDATE event of the products table occurs. The
trigger’s name is before_products_update :
Example contd ..
Example contd ..
Suppose we want to see not only the old price and when it was changed but also who changed it. We can
add additional columns to the price_logs table. However, for the purpose of multiple triggers
demonstration, we will create a new table to store the data of users who made the changes. The name of
the new table is user_change_logs
Example contd ..
Now, we create a second trigger that activates on the BEFORE UPDATE event of the products table. This
trigger will update the user_change_logs table with the data of the user who made the changes. It is
activated after the before_products_update trigger.
Example contd ..
Information On Triggers Order
Index
An index can be created in a table to find data more quickly and efficiently.
Can be used to speed up searches/queries.
Note: Updating a table with indexes takes more time than updating a table without (because the indexes
also need an update). So you should only create indexes on columns (and tables) that will be frequently
searched against.
SQL CREATE INDEX Syntax :-
Creates an index on a table. Duplicate values are allowed:
CREATE INDEX index_name
ON table_name (column_name)
Creates an index on a table. Duplicate values are not allowed:
CREATE UNIQUE INDEX index_name
ON table_name (column_name)

You might also like