0% found this document useful (0 votes)
8 views11 pages

Triger Lab

The document provides a comprehensive overview of database management concepts, focusing on triggers and views in SQL. It includes detailed instructions for creating triggers to manage insurance calculations and maintenance records in a vehicle database, as well as explanations of views and their operations. Additionally, it outlines the conditions under which views can be updated and the implications of such updates on underlying tables.

Uploaded by

2022vivek.a
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views11 pages

Triger Lab

The document provides a comprehensive overview of database management concepts, focusing on triggers and views in SQL. It includes detailed instructions for creating triggers to manage insurance calculations and maintenance records in a vehicle database, as well as explanations of views and their operations. Additionally, it outlines the conditions under which views can be updated and the implications of such updates on underlying tables.

Uploaded by

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

Vidyashilp University

Databases Management
Semester-IV
2023-24
Lab-6
28 th March 2024
Objectives:
 Triggers
 Views

TRIGGERS
A trigger is a special type of stored procedure that automatically runs when an event occurs in the database.

CREATE TRIGGER Trigger_Name


{BEFORE | AFTER | INSTEAD OF} {INSERT | UPDATE | DELETE | TRUNCATE}
ON Table_Name
[FOR EACH ROW]
[WHEN (condition)]
BEGIN
-- Trigger body: SQL statements to be executed when the trigger fires
END;
Exercise:
Create a database called vehicle
 create database vehicle
 use vehicle
CREATE TABLE CARS (
CAR_ID INT AUTO_INCREMENT PRIMARY KEY,
MAKE VARCHAR(50),
MODEL VARCHAR(50),
MYEAR INT,
COLOR VARCHAR(20),
MILEAGE DECIMAL(10,2),
PRICE DECIMAL(10,2),
INSURANCE DECIMAL(10,2)
);

INSERT INTO CARS (MAKE,MODEL,MYEAR,COLOR,MILEAGE,PRICE,INSURANCE) VALUES


('MAHINDRA','SUV','2007','BLACK',14,1350000,250000);
SELECT * FROM CARS;

Create a TRIGGER TO UPDATE THE INSURANCE COLUMN WHEN THE PRICE OF THE VEHICLE IS PROVIDED.

CREATE TRIGGER COMPUTE_INSURANCE


BEFORE INSERT
ON CARS
FOR EACH ROW
SET NEW.INSURANCE=((NEW.PRICE*0.05)+NEW.PRICE);

INSERT INTO CARS (MAKE,MODEL,MYEAR,COLOR,MILEAGE,PRICE) VALUES


('MARUTHI','HATCHBACK','2017','RED',22,550000);
INSERT INTO CARS (MAKE,MODEL,MYEAR,COLOR,MILEAGE,PRICE) VALUES
('KIA','SEDAN','2022','SILVER',18,650000);

SELECT * FROM CARS; // check the output


Insert the following values and observe the output using select statements.

2 Maruthi hatchback 2017 Red 22.00 550000.00


3 KIA Sedan 2022 Silver 18.00 650000.00
4 Benz Sedan 2023 White 10.00 6550000.00
5 Maruthi MUV 2020 JetBlue 14.00 970000.00
6 Kia Sedan 2021 Red 18.00 650000.00

Write a trigger which updates the insurance if the Price of the vehicle is updated.

CREATE TRIGGER RECAL_INSURANCE Write your observation here.


BEFORE UPDATE
ON CARS The insurance values for existing cars will be recalculated
FOR EACH ROW to be 10% of their old prices. The trigger will be using
SET NEW.INSURANCE=OLD.PRICE*0.10; before updating of each row. So, the insurance will not be
Update the price updated according to old row prices.
Update increases the price of car by 100000, now the
UPDATE CARS SET PRICE=PRICE+100000; trigger recalculates based on 10% for the new car prices.
SELECT * FROM CARS;

Create Car Maintenance_Record

CREATE TABLE C_MAINTENANCE (


CAR_MID INT,
MAKE VARCHAR(50),
MODEL VARCHAR(50),
MYEAR INT,
COLOR VARCHAR(20),
INSURANCE DECIMAL(10,2)
);

