Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 70

KEYS

• Keys play an important role in the relational database.


• It is used to uniquely identify any record or row of data from the table. It is also
used to establish and identify relationships between tables.
• For example, ID is used as a key in the Student table because it is unique for each
student. In the PERSON table, passport_number, license_number, SSN are keys
since they are unique for each person.
 A set of one or more attributes whose values
uniquely identifies each record within a relation

 Super key is an attribute set that can uniquely


identify a tuple. A super key is a superset of a
candidate key.

 For example: In the above EMPLOYEE table, for(EMPLOEE_ID,


EMPLOYEE_NAME), the name of two employees can be the
same, but their EMPLYEE_ID can't be the same. Hence, this
combination can also be a key.
 A candidate key is an attribute or set of attributes that
can uniquely identify a tuple.
 Except for the primary key, the remaining attributes
are considered a candidate key. The candidate keys are
as strong as the primary key.
 For example: In the EMPLOYEE table, id is best suited
for the primary key. The rest of the attributes, like SSN,
Passport_Number, License_Number, etc., are
considered a candidate key.
 It is the first key used to identify one and only one instance of
an entity uniquely. An entity can contain multiple keys, as we
saw in the PERSON table. The key which is most suitable from
those lists becomes a primary key.
 In the EMPLOYEE table, ID can be the primary key since it is
unique for each employee. In the EMPLOYEE table, we can
even select License_Number and Passport_Number as primary
keys since they are also unique.
 For each entity, the primary key selection is based on
requirements and developers.
 Foreign keys are the column of the table used to point to
the primary key of another table.
 Every employee works in a specific department in a
company, and employee and department are two different
entities. So we can't store the department's information in
the employee table. That's why we link these two tables
through the primary key of one table.
 We add the primary key of the DEPARTMENT table,
Department_Id, as a new attribute in the EMPLOYEE
table.
 In the EMPLOYEE table, Department_Id is the foreign
key, and both the tables are related.
Alternate key
 There may be one or more attributes or a combination of attributes that uniquely identify each tuple in a
relation.
 These attributes or combinations of the attributes are called the candidate keys.
 One key is chosen as the primary key from these candidate keys, and the remaining candidate key, if it exists,
is termed the alternate key.
 In other words, the total number of the alternate keys is the total number of candidate keys minus the
primary key.
 The alternate key may or may not exist. If there is only one candidate key in a relation, it does not have an
alternate key.
 For example, employee relation has two attributes, Employee_Id and PAN_No, that act as candidate keys. In
this relation, Employee_Id is chosen as the primary key, so the other candidate key, PAN_No, acts as the
Alternate key.
Composite key
Whenever a primary key consists of more than one attribute, it is
known as a composite key. This key is also known as Concatenated
Key.

For example, in employee relations, we assume that an employee may be assigned multiple
roles, and an employee may work on multiple projects simultaneously. So the primary key will
be composed of all three attributes, namely Emp_ID, Emp_role, and Proj_ID in combination.
So these attributes act as a composite key since the primary key comprises more than one
attribute.
Artificial key
 The key created using arbitrarily assigned data are known as artificial keys.
 These keys are created when a primary key is large and complex and has no relationship
with many other relations.
 The data values of the artificial keys are usually numbered in a serial order.

For example, the primary key, which is composed of Emp_ID, Emp_role, and Proj_ID, is large in employee
relations.
So it would be better to add a new virtual attribute to identify each tuple in the relation uniquely.
Relational Algebra procedural query language
Language for expressing Relational DB queries

 RELATIONAL ALGEBRA is a widely used procedural query language.


 It collects instances of relations as input and gives occurrences of relations as output.
 It uses various operations to perform this action.
 SQL Relational algebra query operations are performed recursively on a relation.
 The output of these operations is a new relation, which might be formed from one or more input relations.

Relational Algebra divided in various groups


Unary Relational Operations
•SELECT (symbol: σ)
•PROJECT (symbol: π)
•RENAME (symbol: ρ)
Relational Algebra Operations From Set Theory
•UNION (υ)
•INTERSECTION (∩),
•DIFFERENCE (-)
•CARTESIAN PRODUCT ( x )
Binary Relational Operations
•JOIN
•DIVISION
LOAN Relation
SELECT (σ)
 The SELECT operation is used for selecting a subset of the BRANCH_NA LOAN_NO AMOUNT
tuples according to a given selection condition. ME
 Sigma(σ)Symbol denotes it.
 It is used as an expression to choose tuples which meet the Downtown L-17 1000
selection condition. Redwood L-23 2000
 Select operator selects tuples that satisfy a given condition.
Perryride L-15 1500
σp(r) Downtown L-14 1500
Where: Mianus L-13 500

σ is used for selection prediction Roundhill L-11 900


