0% found this document useful (0 votes)
39 views12 pages

Triggers

Uploaded by

ohioprincess13
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)
39 views12 pages

Triggers

Uploaded by

ohioprincess13
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/ 12

Triggers

Types of Triggers –
We can define 6 types of triggers for each table:
1. AFTER INSERT: activated after data is inserted into the table.
2. AFTER UPDATE: activated after data in the table is modified.
3. AFTER DELETE: activated after data is deleted/removed from the
table.
4. BEFORE INSERT: activated before data is inserted into the table.
5. BEFORE UPDATE: activated before data in the table is modified.
6. BEFORE DELETE: activated before data is deleted/removed from the
table.

Syntax:

create trigger [trigger_name]


[before | after]
{insert | update | delete}
on [table_name]
[for each row]
[trigger_body]

Example1:

delimiter $$
CREATE TRIGGER Check_age BEFORE INSERT ON employee
FOR EACH ROW
BEGIN
IF NEW. age < 25 THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'ERROR:
AGE MUST BE ATLEAST 25 YEARS!';
END IF;
END; $$
delimiter;

Explanation: Whenever we want to insert any tupple to table ’employee’,


then before inserting this tupple to the table, trigger named ‘Check_age’ will
be executed. This trigger will check the age attribute. If it is greater then 25
then this tupple will be inserted into the table
otherwise an error message will be printed stating “ERROR: AGE MUST BE
ATLEAST 25 YEARS!”

Example 2. Create a trigger which will work before deletion in employee


table and create a duplicate copy of the record in another table
employee_backup.

Before writing trigger, we need to create table employee_backup

create table employee_backup (employee_no int,


employee_name varchar(40), job varchar(40),
hiredate date, salary int,
primary key(employee_no));
delimiter $$
CREATE TRIGGER Backup BEFORE DELETE ON employee
FOR EACH ROW
BEGIN
INSERT INTO employee_backup
VALUES (OLD.employee_no, OLD.name,
OLD.job, OLD.hiredate, OLD.salary);
END; $$
delimiter;
Explanation: We want to create a backup table that holds the value of those
employees who are no more the employee of the institution. So, we create a
trigger named Backup that will be executed before the deletion of any Tuple
from the table employee. Before deletion, the values of all the attributes of
the table employee will be stored in the table employee_backup.

Example 3. Write a trigger to count the number of new tuples inserted


using each insert statement.

Declare count int


Set count=0;
delimiter $$
CREATE TRIGGER Count_tupples
AFTER INSERT ON employee
FOR EACH ROW
BEGIN
SET count = count + 1;
END; $$
delimiter;
Explanation: We want to keep track of the number of new Tuples in the
employee table. For that, we first create a variable ‘count’ and initialize it to
0. After that, we create a trigger named Count_tupples that will increment the
value of count after insertion of any new Tuple in the table employee.

Views in SQL

Views in SQL are kind of virtual tables. A view also has rows and columns
as they are in a real table in the database. We can create a view by selecting
fields from one or more tables present in the database. A View can either
have all the rows of a table or specific rows based on certain condition.
Now, we will learn about creating , deleting and updating Views.

Sample Tables:
StudentDetails

StudentMarks
CREATING VIEWS

We can create View using CREATE VIEW statement. A View can be


created from a single table or multiple tables.

Syntax:

CREATE VIEW view_name AS


SELECT column1, column2.....
FROM table_name
WHERE condition;

view_name: Name for the View


table_name: Name of the table
condition: Condition to select rows

Examples:
● Creating View from a single table:

● In this example we will create a View named DetailsView from the
table StudentDetails.
Query:
● CREATE VIEW DetailsView AS

● SELECT NAME, ADDRESS


● FROM StudentDetails
● WHERE S_ID < 5;
To see the data in the View, we can query the view in the same
manner as we query a table.
SELECT * FROM DetailsView;
Output:

● In this example, we will create a view named StudentNames from


the table StudentDetails.
Query:

CREATE VIEW StudentNames AS


SELECT S_ID, NAME
FROM StudentDetails
ORDER BY NAME;
If we now query the view as,
SELECT * FROM StudentNames;
Output:

● Creating View from multiple tables:

● In this example we will create a View named MarksView from two


tables StudentDetails and StudentMarks. To create a View from multiple
tables we can simply include multiple tables in the SELECT statement.
Query:

● CREATE VIEW MarksView AS


● SELECT StudentDetails.NAME, StudentDetails.ADDRESS,
StudentMarks.MARKS
● FROM StudentDetails, StudentMarks
● WHERE StudentDetails.NAME = StudentMarks.NAME;
To display data of View MarksView:
SELECT * FROM MarksView;
Output:
DELETING VIEWS
We have learned about creating a View, but what if a created View is not
needed any more? Obviously we will want to delete it. SQL allows us to
delete an existing View. We can delete or drop a View using the DROP
statement.
Syntax:
DROP VIEW view_name;