Delete table cars; //Clear all the rows in the Table Car.
Create a Trigger to insert into the Table C_Maintenance when Table Car is inserted.
CREATE TRIGGER INSERT_MAINTENANCE
AFTER INSERT
ON CARS
FOR EACH ROW
INSERT INTO C_MAINTENANCE (CAR_MID,MAKE,MODEL,MYEAR,COLOR,INSURANCE)
VALUES(NEW.CAR_ID,NEW.MAKE,NEW.MODEL,NEW.MYEAR,NEW.COLOR,NEW.INSURANCE);

Insert the following into cars table.

insert into cars (make,model,myear,color,mileage,price) values ('Maruthi','hatchback','2017','red',22,550000);


insert into cars (make,model,myear,color,mileage,price) values ('kia','sedan','2022','silver',18,650000);
insert into cars (make,model,myear,color,mileage,price) values ('toyota','suv','2024','black',10,3250000);
SELECT * FROM CARS;
SELECT * FROM C_MAINTENANCE;

What is your Observation?


UPDATE CARS SET PRICE=PRICE+100000;
SELECT * FROM CARS; Before updating it will copies same values to the
SELECT * FROM C_MAINTENANCE; maintenance insurance column.This is because of trigger.

Now the price of car increases by 100000, Now after


updating the values will be not changing in insurance
because the updation will not trigger the maintenance
column. So it will be same as the old row values.
Write a trigger to update the C_maintenance table when car table is updated.

CREATE TRIGGER UPDATE_INSURANCE What is your Observation?


AFTER UPDATE Here the update trigger invokes the insurance values in
ON CARS car maintenance based on the new car prices of 100000
FOR EACH ROW in the car table. This is after updation of new car prices. If
UPDATE C_MAINTENANCE SET trigger applied only the values of new insurance will
INSURANCE=NEW.INSURANCE WHERE recalculate other wise it will just update.
CAR_MID=NEW.CAR_ID;
UPDATE CARS SET PRICE=PRICE+100000;
SELECT * FROM CARS;
SELECT * FROM C_MAINTENANCE;

Delete Trigger: Write a trigger to delete column in C_maintenance if the row is deleted in cars.
CREATE TRIGGER DEL_MAINTENANCE Write your observation here
AFTER DELETE
ON CARS Now the cars and maintenance table is triggered for
FOR EACH ROW deletion. If any row of cars is deleted the corresponding
DELETE FROM C_MAINTENANCE WHERE row that is mid of maintenance will be deleted. So there
CAR_MID=OLD.CAR_ID; is no mis match between the tables.

SELECT * FROM CARS;


SELECT * FROM C_MAINTENANCE;

DELETE FROM CARS WHERE CAR_ID=9; Write your observation here.

SELECT * FROM CARS; Here the car id 9 is deleted, so the corresponding row of
SELECT * FROM C_MAINTENANCE; Car maintenance table is also get deleted because of the
del_maintenance trigger. So finally, the table will only
show the remaining ids rows and not the row with Car id
= 9.
What is a View?

 Views in SQL are a kind of virtual table.

 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 conditions.

 A view is nothing more than a SQL statement that is


stored in the database with an associated name

Why Views are required?

 To Structure data in a way that users find natural or intuitive.


 To Summarize data from various tables which can be used to generate reports.
 To Restrict access to the data in such a way that a user can see and/or modify exactly what they need and no more.

Syntax

CREATE VIEW view_name AS


SELECT column1, column2, ...
FROM table_name
WHERE condition;
Examples of Views:

1 Create a view named ‘car_view’ to view the details of create view car_view as
car_id, make, model from the table ‘cars’ select car_id, make, model from cars;

Display the values of the created view ‘car_view’ select * from car_view;

2 Create a view named ‘car_maintenance’ to view the details create view car_maintenance as
of car_mid, make, myear, insurance from the table select car_mid, make, myear, insurance from
‘c_maintenance’ c_maintenance;

Display the values of the created view ‘car_maintenance’ select * from car_maintenance;

3 Create a view named ‘HighMileageCars’ with mileage of create view HighMileageCars as


cars greater than 15 select * from cars
where mileage > 15;