r is used for relation Perryride L-16 1300
p is used as a propositional logic formula which may use
Input:
connectors like: AND OR and NOT. These relational can use as
1.σ BRANCH_NAME="perryride" (LOAN)
relational operators like =, ≠, ≥, <, >, ≤.
σ topic = “Rollno" (student)
BRANCH_NAME LOAN_NO AMOUNT
σ topic = “admissionno" and author = “dept"( Student)
Perryride L-15 1500
σ sales > 50000 (Customers) Perryride L-16 1300
Projection(π) CUSTOMER RELATION
 The projection eliminates all attributes of the input relation but
those mentioned in the projection list. NAME STREET CITY
 The projection method defines a relation that contains a vertical Jones Main Harrison
subset of Relation.
Smith North Rye
 This helps to extract the values of specified attributes to
eliminates duplicate values. Hays Main Harrison
 (pi) symbol is used to choose attributes from a relation. Curry North Rye
 This operator helps you to keep specific columns from a relation Johnson Alma Brooklyn
and discards the other columns.
Brooks Senator Brooklyn

Π CustomerName, Status (Customers) 1.∏ NAME, CITY (CUSTOMER)


NAME CITY
Jones Harrison
Smith Rye
Hays Harrison
Curry Rye
Johnson Brooklyn
Brooks Brooklyn
Rename (ρ)
Rename is a unary operation used for renaming attributes of a
relation.
ρ (a/b)R will rename the attribute ‘b’ of relation by ‘a’.

Rename Operation:
The rename operation is used to rename the output relation. It is
denoted by rho (ρ).
Example: We can use the rename operator to rename
STUDENT relation to STUDENT1.

ρ(STUDENT1, STUDENT)
Union Operation:
• Suppose there are two tuples R and A union operation must hold the following
S. The union operation contains all condition:
• R and S must have the attribute of the same
the tuples that are either in R or S or
both in R & S. number.
• It eliminates the duplicate tuples. It • Duplicate tuples are eliminated automatically.
is denoted by ∪. ∏ CUSTOMER_NAME (BORROW) ∪ ∏ CUSTOMER_NAME (DEPO
1.Notation: R ∪ S SITOR) CUSTOMER_NAME

DEPOSITOR RELATION BORROW RELATION Johnson

CUSTOMER_NAME ACCOUNT_NO CUSTOMER_NAME LOAN_NO Smith

Jones L-17 Hayes


Johnson A-101 Turner
Smith L-23
Smith A-121 Hayes L-15 Jones
Mayes A-321 Jackson L-14 Lindsay
Turner A-176 Curry L-93 Jackson
Johnson A-273 Smith L-11 Curry
Jones A-472 Williams L-17 Williams

Lindsay A-284 Mayes


Set Intersection:
•Suppose there are two tuples R and S. The set intersection
operation contains all tuples that are in both R & S.
•It is denoted by intersection ∩.
1.Notation: R ∩ S
1.∏ CUSTOMER_NAME (BORROW) ∩ ∏ CUSTOMER_NAME (DEPOSITOR)
CUSTOMER_NAME
Smith
Jones
Set Difference:
•Suppose there are two tuples R and S. The set intersection
operation contains all tuples that are in R but not in S.
•It is denoted by intersection minus (-).
1.Notation: R - S
1.∏ CUSTOMER_NAME (BORROW) - ∏ CUSTOMER_NAME (DEPOSITOR)

CUSTOMER_NAME
Jackson
Hayes
Willians
Curry
Cartesian product
• The Cartesian product is used to combine
each row in one table with each row in the
other table. It is also known as a cross
product. EMPLOYEE
• It is denoted by X. EMP_ID EMP_NAME EMP_DEPT
Notation: E X D
1 Smith A
1.EMPLOYEE X DEPARTMENT
2 Harry C
3 John B

DEPARTMENT

DEPT_NO DEPT_NAME
A Marketing
B Sales
C Legal
EMP_ID EMP_NAME EMP_DEPT DEPT_NO DEPT_NAME
1 Smith A A Marketing
2 Harry C B Sales
3 John B C Legal

EMP_ID EMP_NA EMP_DEP DEPT_NO DEPT_NA


ME T ME
1 Smith A A Marketing
1 Smith A B Sales
1 Smith A C Legal
2 Harry C A Marketing
2 Harry C B Sales
2 Harry C C Legal
3 John B A Marketing
3 John B B Sales
3 John B C Legal
STUDENT ✕ DETAILS
SNO FNAME LNAME