view_name: Name of the View which we want to delete.


For example, if we want to delete the View MarksView, we can do this as:
DROP VIEW MarksView;

UPDATING VIEWS
There are certain conditions needed to be satisfied to update a view. If any
one of these conditions is not met, then we will not be allowed to update the
view.

1. The SELECT statement which is used to create the view should not
include GROUP BY clause or ORDER BY clause.
2. The SELECT statement should not have the DISTINCT keyword.
3. The View should have all NOT NULL values.
4. The view should not be created using nested queries or complex queries.
5. The view should be created from a single table. If the view is created
using multiple tables then we will not be allowed to update the view.
● We can use the CREATE OR REPLACE VIEW statement to add or
remove fields from a view.
Syntax:
● CREATE OR REPLACE VIEW view_name AS
● SELECT column1,coulmn2,..
● FROM table_name
● WHERE condition;
For example, if we want to update the view MarksView and add the
field AGE to this View from StudentMarks Table, we can do this as:

CREATE OR REPLACE VIEW MarksView AS


SELECT StudentDetails.NAME, StudentDetails.ADDRESS,
StudentMarks.MARKS, StudentMarks.AGE
FROM StudentDetails, StudentMarks
WHERE StudentDetails.NAME = StudentMarks.NAME;
If we fetch all the data from MarksView now as:
SELECT * FROM MarksView;
Output:

● Inserting a row in a view:

We can insert a row in a View in a same way as we do in a table. We can


use the INSERT INTO statement of SQL to insert a row in a View.

Syntax:
● INSERT INTO view_name(column1, column2 , column3,..)
● VALUES(value1, value2, value3..);

● view_name: Name of the View

Example:

In the below example we will insert a new row in the View DetailsView
which we have created above in the example of “creating views from a
single table”.

INSERT INTO DetailsView(NAME, ADDRESS)


VALUES("Suresh","Gurgaon");
If we fetch all the data from DetailsView now as,
SELECT * FROM DetailsView;
Output:


● Deleting a row from a View:
Deleting rows from a view is also as simple as deleting rows from a
table. We can use the DELETE statement of SQL to delete rows from a
view. Also deleting a row from a view first delete the row from the
actual table and the change is then reflected in the view.Syntax:
● DELETE FROM view_name
● WHERE condition;

● view_name:Name of view from where we want to delete rows
● condition: Condition to select rows
Example:
In this example we will delete the last row from the view DetailsView
which we just added in the above example of inserting rows.
DELETE FROM DetailsView
WHERE NAME="Suresh";
If we fetch all the data from DetailsView now as,
SELECT * FROM DetailsView;
Output:

WITH CHECK OPTION


The WITH CHECK OPTION clause in SQL is a very useful clause for
views. It is applicable to a updatable view. If the view is not updatable, then
there is no meaning of including this clause in the CREATE VIEW
statement.
● The WITH CHECK OPTION clause is used to prevent the insertion of
rows in the view where the condition in the WHERE clause in CREATE
VIEW statement is not satisfied.
● If we have used the WITH CHECK OPTION clause in the CREATE
VIEW statement, and if the UPDATE or INSERT clause does not satisfy
the conditions then they will return an error.
Example:
In the below example we are creating a View SampleView from
StudentDetails Table with WITH CHECK OPTION clause.
CREATE VIEW SampleView AS
SELECT S_ID, NAME
FROM StudentDetails
WHERE NAME IS NOT NULL
WITH CHECK OPTION;
In this View if we now try to insert a new row with null value in the NAME
column then it will give an error because the view is created with the
condition for NAME column as NOT NULL.

For example,though the View is updatable but then also the below query for
this View is not valid:
INSERT INTO SampleView(S_ID)
VALUES(6);
NOTE: The default value of NAME column is null.
Uses of a View :

A good database should contain views due to the given reasons:


1. Restricting data access –
Views provide an additional level of table security by restricting access
to a predetermined set of rows and columns of a table.
2. Hiding data complexity –
A view can hide the complexity that exists in a multiple table join.
3. Simplify commands for the user –
Views allows the user to select information from multiple tables without
requiring the users to actually know how to perform a join.
4. Store complex queries –
Views can be used to store complex queries.
5. Rename Columns –
Views can also be used to rename the columns without affecting the base
tables provided the number of columns in view must match the number
of columns specified in select statement. Thus, renaming helps to to hide
the names of the columns of the base tables.
6. Multiple view facility –
Different views can be created on the same table for different users.

You might also like