ADBMS Lab Manual
ADBMS Lab Manual
Engineering
LAB MANUAL
Chandigarh University
Gharuan, Mohali
Syllabus
Institute/Department UNIVERSITY Program Bachelor of Engineering in
INSTITUTE OF Computer Science and
ENGINEERING (UIE) Engineering (Hons.) IBM -
artificial intelligence &
machine learning(CS222)
Master Subject Ms. Amanpreet Kaur Master Subject E13851
Coordinator Name: Coordinator E- Code:
Course Name Advanced Database Course Code CSH-434
Management Lab
Mission of Providing world class infrastructure, renowned academicians and ideal environment for Research,
the Innovation, Consultancy and Entrepreneurship relevant to the society.
University
Offering programs & courses in consonance with National policies for nation building and meeting
global challenges.
Designing Curriculum to match international standards, needs of Industry, civil society and for
inculcation of traits of Creative Thinking and Critical Analysis as well as Human and Ethical
values.
Ensuring students delight by meeting their aspirations through blended learning, corporate
mentoring, professional grooming, flexible curriculum and healthy atmosphere based on
cocurricular and extra-curricular activities.
Establishing strategic relationships with leading National and International corporates and universities
for academic as well as research collaborations.
Contributing for creation of healthy, vibrant and sustainable society by involving in Institutional
Social Responsibility (ISR) activities like rural development, welfare of senior citizens, women
empowerment, community service, health and hygiene awareness and environmental protection
Vision of the
University To be globally recognized as a Centre of Excellence for Research, Innovation, Entrepreneurship
and disseminating knowledge by providing inspirational learning to produce professional leaders
for serving the society.
Mission of the M1: To provide relevant, rigorous and contemporary curriculum and aligned assessment system to
Department ensure effective learning outcomes for engineering technologies.
M2: To provide platform for industry engagement aimed at providing hands-on training on advanced
technological and business skills to our students.
M3: To provide opportunities for collaborative, interdisciplinary and cutting-edge research aimed at
developing solutions to real life problems
M4: To imbibe quest for innovation, continuous learning and zeal to pursue excellence through hard
work and problem-solving approach
M5: To foster skills of leadership, management, communication, team spirit and strong professional
ethics in all academic and societal endeavors of our students
Vision of the To be recognized as a center of excellence for Computer Science & Engineering education and
Department research, through effective teaching practices, hands-on training on cutting edge computing
technologies and excellence in innovation, for creating globally aware competent professionals
with strong work ethics whom would be proficient in implementing modern technology solutions
and shall have entrepreneurial zeal to solve problems of organizations and society at large.
PEO To be able to design, and implement technology and computing solutions to the organizational
2 problems, effectively deploy knowledge of engineering principles, demonstrate critical thinking
skills&make the intellectual connections between quantitative and qualitative tools, theories and
context to solve the organizational problems
PEO To be able to work with, lead & engage big and small teams comprising diverse people in terms of
3 gender, nationality, region, language, culture & beliefs. To understand stated and unstated
differences of views, beliefs & customs in diverse & inter disciplinary team settings
PEO To be able to continuously learn and update one’s knowledge, engage in lifelong learning habits and
4 acquire latest knowledge to perform in current work settings
PEO To continuously strive for justice, ethics, equality, honesty, and integrity both in personal and
5 professional pursuits. Able to understand and conduct in a way that is responsible and respectful.
PSO1 The graduating student will be able to make valuable contributions in design, development, and production of
computer science and related engineering applications in the areas of Artificial intelligence and Machine
learning
PSO2 The graduating student will be able to use and deploy the latest software tools and technologies related to
Artificial intelligence and Machine learning.
PSO3 The graduating student will be able to practice as an engineer / researcher in the evolving field of AI and ML
and its allied application domains by employing project development skills learnt throughout the program
PSO4 The graduating student will be able to exhibit proficiency in Artificial Intelligence and Data Analytics for
providing solutions to real world problems in Industry and Research establishments.
Program OutComes(POs)
PO1 Engineering Knowledge: Apply knowledge of mathematics, science, engineering fundamentals and an
engineering specialization to the solution of complex engineering problems.
PO2 Problem Analysis: Identify, formulate, research literature and analyze complex engineering problems reaching
Substantiated conclusions using first principles of mathematics, natural sciences and engineering sciences.
PO3 Design/ Development of Solutions: Design solutions for complex engineering problems and design system
components or processes that meet specified needs with appropriate consideration for public health and
safety, cultural, societal and environmental considerations
PO4 Conduct investigations of complex problems using research-based knowledge and research methods including
design of experiments, analysis and interpretation of data and synthesis of information to provide valid
conclusions.
PO5 Modern Tool Usage: Create, select and apply appropriate techniques, resources and modern engineering and IT
tools Including prediction and modeling to complex engineering activities with an understanding of the
limitations
PO6 The Engineer and Society: Apply reasoning informed by contextual knowledge to assess societal, health, safety,
legal and Cultural issues and the consequent responsibilities relevant to professional engineering practice.
PO7 Environment and Sustainability: Understand the impact of professional engineering solutions in societal and
Environmental contexts and demonstrate knowledge of and need for sustainable development.
PO8 Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of engineering
practice.
PO9 Individual and Team Work: Function effectively as an individual, and as a member or leader in diverse teams
and in multi-disciplinary settings.
PO10 Communication: Communicate effectively on complex engineering activities with the engineering
community and with society at large, such as being able to comprehend and write effective reports and
design documentation, make effective presentations and give and receive clear instructions.
PO11 Project Management and Finance: Demonstrate knowledge and understanding of engineering and
management principles and apply these to one's own work, as a member and leader in a team, to
manage projects and in multidisciplinary environments
PO12 Life-long Learning: Recognize the need for and have the preparation and ability to Engage in independent and
life- long learning in the broadest context of technological Change.
Course Objective
Course Objective
1 Develop understanding the advancement in SQL
3 Use and application of normalization techniques and implement the concept of triggers.
Course Outcome
Course Outcome
CO2 Create views of data and Implement transaction control using locks.
CO3 Apply the concept of PL/SQL programming for control structures and cursors
S.NO. CO
Unit-I
3 Experiment 1.3 To analyze and create locks and different types of locks. CO2
Experiment 1.4 To create and perform queries on sequences, synonyms and CO2
4 views.
Unit 2
Unit 3
Experiment 3.2 Prepare a Case Study explaining the need for converting CO5
9 tables to fourth and fifth Normal forms.
Experiment No. 1
Mapped Course Outcomes- CO1
CO1: Execute and apply advanced level SQL queries.
Objective: Create a database for Company, add employee details into it as a part of
transaction. Analyse the role of Commit, Rollback and Save point.
Apparatus Required:
A single unit of work in a database is formed after the consecutive execution of commands is
known as a transaction.
There are certain commands present in SQL known as TCL commands that help the user
manage the transactions that take place in a database.
COMMIT, ROLLBACK and SAVEPOINT are the most commonly used TCL commands in
SQL.
COMMIT:
COMMIT command in SQL is used to save all the transaction-related changes permanently to
the disk. Whenever DDL commands such as INSERT, UPDATE and DELETE are used, the
changes made by these commands are permanent only after closing the current session. So
before closing the session, one can easily roll back the changes made by the DDL commands.
Hence, if we want the changes to be saved permanently to the disk without closing the session,
we will use the commit command.
Syntax:
COMMIT;
Program Code:
CREATE TABLE t_Company(ID INT, Company_Name VARCHAR(40), Number_Of_Empl
oyees INT, Number_Of_Project_Managers INT, EmailID VARCHAR(40));
BEGIN TRANSACTION;
INSERT INTO t_Company(ID, Company_Name, Number_Of_Employees, Number_Of_Proj
ect_Managers, EmailID) VALUES(1, "XYZ Public Company", 1000, 12, "xyz15@gmail.com
"), (2, "ABCDPublic Company", 800, 35, "abcd25@gmail.com"), (3, "Agra Public Company
", 1200, 10, "agra101@gmail.com"), (4, "imperial Company", 1110, 40,"imperial@gmail.co
m”);
COMMIT;
Output :
ID Company_Name Number_of Number_of_Project_Ma EmailID
_Employees nagers
1 XYZ Public Comp 1000 80 xyz15@gmail.com
any ")
2 ABCDPublic Co 800 35 abcd25@gmail.co
mpany m
3 Agra Public Com 1200 30 agra101@gmail.c
pany om
4 imperial Compan 1110 40 imperial@gmail.c
y om
Database Table will be created using name t_Company and data will be inserted. Commit
Command Will save the data permanently.
SAVEPOINT operation:
A SAVEPOINT is a point in a transaction when you can roll the transaction back to a certain
point without rolling back the entire transaction.
Syntax:
SAVEPOINT SAVEPOINT_NAME;
ROLLBACK operation:
The ROLLBACK command is the transactional command used to undo transactions that have
not already been saved to the database. This command can only be used to undo transactions
since the last COMMIT or ROLLBACK command was issued.
Syntax:
ROLLBACK;
Program Code:
BEGIN TRANSACTION;
SAVEPOINT Insertion;
SAVEPOINT Updation;
ROLLBACK TO Insertion;
Output:
ID Company_Name Number_of Number_of_ EmailID
_Employees Project_Ma
nagers
1 XYZ Public Company 1000 80 xyz15@gmail.com
")
2 ABCDPublic Company 800 35 abcd25@gmail.co
m
3 Agra Public Company 1200 30 agra101@gmail.c
om
4 imperial Company 1110 40 imperial@gmail.c
om
Text Book:
Reference Book:
Web Reference:
1. https://www.javatpoint.com/tcl-commands-
insql#:~:text=In%20SQL%2C%20TCL%20stands%20for,take%20place%20in%20a%2
0database.
2. https://www.geeksforgeeks.org/tcl-
fullform/#:~:text=TCL%20stands%20for%20Transaction%20Control,the%20data%20s
to red%20in%20DBMS. Video:
https://youtu.be/W0dJ8e_IIZI
Viva Question:
Experiment No. 2
Mapped Course Outcomes- CO1
Objective: Use a Database crated in Experiment 1 and Grant permission to user at various
level.
Apparatus Required:
sysdba is a set of priviliges which has all the permissions in it. So if we want to provide all
the privileges to any user, we can simply grant them the sysdba permission.
When we create a user in SQL, it is not even allowed to login and create a session until and
unless proper permissions/priviliges are granted to the user. Following command can be used
to grant the session creating priviliges.
To allow a user to create tables in the database, we can use the below command,
Allowing a user to create table is not enough to start storing data in that table. We also must
provide the user with priviliges to use the available tablespace for their table and data.
The above command will alter the user details and will provide it access to unlimited
tablespace on system.
Sometimes user is restricted from creating come tables with names which are reserved for
system tables. But we can grant privileges to a user to create any table using the below
command,
As the title suggests, if you want to allow user to drop any table from the database, then grant
this privilege to the user,
And, if you want to take back the privileges from any user, use the REVOKE command.
Program Code:
GRANT CREATE ANY TABLE TO username GRANT DROP ANY TABLE TO username
Output:
Revoke Command: The Oracle REVOKE statement revokes system and object privileges
from a user.
To revoke all system privileges from a user, you can use the following statement:
Program Code:
Text Book:
Reference Book:
Viva Questions:
Experiment No. 3
CO2: Create views of data and Implement transaction control using locks.
Objective: Lock a flight table in share mode and in some other possible manner.
Apparatus Required:
MySQL also allows table locking to prevent it from unauthorized modification into the same
table during a specific period.
Table Locking in MySQL is mainly used to solve concurrency problems. It will be used while
running a transaction, i.e., first read a value from a table (database) and then write it into the
table (database).
MySQL provides two types of locks onto the table, which are:
READ LOCK: This lock allows a user to only read the data from a table.
WRITE LOCK: This lock allows a user to do both reading and writing into a table.
Default storage engine used in MySQL is InnoDB. The InnoDB storage engine does not
require table locking manually because MySQL automatically uses row-level locking for
InnoDB tables.
Therefore, we can do multiple transactions on the same table simultaneously to read and write
operations without making each other wait. All other storage engines use table locking in
MySQL.
The LOCK TABLE statement allows you to explicitly acquire a shared or exclusive table
lock on the specified table. The table lock lasts until the end of the current transaction.
Syntax:
Program Code:
To lock the entire Flights table in share mode to avoid a large number of row locks, use the
following statement:
LOCK TABLE Flights IN SHARE MODE;
SELECT *
FROM Flights
WHERE orig_airport > 'OOO';
Output:
Text Book:
Reference Book:
Web Reference:
1. https://docs.oracle.com/cd/B13789_01/server.101/b10759/statements_9015.htm#:~:te
xt=RW%20EXCLUSIVE%20is%20the%20same,updating%2C%20inserting%2C%2
0or%20deleting.&text=See%20ROW%20SHARE%20.&text=SHARE%20permits%2
0concurrent%20queries%20but%20prohibits%20updates%20to%20the%20locked%2
0table.
2. https://www.ibm.com/docs/en/informix-servers/14.10?topic=scope-row-key-locks
Viva Questions:
1. What is use of locks?
2. Why are the different type of locks?
3. How locks ensure concurrency?
4. What is Row Exclusive Lock?
5. Why do we use various level of locking?
6. What is difference between share mode and exclusive mode of locking?
7. How can we create locks?
8. What is other name of share lock?
Experiment No. 4
Mapped Course Outcomes- CO2
CO2: Create views of data and Implement transaction control using locks. AIM:
Objective: Create table and create sequence. Use this sequence to add data in sequence in it. Create Synonym
and Views. Drop and update a View.
Apparatus Required:
A computer system with Oracle 10g installed
Sequences are frequently used in many databases because many applications require each row
in a table to contain a unique value and sequences provides an easy way to generate them.
INCREMENT BY increment_value
Initial_value should be greater than or equal to minimum value and less than equal to
maximum value.
maximum_value: Maximum value of the sequence. cycle: When sequence reaches its
start with 1
increment by 1
minvalue 0
Program Code: create a table named students with columns as id and name.
CREATE TABLE students
( ID number(10), NAME char(20) );
Output:
ID NAME
1 Ramesh
2 Suresh
SYNONYMS
A SYNONYM provides another name for database object, referred to as original object, that
may exist on a local or another server. A synonym belongs to schema, name of synonym should
be unique. A synonym cannot be original object for an additional synonym and synonym cannot
refer to user-defined function.
The query below results in an entry for each synonym in database. This query provides details
about synonym metadata such as the name of synonym and name of the base object.
select * from
sys.synonyms ;
Syntax –
FOR servername.databasename.schemaname.objectname;
Views:
A view contains rows and columns, just like a real table. The fields in a view are fields from
one or more real tables in the database.
You can add SQL statements and functions to a view and present the data as if the data were
coming from one single table.
A view is created with the CREATE VIEW statement.
VIEW view_name AS
FROM table_name
WHERE condition;
Program Code:
CREATE VIEW Customers AS
FROM Customers
Output:
Program Code:
DROP VIEW Customers;
Output:
WHERE condition;
Program Code:
CREATE OR REPLACE VIEW Customers AS
FROM Customers
Output:
Text Book:
Reference Book:
1. https://www.mssqltips.com/sqlservertip/6219/create-alter-drop-and-query-sql-server-views/
Video:
https://youtu.be/Ja5-aVI1TBY
Viva Questions:
1. Why do we use the Views?
2. What the role of Sequence?
3. How do we can set the minimum and maximum value of a sequence?
4. How do we can create a synonym?
5. How to create view?
6. Which attribute can be used with SEQUENCE to set a starting sequence?
7. Which commands is used to drop a view?
8. Which command is used to replace a view?
9. What is the role of synonyms?
10. How to create sequence?
Experiment No.5
Mapped Course Outcomes- CO3
CO3: Apply the concept of PL/SQL programming for control structures and cursors
Objective: Write PL/SQL commands using control structure to give bonus to employee if
sales is greater than his /her quota.
Apparatus Required:
A computer system with Oracle 10g installed.
Conditional selection statements, which run different statements for different data values.
2. CASE statements
Loop statements, which run the same statements with a series of different data values.
1.LOOP
2. FOR LOOP
3. WHILE LOOP
The EXIT statement transfers control to the end of a loop. The CONTINUE statemnt exits the
current iteration of a loop and transfers control to
the next iteration. Both EXIT and CONTINUE have an optional WHEN clause, where
you can specify a condition.
The sequential control statements are GOTO, which goes to a specified statement, and
NULL, which does nothing.
The IF THEN statement has this structure:
Syntax:
IF condition THEN
statements
END IF;
•If the condition is true, the statement run; otherwise the IF statement does nothing.
Program Code:
DECLARE
sales NUMBER(8,2) := 12100;
quota NUMBER(8,2) := 10000;
bonus NUMBER(6,2);
emp_id NUMBER(6) := 120;
BEGIN
IF sales > (quota + 200) THEN
bonus := (sales - quota)/4;
ELSE
bonus := 50;
END IF;
UPDATE employees SET salary = salary + bonus WHERE employee_id = emp_id;
END;
Output:
Output:
Values will be update based on the if and nested if condition and program is executed
successfully.
Text Book:
Reference Book:
Web Reference:
1. https://www.tutorialspoint.com/plsql/plsql_loops.htm
2. https://tutorialink.com/dbms/control-structures.dbms
3. https://docs.oracle.com/cd/E18283_01/appdev.112/e17126/controlstatements.htm
#:~:text=PL%2FSQL%20has%20three%20categories,series%20of%20different%20d
ata%20values.
Video:
https://www.youtube.com/embed/5jj6hE1rvek?feature=oembed
Viva Question:
CO3: Apply the concept of PL/SQL programming for control structures and cursor
Apparatus Required:
A computer system with Oracle 10g installed
You can name a cursor so that it could be referred to in a program to fetch and process the
rows returned by the SQL statement, one at a time. There are two types of cursors −
•Implicit cursors
•Explicit cursors
Implicit Cursors:
•Implicit cursors are automatically created by Oracle whenever an SQL statement is executed,
when there is no explicit cursor for the statement. Programmers cannot control the implicit
cursors and the information in it.
•Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an implicit cursor
is associated with this statement. For INSERT operations, the cursor holds the data that needs
to be inserted. For UPDATE and DELETE operations, the cursor identifies the rows that
would be affected.
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 PL/SQL Block. It is
created on a SELECT Statement which returns more than one row.
Declaring the cursor defines the cursor with a name and the associated SELECT statement.
For example −
CURSOR c_customers IS
Opening the cursor allocates the memory for the cursor and makes it ready for fetching the
rows returned by the SQL statement into it. For example, we will open the above defined cursor
as follows −
Input:
Program Code:
DECLARE
c_id customers.id%type;
c_name customers.name%type;
c_addr customers.address%type;
CURSOR c_customers is
SELECT id, name, address FROM customers;
BEGIN
OPEN c_customers;
LOOP
FETCH c_customers into c_id, c_name, c_addr;
EXIT WHEN c_customers%notfound;
dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);
END LOOP;
CLOSE c_customers;
END;
/
Output:
Text Book:
Reference Book:
Web Reference:
1. https://www.tutorialspoint.com/plsql/plsql_cursors.htm
2. https://www.geeksforgeeks.org/cursors-in-pl-sql/
Viva Questions:
1. What is role of Cursor?
2. What is the different type of the cursors used?
3. How do we cursors?
4. Name the SQL command with whom the implicit cursor is always associated?
5. What is the difference between implicit and explicit cursor?
6. Can you write program code to create a cursor?
7. Can you write a code to open a cursor?
8. Implicit cursors are automatically created in the oracle or do we need to create
separately?
Experiment No. 7
Mapped Course Outcomes- CO3, CO4
CO3: Apply the concept of PL/SQL programming for control structures and cursors.
CO4: Apply the concept of PL/SQL programming for performing operations on packages and
triggers.
Apparatus Required:
A computer system with Oracle 10g installed
•System-defined exceptions
•User-defined exceptions
Using exceptions for error handling has several advantages. Without exception handling,
every time you issue a command, you must check for execution errors:
Error processing is not clearly separated from normal processing; nor is it robust. If you
neglect to code a check, the error goes undetected and is likely to cause other, seemingly
unrelated errors.
With exceptions, you can handle errors conveniently without the need to code multiple
checks, as follows:
BEGIN
SELECT ...
SELECT ...
SELECT ...
...
EXCEPTION
Exceptions improve readability by letting you isolate error-handling routines. The primary
algorithm is not obscured by error recovery algorithms. Exceptions also improve reliability.
You need not worry about checking for an error at every point it might occur. Just add an
exception handler to your PL/SQL block. If the exception is ever raised in that block (or any
sub-block), you can be sure it will be handled.
User-defined Exceptions
PL/SQL allows you to define your own exceptions according to the need of your program. A
user-defined exception must be declared and then raised explicitly, using either a RAISE
statement or the procedure DBMS_STANDARD.RAISE_APPLICATION_ERROR.
DECLARE
my-exception EXCEPTION;
Exceptions can be declared only in the declarative part of a PL/SQL block, subprogram, or
package. You declare an exception by introducing its name, followed by the keyword
EXCEPTION.
Exception and variable declarations are similar. But remember, an exception is an error
condition, not a data item. Unlike variables, exceptions cannot appear in assignment
statements or SQL statements. However, the same scope rules apply to variables and
exceptions.
Program Code:
DECLARE
out_of_stock EXCEPTION;
number_on_hand NUMBER(4); BEGIN
IF number_on_hand < 1 THEN
RAISE out_of_stock;
END IF;
EXCEPTION
WHEN out_of_stock THEN
dbms_output.put_line('No such customer!');
END;
Output:
Text Book:
Reference Book:
Web Reference:
https://www.tutorialspoint.com/plsql/plsql_exceptions.htm
Viva Question:
1. Why Exceptions occurs?
2. What are type of Exception?
3. How do we can handle it?
4. What System defined exception are different from user-defined exceptions?
5. How can we raise exception?
6. Name some of the System defined Exceptions?
7. How can you create your exception?
8. Which command is used to handle the Exception?
9. What are the advantages of exception handling?
10. Why exception handling is required?
Experiment No. 8
Mapped Course Outcomes- CO4
CO4: Apply the concept of PL/SQL programming for performing operations on packages and
triggers.
Apparatus Required:
A computer system with Oracle 10g installed
Packages:
Packages are schema objects that groups logically related PL/SQL types, variables and
subprograms. A package will have two mandatory parts:
• Package specification
Package Specification:
The specification is the interface to the package. It just DECLARES the types, variables,
constants, exceptions, cursors, and subprograms that can be referenced from outside the
package. In other words, it contains all information about the content of the package, but
excludes the code for the subprograms.
All objects placed in the specification are called public objects. Any subprogram not in the
package specification but coded in the package body is called a private object.
The following code snippet shows a package specification having a single procedure. You can
have many global variables defined and multiple procedures or functions inside a package.
Program Code:
CREATE PACKAGE cust_sal AS
PROCEDURE find_sal(c_id number);
END cust_sal;
/
Output:
When the above code is executed at SQL prompt, it produces the following result:
Package Body:
When the above code is executed at SQL prompt, it produces the following result: Package
body created
The package body has the codes for various methods declared in the package specification
and other private declarations, which are hidden from code outside the package.
The CREATE PACKAGE BODY Statement is used for creating the package body. The
following code snippet shows the package body declaration for the cust_sal package created
above.
Program Code:
CREATE OR REPLACE PACKAGE BODY cust_sal AS
PROCEDURE find_sal(c_id customers.id%TYPE) IS c_sal
customers.salary%TYPE;
BEGIN
SELECT salary INTO c_sal
FROM customers
WHERE id = c_id;
dbms_output.put_line('Salary: '|| c_sal);
END find_sal;
END cust_sal;
/
Output:
When the above code is executed at SQL prompt, it produces the following result:
Program Code:
DECLARE
code customers.id%type := &cc_id; BEGIN
cust_sal.find_sal(code);
END;
/
Output:
When the above code is executed at SQL prompt, it prompts to enter customer ID, and when
you enter an ID, it displays the corresponding salary as follows:
Triggers:
Triggers are stored programs, which are automatically executed or fired when some events
occur. Triggers are, in fact, written to be executed in response to any of the following events:
• A database manipulation (DML) statement (DELETE, INSERT, or UPDATE).
• A database definition (DDL) statement (CREATE, ALTER, or DROP).
• A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or
SHUTDOWN).
Triggers could be defined on the table, view, schema, or database with which the event is
associated.
Creating Triggers
The syntax for creating a trigger is:
Where,
CREATE [OR REPLACE] TRIGGER trigger_name : Creates or replaces an existing trigger
with the trigger_name.
• {BEFORE | AFTER | INSTEAD OF}: This specifies when the trigger would be
executed. The INSTEAD OF clause is used for creating trigger on a view.
• {INSERT [OR] | UPDATE [OR] | DELETE}: This specifies the DML operation.
• [OF col_name]: This specifies the column name that would be updated.
• [ON table_name]: This specifies the name of the table associated with the trigger.
• [REFERENCING OLD AS o NEW AS n]: This allows you to refer new and old
values for various DML statements, like INSERT, UPDATE, and DELETE.
• [FOR EACH ROW]: This specifies a row level trigger, i.e., the trigger would be
executed for each row being affected. Otherwise the trigger will execute just once
when the SQL statement is executed, which is called a table level trigger.
• WHEN (condition): This provides a condition for rows for which the trigger would
fire.
This clause is valid only for row level triggers.
To start with, we will be using the CUSTOMERS table:
Select * from customers;
+ + + + + -+
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
|1 | Ramesh| 32 | Ahmedabad | 2000.00 |
|2 | Khilan | 25 | Delhi | 1500.00 |
|3 | Kaushik | 23 | Kota | 2000.00 |
|4 | Chaitali | 25 | Mumbai | 6500.00 |
|5 | Hardik | 27 | Bhopal | 8500.00 |
|6 | Komal | 22 | MP | 4500.00 |
+ + + + + +
he following program creates a row level trigger for the customers table that would fire for
INSERT or UPDATE or DELETE operations performed on the CUSTOMERS table. This
trigger will display the salary difference between the old values and new values:
Program Code:
CREATE OR REPLACE TRIGGER display_salary_changes
BEFORE DELETE OR INSERT OR UPDATE ON customers
FOR EACH ROW
WHEN (NEW.ID > 0)
DECLARE
sal_diff number;
BEGIN
sal_diff := :NEW.salary - :OLD.salary;
dbms_output.put_line('Old salary: ' || :OLD.salary);
dbms_output.put_line('New salary: ' || :NEW.salary);
dbms_output.put_line('Salary difference: ' || sal_diff);
END;
/
Output:
When the above code is executed at SQL prompt, it produces the following result:
Trigger created.
Here following two points are important and should be noted carefully:
• OLD and NEW references are not available for table level triggers, rather you can use
them for record level triggers.
• If you want to query the table in the same trigger, then you should use the AFTER
keyword, because triggers can query the table or change it again only after the initial
changes are applied and the table is back in a consistent state.
• Above trigger has been written in such a way that it will fire before any DELETE or
INSERT or UPDATE operation on the table, but you can write your trigger on a single
or multiple operations, for example BEFORE DELETE, which will fire whenever a
record will be deleted using DELETE operation on the table.
Text Book:
Reference Book:
Web Reference:
1. https://www.tutorialspoint.com/plsql/plsql_packages.htm
2. https://docs.oracle.com/cd/B19306_01/server.102/b14200/statements_6006.ht m
Viva Question:
1. Why do we create Packages?
2. Why do we create triggers?
3. How do we create triggers?
4. Why do we need package body?
5. Why do we need package specifications?
6. Write code for the create trigger?
7. How do we specify when the trigger will be executed?
8. How do we specify which column need to be updated?
Experiment No.- 9
AIM: Prepare a Case Study explaining the need for converting tables to fourth and fifth
Normal forms.
Objective: Understand the process of converting table into fourth and fifth Normal forms.
• Attribute of one or more rows in the table should not result in more than one rows of the same
table leading to multi-valued dependencies
Case Study: To understand the need of converting table in to fourth normal form, we should
understand that we are trying to reduce multivalued dependency. consider a table with Subject, Lecturer
who teaches each subject and recommended Books for each subject.
If we observe the data in the table above it satisfies 3NF. But LECTURER and BOOKS are two
independent entities here. There is no relationship between Lecturer and Books. In the above case study
either Alex or Bosco can teach Mathematics. For Mathematics subject , student can refer either ‘Maths
Book1’ or ‘Maths Book2’.
Solution:
To eliminate this dependency, we divide the table into two as below:
Now if we want to know the lecturer names and books recommended for any of the subject, we
will fire two independent queries. Hence it removes the multi-valued dependency and
confusion around the data. Thus the table is in 4NF
• It’s in 4NF
• If we can decompose table further to eliminate redundancy and anomaly, and when
we re-join the decomposed tables by means of candidate keys, we should not be
losing the original data or any new record set should not arise. In simple words,
joining two or more decomposed table should not lose records nor create new records.
Case Study: Consider an case study of different Subjects taught by different lecturers and
the lecturers taking classes for different semesters.
Note: Please consider that Semester 1 has Mathematics, Physics and Chemistry and Semester
2 has only Mathematics in its academic year!!
In above table, Rose takes both Mathematics and Physics class for Semester 1, but she does not
take Physics class for Semester 2. In this case, combination of all these 3 fields is required to
identify a valid data. Imagine we want to add a new class – Semester3 but do not know which
Subject and who will be taking that subject. We would be simply inserting a new entry with
Class as Semester3 and leaving Lecturer and subject as NULL. As we discussed above, it’s not
a good to have such entries. Moreover, all the three columns together act as a primary key, we
cannot leave other two columns blank!
Solution:
Hence we have to decompose the table in such a way that it satisfies all the rules till 4NF and
when join them by using keys, it should yield correct record. Here, we can represent each
lecturer’s Subject area and their classes in a better way. We can divide above table into three –
(SUBJECT, LECTURER), (LECTURER, CLASS), (SUBJECT, CLASS)
Now, each of combinations is in three different tables. If we need to identify who is teaching
which subject to which semester, we need join the keys of each table and get the result.
For example, who teaches Physics to Semester 1, we would be selecting Physics and Semester1
from table 3 above, join with table1 using Subject to filter out the lecturer names. Then join
with table2 using Lecturer to get correct lecturer name. That is we joined key columns of each
table to get the correct data. Hence there is no lose or new data – satisfying 5NF condition.
Reference Book:
Viva Question:
1. What is Normalization?
2. What are 4th and 5th Normal forms?
3. Why do we need to convert relation in to 4 NF?
4. Why do we need to convert relation in to 5NF?
5. How can be convert relation into 4NF?
6. How can be convert relation into 5NF?
7. What is join Dependency?
8. What is multivalued dependency?
9. What is denormalization?
10. How do we achieve denormalization?
Experiment No. 10
Mapped Course Outcomes- CO5
CO5: Analyze and apply advanced normalization technique and redundant functional dependencies.
AIM: Prepare a Case Study on Functional dependency with examples for redundant
functional dependencies.
Objective: Analyse Functional dependency and find redundant functional dependencies and
remove them.
Functional Dependency
Functional dependency in DBMS, as the name suggests is a relationship between attributes of
a table dependent on each other. Introduced by E. F. Codd, it helps in preventing data
redundancy and gets to know about bad designs.
To understand the concept thoroughly, let us consider P is a relation with attributes A and B.
Functional Dependency is represented by -> (arrow sign)
Then the following will represent the functional dependency between attributes with an arrow
sign −
Functional Dependency:
A -> B
B- functionally dependent on A
A-determinant set
B- dependent attribute
Example
The following is an example that would make it easier to understand functional dependency −
We have a <Department> table with two attributes − DeptId and DeptName.
DeptId = Department ID
DeptName = Department Name
The DeptId is our primary key. Here, DeptId uniquely identifies the DeptName attribute. This
is because if you want to know the department name, then at first you need to have the
DeptId.
DeptId DeptName
001 Finance
002 Marketing
003 HR
Therefore, the above functional dependency between DeptId and DeptName can be
determined as DeptId is functionally dependent on DeptName −
DeptId -> DeptName
Steps:
1. F' = F - f //find out new set of
FDs by removing f from F.
Case Study:
Suppose, there is a relation R(A,B,X,Y,Z) and the following set of FDs is given for the table
R.
Z -> A
B -> X
AX -> Y
ZB -> Y.
Now, It is the case that these functional dependency must be implement for the table. Having
too many functional dependency increases the computational time. So, How can be reduce this
computational time?
Solution:
The following set of FDs is given for the table R.
Z -> A
B -> X
AX -> Y ZB
-> Y.
Hence, in this case study, we will apply these steps. It gives us following redundant functional
dependencies:
Because ZB -> Y Can be derived from other FDs in the set, it can be shown to be redundant.
The following argument can be given:
• Z -> A by augmentation rule will yield ZB -> AB.
• B -> X and AX -> Y by pseudo-transitivity rule will yield AB -> Y.
• ZB -> AB and AB -> Y by transitivity rule will yield ZB -> Y.
Output:
ZB -> Y is a redundant functional dependency. It must be removed.
Text Book:
Reference Book:
Web References:
1. https://www.javatpoint.com/dbms-functional-dependency
2. https://opentextbc.ca/dbdesign01/chapter/chapter-11-
functionaldependencies/#:~:text=A%20functional%20dependency%20(FD)%20is,deter
mines% 20the%20value%20of%20Y.
Viva Question:
1. Why we remove redundant functional dependency?
2. What is functional dependency?
3. How to remove redundant functional dependency?
4. What is the role of functional dependency?
5. What are the armstrong’s Axioms?
6. What is algorithm to remove redundant functional dependency?
7. What is trivial Functional dependency?
8. What is the prime Attribute?
9. What is the non-trivial functional dependency?
10. What is transitive functional dependency?