Display the values of the created view ‘HighMileageCars’ select * from HighMileageCars;

4 Create a view named ‘RecentCars’ with a Year of create view RecentCars as


manufacturing greater than 2015 select * from cars
where myear > 2015;
Display the values of the created view ‘RecentCars’ select * from RecentCars;

Operations which can be performed on Views in SQL:

Inserting the values, Deleting the values, Modifying the values, Altering the View and Dropping the View.

Updating the values of the view ‘car_view’ update car_view set make='Century' where car_id=1;

Display the Updated View Table select * from car_view;

WHAT WILL HAPPEN TO THE DATA OF MAIN TABLE ‘CARS’ WHEN VIEW ‘CAR_VIEW’ was Updated?

Display the original table from which View select * from cars;
Table was made

What is your Observation?

UPDATE operation on a view, might indirectly affect the underlying tables depending on various factors:

 Simple Views: If the view is based on a single table updating the view might directly modify the underlying table

 Complex Views: If the view is based on multiple tables or contains aggregate functions, joins or other complex
operations, updates will not be entertained, if entertained then it do not reflect on the underlying tables
Complex Views: Views involving two or more tables from a Database:

1 Create a view named ‘CarView1’ with car_id, Mileage, create view CarView1 as
MYear, and Insurance details from ‘Cars’ and select c.car_id, c.mileage, m.myear, m.insurance
‘C_Maintenance’ Tables from cars c, c_maintenance m
where c.car_id=m.car_mid;

select * from CarView1;


Display the values of the created view ‘CarView1’

2 Create a view called ‘CombinedCar’ which provides details create view CombinedCar as
of Make, Model, Myear and Insurance cost by combining select
both ‘Cars’ and C_Maintenance Tables c.MAKE AS CarMake,
c.MODEL AS CarModel,
m.MYEAR AS MaintenanceYear,
m.INSURANCE AS MaintenanceInsurance
from
Cars c
JOIN
C_Maintenance m ON c.Make = m.Make AND
c.Model = m.Model AND c.MYear = m.MYear;

Display the values of the created view ‘CombinedCar’


select * from CombinedCar;
3 Observe the View ‘Carmaintenancecost’ and note down the Create View Carmaintenancecost As
Output for the same. Select
C.*,
What does select c.* selecting from the table ‘Cars’? M.Insurance As Maintenancecost
From
Cars C
Join
C_Maintenance M On C.Make = M.Make AND
C.Model = M.Model And C.Myear = M.Myear;
Display the values of the created view Select * from Carmaintenancecost;
‘Carmaintenancecost’
4 Observe the View and note down the reason for the Error CREATE VIEW CombinedCarMaintenance AS
Message for this View SELECT
c.*,
m.*
FROM
CARS c, C_Maintenance m;

Select * From CombinedCarMaintenance;

Inserting the values into the Complex View

insert into CarView1(car_id, mileage, MYEAR, insurance) What is your Observation while trying to Insert values
values (19, 21, 2023, 14500); to this complex view ‘CarView1’?

Since it is a complex view, Inserting/ Updating will not


be allowed for most of the complex ‘Views’

Write down your Observations for the following questions:


1. What will happen to the Data of the Underlying Write down your Observation.
Tables when the Contents of Simple View are
Updated or Inserted?

2. What will happen to the Data of the View Table Write down your Observation.
when the contents of the Underlying Table /
Main Table are Updated or Inserted?
3. What will happen to the Structure of the Write down your Observation.
Underlying Tables when the Structure of Simple
View is Altered using Alter Command?
4. What will happen to the Structure of the Simple Write down your Observation.
View when the Structure of its Underlying Table
is Altered using Alter Command?

A view can be updated under certain conditions which are given below:

 The SELECT clause may not contain the keyword DISTINCT.


 The SELECT clause may not contain summary functions.
 The SELECT clause may not contain set functions.
 The SELECT clause may not contain set operators.
 The SELECT clause may not contain an ORDER BY clause.
 The FROM clause may not contain multiple tables.
 The WHERE clause may not contain subqueries.
 The query may not contain GROUP BY or HAVING.

You might also like