1 Albert Singh
SNO FNAME LNAME ROLLNO AGE
2 Nora Fatehi 1 Albert Singh 5 18
1 Albert Singh 9 21
2 Nora Fatehi 5 18
ROLLNO AGE 2 Nora Fatehi 9 21
5 18
9 21
Join Operations:
1.Operation: (EMPLOYEE ⋈ SALARY)
A Join operation combines related tuples from different
relations, if and only if a given join condition is satisfied. It is
denoted by ⋈. EMP_CODE EMP_NAME SALARY
EMPLOYEE 101 Stephan 50000
102 Jack 30000
EMP_CODE EMP_NAME
103 Harry 25000
101 Stephan
102 Jack
103 Harry

SALARY

EMP_CODE SALARY
101 50000
102 30000
103 25000
Natural Join:

A natural join is the set of tuples of all combinations in R and S


that are equal on their common attribute names.
It is denoted by ⋈.
Example: Let's use the above EMPLOYEE table and SALARY
table:

1.∏EMP_NAME, SALARY (EMPLOYEE ⋈ SALARY)

EMP_NAME SALARY
Stephan 50000
Jack 30000
Harry 25000
Inner Join:
The outer join operation is an extension of the join operation. It
is used to deal with common information.

EMPLOYEE FACT_WORKERS
EMP_NAME STREET CITY EMP_NAME BRANCH SALARY

Ram Civil line Mumbai Ram Infosys 10000


Shyam Park street Kolkata Shyam Wipro 20000
Ravi M.G. Street Delhi Kuber HCL 30000
Hari Nehru nagar Hyderabad Hari TCS 50000

1.(EMPLOYEE ⋈ FACT_WORKERS)

EMP_NAME STREET CITY BRANCH SALARY

Ram Civil line Mumbai Infosys 10000


Shyam Park street Kolkata Wipro 20000
Hari Nehru nagar Hyderabad TCS 50000
An outer join is basically of three types: Left outer join contains the set of tuples of all combinations in R and S that
are equal on their common attribute names.
Left outer join In the left outer join, tuples in R have no matching tuples in S.
Right outer join It is denoted by ⟕.
Full outer join Example: Using the above EMPLOYEE table and FACT_WORKERS table

EMPLOYEE ⟕ FACT_WORKERS
EMP_NAME STREET CITY EMP_NAME BRANCH SALARY

Ram Civil line Mumbai Ram Infosys 10000


Shyam Park street Kolkata Shyam Wipro 20000
Ravi M.G. Street Delhi Kuber HCL 30000
Hari Nehru nagar Hyderabad Hari TCS 50000

EMP_NAME STREET CITY BRANCH SALARY


Ram Civil line Mumbai Infosys 10000
Shyam Park street Kolkata Wipro 20000
Hari Nehru street Hyderabad TCS 50000
Ravi M.G. Street Delhi NULL NULL
Right outer join:
•Right outer join contains the set of tuples of all combinations in R and S that are equal on their common
attribute names.
•In right outer join, tuples in S have no matching tuples in R.
•It is denoted by ⟖.
Example: Using the above EMPLOYEE table and FACT_WORKERS Relation

EMPLOYEE ⟖ FACT_WORKERS

EMP_NAME STREET CITY EMP_NAME BRANCH SALARY


Ram Civil line Mumbai Ram Infosys 10000
Shyam Park street Kolkata Shyam Wipro 20000
Ravi M.G. Street Delhi
Kuber HCL 30000
Hari Nehru nagar Hyderabad
Hari TCS 50000

EMP_NAME BRANCH SALARY STREET CITY


Ram Infosys 10000 Civil line Mumbai
Shyam Wipro 20000 Park street Kolkata
Hari TCS 50000 Nehru street Hyderabad
Kuber HCL 30000 NULL NULL
Full outer join:
•Full outer join is like a left or right join except that it contains all rows from both tables.
•In full outer join, tuples in R that have no matching tuples in S and tuples in S that have no matching tuples in R in
their common attribute name.
•It is denoted by ⟗.
Example: Using the above EMPLOYEE table and FACT_WORKERS table

EMPLOYEE ⟗ FACT_WORKERS

EMP_NAME STREET CITY BRANCH SALARY


Ram Civil line Mumbai Infosys 10000
Shyam Park street Kolkata Wipro 20000
Hari Nehru street Hyderabad TCS 50000
Ravi M.G. Street Delhi NULL NULL
Kuber NULL NULL HCL 30000
Equi join

It is also known as an inner join. It is the most common join.


It is based on matched data as per the equality condition.
The equi join uses the comparison operator(=).

CUSTOMER RELATION PRODUCT


CLASS_ID NAME PRODUCT_ID CITY
1 John 1 Delhi
2 Harry 2 Mumbai
3 Jackson 3 Noida
1.CUSTOMER ⋈ PRODUCT

CLASS_ID NAME PRODUCT_ID CITY


1 John 1 Delhi
2 Harry 2 Mumbai
3 Jackson 3 Noida
1. {s.sname|supplier(s)}
2. {p.name|parts(p) Ʌ p.colour = ‘red’}
3. {s.sid|supplier(s) Ʌs.name = ‘varun’ Ʌ s.add = ‘chandigrh’}
4. {c.sid|catalog(c)}
5. {s.sname|supplier(s) Ʌ Ǝ c(catalog(c)) Ʌ s.sid = c.sid}
6. { s.name|supplier(s) Ʌ Ǝ c(catalog(c)) Ʌ Ǝ p(parts(p)) Ʌ s.sid = c.sid
Ʌ p.pid = c.pid
Ʌ p.colour = ‘red’}
Universal Quantifiers: The universal quantifier denoted by ∀ is read as for all which means that in a given set of tuples exactly
all tuples satisfy a given condition.
Existential Quantifiers: The existential quantifier denoted by ∃ is read as for all which means that in a given set of tuples there
is at least one occurrences whose value satisfy a given condition.

Domain Relational Calculus (DRC)


• The second form of relation is known as Domain relational calculus.
• In domain relational calculus, filtering variable uses the domain of attributes.
• Domain relational calculus uses the same operators as tuple calculus.
• It uses logical connectives ∧ (and), ∨ (or) and ┓ (not).
• It uses Existential (∃) and Universal Quantifiers (∀) to bind the variable.
• The QBE or Query by example is a query language related to domain relational calculus.
Notation:
{ a1, a2, a3, ..., an | P (a1, a2, a3, ... ,an)} a1, a2 are attributes
P stands for formula built by inner attributes
{< article, page, subject > | ∈ javatpoint ∧ subject = 'database'}
Query Format
{ …….)}

Condition over Domain variables


Example Domain variables
a b c d e f g h
Employee(firstname,lastname, Eid,DoB,ADD, Sex, Salary, Dno)
x y z
Department(Dno, Dname,Mid)
Query: List of name and address of the employee whose name is Foo bar
a to h , x,y,z  Domain variable a b
Optional
{ abe|Ǝ c Ǝ d Ǝ f Ǝ h(employee(abcdefgh) Ʌ (a = ‘Foo’) Ʌ (b = ‘bar’)}
Or
{abe|(employee(abcdefgh) Ʌ (a = ‘Foo’) Ʌ (b = ‘bar’)}
Or
{abe|(employee(‘Foo’,’bar’,b,c,d,e,f,g,h)}
Example
a b c d e f g h
Employee(firstname,lastname, Eid,DoB,ADD, Sex, Salary, Dno)
x y z
Department(Dno, Dname,Mid)

List the name of the employee who have no dept to manage

so while we have to find out the 1stname and lastname of employee whose Eid =! Mid
c =! z

{ ab|Ǝ c (employee(abcdefgh) Ʌ ¬Ǝ z (dept(xyz) Ʌ z=c))}


TRANSACTION CONTROL LANGUAGE
• Transactions group a set of tasks into a single execution unit.
• Each transaction begins with a specific job and ends when all the
tasks in the group successfully completed.
• If any of the tasks fail, the transaction fails. Therefore, a transaction
has only two results: success or failure.

• COMMIT
• SAVEPOINT
• ROLLBACK
COMMIT Command
• If everything is in order with all statements within a single transaction, all changes are
recorded together in the database is called committed.
• The COMMIT command saves all the transactions to the database since the last
COMMIT or ROLLBACK command.
Syntax:
COMMIT;
Example:
Sample Table1

DELETE FROM Student WHERE AGE = 20;


COMMIT;
ROLLBACK Command
• If any error occurs with any of the SQL grouped statements, all changes need to be
aborted. The process of reversing changes is called rollback.

• This command can only be used to undo transactions since the last COMMIT or
ROLLBACK command was issued.
Syntax for ROLLBACK command:
ROLLBACK;

DELETE FROM Student WHERE AGE = 20;


ROLLBACK;
SAVEPOINT Command
• SAVEPOINT creates points within the groups of transactions in which to ROLLBACK.
• A SAVEPOINT is a point in a transaction in which you can roll the transaction back to a
certain point without rolling back the entire transaction.
Syntax for Savepoint command:
you can ROLLBACK to any SAVEPOINT at any
SAVEPOINT SAVEPOINT_NAME; time to return the appropriate data to its original
This command is used only in the creation of SAVEPOINT state.
among all the transactions. Example:
In general ROLLBACK is used to undo a group of From the above example Sample table1, Delete
transactions. those records from the table which have age = 20
Syntax for rolling back to Savepoint Command: and then ROLLBACK the changes in the database
by keeping Savepoints.
ROLLBACK TO SAVEPOINT_NAME;
RELEASE SAVEPOINT Command
SAVEPOINT SP1; ROLLBACK TO SP1; This command is used to remove a
//Savepoint created. //Rollback completed SAVEPOINT that you have created.
DELETE FROM Student WHERE AGE = 20;
//deleted Syntax:
SAVEPOINT SP2;
//Savepoint created. RELEASE SAVEPOINT SAVEPOINT_NAME
PROCEDURAL SQL
Sql – WHAT TO DO
PL/SQL WRITE A PROGRAM /PLSQL CODE BUT NOT HOW TO DO
WRITE A QUERY

FUNCTION PROCEDURE TRIGGER CURSOR

Declaration DECLARE
declare A INT;
Block code a int B INT;
b int C INT;
c int BEGIN
A:= &A;
Executable code B:= &B;
Begin
C:= A+B;
End dbms_output.put_line('sum of a and b'||c);
end;

Exception Handling

Ant type of error ONLINE ORACLE &A AND &B wont work
DECLARE
A INT;
B INT;
C INT;
BEGIN
A:= 10;
B:= 20;
if(A>B)
THEN
dbms_output.put_line('A IS GREATER'||A);
ELSE
dbms_output.put_line('B IS GREATER'||B);
END IF;
end;
Trigger
A Trigger in Structured Query Language is a set of procedural statements which are executed
automatically when there is any response to certain events on the particular table in the database.
Triggers are used to protect the data integrity in the database.

In SQL, this concept is the same as the trigger in real life. For example, when we pull the gun
trigger, the bullet is fired.

Suppose Rishabh is the human resource manager in a multinational company. When the record of a new employee
is entered into the database, he has to send the 'Congrats' message to each new employee. If there are four or five
employees, Rishabh can do it manually, but if the number of new Employees is more than the thousand, then in
such condition, he has to use the trigger in the database.

Thus, now Rishabh has to create the trigger in the table, which will automatically send a 'Congrats' message to the
new employees once their record is inserted into the database.

The trigger is always executed with the specific table in the database. If we remove the table, all the triggers
associated with that table are also deleted automatically.
In Structured Query Language, triggers are called only either before or after the
below events:
1.INSERT Event: This event is called when the new row is entered in the table.
2.UPDATE Event: This event is called when the existing record is changed or modified
in the table.
3.DELETE Event: This event is called when the existing record is removed from the
table.
Types of Triggers in SQL
Following are the six types of triggers in SQL:
1.AFTER INSERT Trigger
This trigger is invoked after the insertion of data in the table.
2.AFTER UPDATE Trigger
This trigger is invoked in SQL after the modification of the data in
the table.
3.AFTER DELETE Trigger
This trigger is invoked after deleting the data from the table.
4.BEFORE INSERT Trigger
This trigger is invoked before the inserting the record in the table.
5.BEFORE UPDATE Trigger
This trigger is invoked before the updating the record in the table.
6.BEFORE DELETE Trigger
This trigger is invoked before deleting the record from the table.
• In the trigger syntax, firstly, we have
Syntax of Trigger in SQL
CREATE TRIGGER Trigger_Name to define the name of the trigger
[ BEFORE | AFTER ] [ Insert | Update | Delete] after the CREATE TRIGGER
ON [Table_Name] keyword.
• After that, we have to define the
[ FOR EACH ROW | FOR EACH COLUMN ]
AS BEFORE or AFTER keyword with
Set of SQL Statement anyone event.
• Then, we define the name of that
table on which trigger is to occur.
• After the table name, we have to
define the row-level or statement-
level trigger.
• And, at last, we have to write the
SQL statements which perform
actions on the occurring of event.
Example of Trigger in SQL CREATE TABLE Student_Trigger
To understand the concept of trigger in SQL, first, we have to (
create the table on which trigger is to be executed. Student_RollNo INT NOT NULL PRIMARY KEY,
The following query creates the Student_Trigger table in the Student_FirstName Varchar (100),
SQL database: Student_EnglishMarks INT,
Student_PhysicsMarks INT,
Student_ChemistryMarks INT,
Student_MathsMarks INT,
Student_TotalMarks INT,
Student_Percentage ); DESC Student_Trigger;

Field Type NULL Key Default Extra


Student_RollNo INT NO PRI NULL

Student_FirstNa Varchar(100) YES NULL


me
Student_Englis INT YES NULL
hMarks

Student_Physic INT YES NULL


sMarks

Student_Chemi INT YES NULL


stryMarks

Student_Maths INT YES NULL


Marks

Student_TotalM INT YES NULL


arks

Student_Percent INT YES NULL


age
The following query fires a trigger before the insertion of the
student record in the table:
CREATE TRIGGER Student_Table_Marks
BEFORE INSERT
ON
Student_Trigger
FOR EACH ROW
SET new.Student_TotalMarks = new.Student_EnglishMarks + new.Student_PhysicsMarks + new.Student_ChemistryMark
s + new.Student_MathsMarks, new.Student_Percentage = ( new.Student_TotalMarks / 400) * 100;

The following query inserts the record into Student_Trigger


table:
INSERT INTO Student_Trigger (Student_RollNo, Student_FirstName, Student_EnglishMarks, Student_PhysicsMarks, Stud
ent_ChemistryMarks, Student_MathsMarks, Student_TotalMarks, Student_Percentage) VALUES ( 201, Sorya, 88, 75, 69, 92
, 0, 0);
SELECT * FROM Student_Trigger;

Student_Rol Student_Firs Student_Eng Student_Phy Student_che Student_Mat Student_Tot Student_Per


lNo tName lishMarks sicsMarks mistryMarks hsMarks alMarks centage

201 Sorya 88 75 69 92 324 81


Advantages of Triggers in SQL
Following are the three main advantages of triggers in
Structured Query Language:
1. SQL provides an alternate way for maintaining the data and
referential integrity in the tables.
2. Triggers helps in executing the scheduled tasks because they
are called automatically.
3. They catch the errors in the database layer of various
businesses.
4. They allow the database users to validate values before
inserting and updating.

Following are the main disadvantages of triggers in Structured


Query Language:
1. They are not compiled.
2. It is not possible to find and debug the errors in triggers.
3. If we use the complex code in the trigger, it makes the
application run slower.
4. Trigger increases the high load on the database system.
PL/SQL Trigger Example •CREATE [OR REPLACE] TRIGGER trigger_name: It creates
or replaces an existing trigger with the trigger_name.
•{BEFORE | AFTER | INSTEAD OF} : This specifies when the
CREATE [OR REPLACE ] TRIGGER trigger_name trigger would be executed. The INSTEAD OF clause is used for
{BEFORE | AFTER | INSTEAD OF } creating trigger on a view.
{INSERT [OR] | UPDATE [OR] | DELETE} •{INSERT [OR] | UPDATE [OR] | DELETE}: This specifies
[OF col_name] the DML operation.
ON table_name •[OF col_name]: This specifies the column name that would be
[REFERENCING OLD AS o NEW AS n] updated.
[FOR EACH ROW] •[ON table_name]: This specifies the name of the table
WHEN (condition) associated with the trigger.
DECLARE •[REFERENCING OLD AS o NEW AS n]: This allows you to
Declaration-statements refer new and old values for various DML statements, like
BEGIN INSERT, UPDATE, and DELETE.
Executable-statements •[FOR EACH ROW]: This specifies a row level trigger, i.e., the
EXCEPTION trigger would be executed for each row being affected.
Exception-handling-statements Otherwise the trigger will execute just once when the SQL
END; 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.
ID NAME AGE ADDRESS SALARY Let's take a program to create a row level trigger for the
CUSTOMERS table that would fire for INSERT or
1 Ramesh 23 Allahabad 20000
UPDATE or DELETE operations performed on the
2 Suresh 22 Kanpur 22000 CUSTOMERS table. This trigger will display the salary
3 Mahesh 24 Ghaziabad 24000 difference between the old values and new values:
4 Chandan 25 Noida 26000
5 Alex 21 Paris 28000 CREATE OR REPLACE TRIGGER display_salary_c
6 Sunita 20 Delhi 30000 hanges
BEFORE DELETE OR INSERT OR UPDATE ON cu
stomers
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;
/ the execution of the above code at SQL Prompt, it produces the following result.
After
Trigger created.
Check the salary difference by procedure:
Use the following code to get the old salary, new salary and salary
difference after the trigger created.
Output:
DECLARE
Old salary: 20000 Old salary: 25000
total_rows number(2);
New salary: 25000 New salary: 30000
BEGIN
Salary difference: 5000 Salary difference: 5000
UPDATE customers
Old salary: 22000 Old salary: 27000
SET salary = salary + 5000;
New salary: 27000 New salary: 32000
IF sql%notfound THEN
Salary difference: 5000 Salary difference: 5000
dbms_output.put_line('no customers updated');
Old salary: 24000 Old salary: 29000
ELSIF sql%found THEN
New salary: 29000 New salary: 34000
total_rows := sql%rowcount;
Salary difference: 5000 Salary difference: 5000
dbms_output.put_line( total_rows || ' customers updated ');
Old salary: 26000 Old salary: 31000
END IF;
New salary: 31000 New salary: 36000
END;
Salary difference: 5000 Salary difference: 5000
/
Old salary: 28000 Old salary: 33000
New salary: 33000 New salary: 38000
Salary difference: 5000 Salary difference: 5000
Old salary: 30000 Old salary: 35000
New salary: 35000 New salary: 40000
Salary difference: 5000 Salary difference: 5000
6 customers updated 6 customers updated
PL/SQL Cursor
• When an SQL statement is processed, Oracle creates a memory area known as context area. A cursor is a pointer
to this context area.
• It contains all information needed for processing the statement.
• In PL/SQL, the context area is controlled by Cursor. A cursor contains information on a select statement and the
rows of data accessed by it.
• A cursor is used to referred to 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

PL/SQL Implicit Cursors


The implicit cursors are automatically generated by Oracle while an SQL
statement is executed, if you don't use an explicit cursor for the
statement.
These are created by default to process the statements when DML
statements like INSERT, UPDATE, DELETE etc. are executed.
For Example :
• When you execute the SQL statements like INSERT, UPDATE, DELETE then the cursor attributes
tell whether any rows are affected and how many have been affected.
• If you run a SELECT INTO statement in PL/SQL block, the implicit cursor attribute can be used to
find out whether any row has been returned by the SELECT statement.
• It will return an error if there no data is selected.
Attribute Description
%FOUND Its return value is TRUE if DML statements like INSERT, DELETE and
UPDATE affect at least one row or more rows or a SELECT INTO statement
returned one or more rows. Otherwise it returns FALSE.

%NOTFOUND Its return value is TRUE if DML statements like INSERT, DELETE and
UPDATE affect no row, or a SELECT INTO statement return no rows.
Otherwise it returns FALSE. It is a just opposite of %FOUND.
%ISOPEN It always returns FALSE for implicit cursors, because the SQL cursor is
automatically closed after executing its associated SQL statements.

%ROWCOUNT It returns the number of rows affected by DML statements like INSERT,
DELETE, and UPDATE or returned by a SELECT INTO statement.
PL/SQL Implicit Cursor Example
Create customers table and have records:
ID NAME AGE ADDRESS SALARY DECLARE
total_rows number(2);
1 Ramesh 23 Allahabad 20000 BEGIN
2 Suresh 22 Kanpur 22000 UPDATE customers SET salary = salary + 5000;
IF sql%notfound THEN
3 Mahesh 24 Ghaziabad 24000
dbms_output.put_line('no customers updated');
4 Chandan 25 Noida 26000 ELSIF sql%found THEN
total_rows := sql%rowcount;
5 Alex 21 Paris 28000
dbms_output.put_line( total_rows || ' customers updat
6 Sunita 20 Delhi 30000 ed ');
END IF;
Let's execute the following program to update the table and
END;
increase salary of each customer by 5000. Here, SQL
/
%ROWCOUNT attribute is used to determine the number of
rows affected:

Output:
6 customers updated PL/SQL procedure
successfully completed.
select * from customers;

ID NAME AGE ADDRESS SALARY


1 Ramesh 23 Allahabad 25000
2 Suresh 22 Kanpur 27000
3 Mahesh 24 Ghaziabad 29000
4 Chandan 25 Noida 31000
5 Alex 21 Paris 33000
6 Sunita 20 Delhi 35000
PL/SQL Explicit Cursors
The Explicit cursors are defined by the programmers to gain more control over the context
area.
These cursors 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.
Following is the syntax to create an explicit cursor:
Syntax of explicit cursor
Following is the syntax to create an explicit cursor:
CURSOR cursor_name IS select_statement;;

Steps:
You must follow these steps while working with an explicit cursor.
1.Declare the cursor to initialize in the memory.
2.Open the cursor to allocate memory.
3.Fetch the cursor to retrieve data.
4.Close the cursor to release allocated memory.
Declare the cursor:
It defines the cursor with a name and the associated SELECT
statement.
Syntax for explicit cursor decleration
CURSOR name IS
SELECT statement;
Open the cursor:
It is used to allocate memory for the cursor and make it easy to
fetch the rows returned by the SQL statements into it.
Syntax for cursor open:
OPEN cursor_name;
Fetch the cursor:
It is used to access one row at a time. You can fetch rows from
the above-opened cursor as follows:
FETCH cursor_name INTO variable_list;
Close the cursor:
It is used to release the allocated memory. The following syntax
is used to close the above-opened cursors.

Close cursor_name;
Create customers table and have records:
Execute the following program to retrieve the customer name
and address.
ID NAME AGE ADDRESS SALARY
DECLARE
1 Ramesh 23 Allahabad 20000 c_id customers.id%type;
c_name customers.name%type;
2 Suresh 22 Kanpur 22000
c_addr customers.address%type;
3 Mahesh 24 Ghaziabad 24000 CURSOR c_customers is
4 Chandan 25 Noida 26000 SELECT id, name, address FROM customers;
BEGIN
5 Alex 21 Paris 28000 OPEN c_customers;
6 Sunita 20 Delhi 30000 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;
1 Ramesh Allahabad
/
2 Suresh Kanpur
3 Mahesh Ghaziabad
4 Chandan Noida
5 Alex Paris
6 Sunita Delhi
PL/SQL procedure successfully completed.
Functional dependency
The functional dependency is a relationship that exists between two attributes.
It typically exists between the primary key and non-key attribute within a table.
X → Y
The left side of FD is known as a determinant, the right side of the production is
known as a dependent.
For example:
Assume we have an employee table with attributes: Emp_Id, Emp_Name,
Emp_Address.

Here Emp_Id attribute can uniquely identify the Emp_Name attribute of employee
table because if we know the Emp_Id, we can tell that employee name associated
with it.
Functional dependency can be written as:
Emp_Id → Emp_Name
X determines Y • Functional dependency from X to Y
X → Y
Y is dependent on X • Here we are not calculating y for X like calculating Y
dependent • In DBMS you have given a table from X you would be
determinant determining the value of Y X Y
• Through X value determining Y value
• X -> ROLL NO , Y-> Name 1 2
If it is true then it is called as Functional dependency
2 1
3 1
4 3

• In a Relation R if you have given the value of X = 2 then


Rules search the value of Y
1. If two tuples of X having the same • IF X = 2 then Y=1
value should also have Same Y value. • If X = 2 & Y = 1
Y= 5 ---- WORNG means not dependent
2. All the determinant value should be This is the not the case & it is not X Y
Unique then it is functional dependent. Functional dependent 1 2

Roll no in CS is unique for a relation but when if CS and EC 2 1


sitting together then in this case it is not functional dependent 3 1
4 3
2 5
F.D  Functional dependency
X Y
1. Take T1 AND T2 FOR
SOLVING ABOVE T1. 1 1
2. IF THIS IS TRUE T2. 2 2
IF T1.X = T2.X THEN ONLY WE
3 3
THEN T1.Y = T2.Y CHECK NEXT T1 &
QUESTION IS XY FUNCTIONALLY DEPENDENT OR NOT T2 CAN BE TAKEN 4 5
ANY TUPLE FROM X 2 5
FD X Y
R NO Name Marks Dept Course IF T1.X = T2.X
1 A 70 Cs C1 THEN T1.Y = T2.Y
2 B 60 Ee C1
3 A 78 Cs C2
4 B 60 Ee C3
5 C 80 It C3
6 D 80 Ec C2
2. Non-trivial functional dependency
•A → B has a non-trivial functional dependency if B is not a
subset of A.
•When A intersection B is NULL, then A → B is called as
complete non-trivial.

1.ID → Name,
2.Name → DOB

1. Trivial functional dependency For Non trival FD only we can check valid / or not

•A → B has trivial functional dependency if B is a subset of A.


•The following dependencies are also trivial like: A → A, B →
B
Consider a table with two columns Employee_Id and Employee_Name.
{Employee_id, Employee_Name} → Employee_Id is a trivial functional dependency as
Employee_Id is a subset of {Employee_Id, Employee_Name}.
Also, Employee_Id → Employee_Id and Employee_Name → Employee_Name are trivial dependencies too.
Properties of Functional Dependecy

1. Reflexivity : if Y is subset of X then X--> Y


• Empid  Empid
2. Augmentation : if X Y then XZ YZ
• Empid  Empname then Empid,dept Empname,dept
3. Transitive Properties : if X Y and Y  Z then X  Z
• Empid  Empname and Empname  City then Empid  City
4. Union : if X  Y and X Z then X  YZ
5. Decomposition : if X YZ then X  Y and X Z
• But XY  Z then X  Z and Y Z
6. Psedutranstive Properties: if X  Y and WY Z then WX  Z
7. Composition : X  Y and Z W then XZ YW
Normalization in DBMS

Need of Normalization

• Reduce the redundancy


• Save the space by redundancy
• To reduce this Anomalies
• To minimize the Null values
• To minimize the Queries OLTP where insert/update/delete occurs frequently
• It is important for OLTP (ONLINE TRANSACTION PROCESSING) systems
• Simplifies the database structure

• Decomposition of any table is not so simple because having the big table we cant do it
• Problems occur like lossless information & lossy information

Normalization : It is a process of making the


table free from insert/delete and update
anomaly and reduce the space by
decomposing of table by removing redundant
data
Student
PK
Sid Sname Credits Dept Name Building Room no
1 Ravi 5 CSE B1 105
2 Rahil 6 CSE B1 105
3 Ali 7 EC B2 203
4 Mohamad 4 EC B2 203
5 Salman 5 IT B1 301
6 Karthik 8 CIVIL B1 302
N N N MECH B2 205

Insert Anomaly
Update Anomaly Problem occurs when Normalization occurs
Delete Anomaly
Student Dept
PK FK PK

Sid Sname Credits Dept Name Dept Name Building Room no


1 Ravi 5 CSE CSE B1 105
2 Rahil 6 CSE EC B2 203
3 Ali 7 EC IT B1 301
4 Mohamad 4 EC CIVIL B1 302
5 Salman 5 IT MECH B2 205
6 Karthik 8 CIVIL

You might also like