DBMS Module3
DBMS Module3
Module: 3
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 1
Module 2
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 2
Module 3
3
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 3
1.More Complex SQL Retrieval Queries
Subtopics to be covered under this topic
1. Comparisons Involving NULL and Three-Valued Logic
2. Nested Queries, Tuples, and Set/Multiset Comparisons
3. Correlated Nested Queries
4. The EXISTS and UNIQUE Functions in SQL
5. Explicit Sets and Renaming of Attributes in SQL
6. Joined Tables in SQL and Outer Joins
7. Aggregate Functions in SQL
8. Grouping: The GROUP BY and HAVING Clauses
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 4
More Complex SQL Retrieval Queries-Introduction
5
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 5
1.1Comparisons Involving NULL
and Three-Valued Logic
• SQL has various rules for dealing with NULL values.
• NULL is used to represent a missing value
• Meanings of NULL
– Unknown value
– Unavailable or withheld value
– Not applicable attribute
– Unknown value- (exists but is not known)
– Unavailable or withheld value
– (exists but is purposely withheld),
– Not applicable attribute(the attribute is undefined for this tuple).
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 6
Consider the following examples to illustrate each of the meanings of
NULL.
1. Unknown value. A person’s date of birth is not known, so it is
represented by NULL in the database.
2. Unavailable or withheld value. A person has a home phone but does
not want it to be listed, so it is withheld and represented as NULL in
the database.
3. Not applicable attribute. An attribute LastCollegeDegree would be
NULL for a person who has no college degrees because it does not
apply to that person.
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 7
NULL
• In general, each individual NULL value is considered to be different
from every other NULL value in the various database records.
• When a NULL is involved in a comparison operation, the result is
considered to be UNKNOWN (it may be TRUE or it may be FALSE).
• Hence, SQL uses a three-valued logic with values TRUE, FALSE, and
UNKNOWN instead of the standard two-valued (Boolean) logic with
values TRUE or FALSE.
• It is therefore necessary to define the results (or truth values) of three-
valued logical expressions when the logical connectives AND, OR, and
NOT are used.
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 8
Comparisons Involving NULL
and Three-Valued Logic (cont’d.)
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 9
Comparisons Involving NULL
and Three-Valued Logic (cont’d.)
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 10
1.2.Nested Queries, Tuples,
and Set/Multiset Comparisons
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 11
Nested query
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 12
IN OPERATOR
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 13
Populated Dataset
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 14
Retrieve those employees who work with same project and
number of hours combination as employee with usn -
123456789
• Select PNO ,HOURS FROM WORKS_ON WHERE
ESSN=‘ 123456789’
• {(1,32.5),(2,7.5)}
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 15
Query
• SELECT DISTINCT Essn FROM WORKS_ON WHERE (Pno, Hours) IN ( SELECT
Pno, Hours FROM WORKS_ON WHERE Essn=‘123456789’);
• This query will select the Essns of all employees who work the same (project,hours)
combination on some project that employee ‘John Smith’ (whose Ssn = ‘123456789’)
works on.
• In this example, the IN operator compares the subtuple of values in parentheses (Pno,
Hours) within each tuple in WORKS_ON with the set of type-compatible tuples
produced by the nested query.
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 16
Other Operators
• In addition to the IN operator ,a number of other comparison operators can be used to compare a
single value v (typically an attribute name) to a set or multiset v (typically a nested query).
• The = ANY (or = SOME) operator returns TRUE if the value v is equal to some value in the set V and
is hence equivalent to IN.
• The two keywords ANY and SOME have the same effect. Other operators that can be combined with
ANY (or SOME) include >, >=, <, <=, and <>.
• The keyword ALL can also be combined with each of these operators.
• For example,the comparison condition (v>ALL V) returns TRUE if the value v is greater than all the
values in the set (or multiset) V.
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 17
• Retrieve those employees who has salary greater than salary of all
employees working for department number 5
• SELECT SALARY FROM EMPLOYEE WHERE DNO=5
{30000,40000,38000,25000}
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 18
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 19
1.3 Correlated Nested Queries
• Correlated nested query
• Whenever a condition in the WHERE clause of a nested query references some
attribute of a relation declared in the outer query, the two queries are said to be
correlated.
• We can understand a correlated query better by considering that the nested query is
evaluated once for each tuple (or combination of tuples) in the outer query.
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 20
Question: Retrieve the name of each employee who has a dependent with
the same first name and is the same gender as the employee.
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 21
SELECT E.Fname, E.Lname
FROM EMPLOYEE AS E
WHERE E.Ssn IN ( SELECT D.Essn
FROM DEPENDENT AS D
WHERE E.Fname = D.Dependent_name
AND E.Sex = D.Sex );
For each EMPLOYEE tuple ,evaluate the nested query ,which retrieves the ESSN values for all
DEPENDENTS tuples with the same GENDER and name as that EMPLOYEE tuple ;if the ssn of
the employee tuple is in the result of the nested query ,then select that EMPLOYEE table.
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 22
Equivalent Query
SELECTE.Fname, E.Lname
FROMEMPLOYEE ASE, DEPENDENT ASD
WHERE E.Ssn=D.EssnAND E.Sex=D.Sex
AND E.Fname=D.Dependent_name;
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 23
1.4 The EXISTS and UNIQUE Functions in SQL
• EXISTS and UNIQUE are Boolean function that returns TRUE or FALSE.
• EXISTS function
• Check whether the result of a nested query is empty (Contains no tuple)or not
• The result of EXISTS is a boolean value TRUE if the nested query contains at least one
tuple or FALSE if the nested query contains no tuples.
• EXISTS and NOT EXISTS
• Typically used in conjunction with a correlated nested query
• SQL function UNIQUE(Q)
• Returns TRUE if there are no duplicate tuples in the result of query Q. Otherwise it returns
false
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 24
Retrieve name of managers who has atleast
one dependent
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 25
SELECT Fname, Lname
FROM EMPLOYEE
WHERE EXISTS ( SELECT * FROM DEPENDENT
WHERE Ssn = Essn )
AND
EXISTS ( SELECT *
FROM DEPARTMENT
WHERE Ssn = Mgr_ssn );
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 26
Retrieve the name of employees who have no dependents.
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 27
• Select Fname,Lname from Employee where NOT EXISTS (Select *
from DEPENEDENT where Ssn=Essn);
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 28
Retrieve the name of each employee who works on all
project controlled by department no 5.
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 29
Query
Select Fname,Lname
FROM EMPLOYEE
WHERE NOT EXISTS ((Select Pnumber
FROM PROJECT
WHERE Dnum=5)
EXCEPT (select Pno
FROM Works_on
WHERE Ssn=Essn));
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 30
Aggregate Functions in SQL
• Used to summarize information from multiple tuples into a single-tuple summary
• Grouping
– Create subgroups of tuples before summarizing
• Built-in aggregate functions
– COUNT, SUM, MAX, MIN, and AVG
• Functions can be used in the SELECT clause or in a HAVING clause
• NULL values discarded when aggregate functions are applied to a particular column
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 31
AGGREGATE FUNCTIONS in SQL
Include COUNT, SUM, MAX, MIN, and AVG
• Query 1: Find the maximum salary, the minimum salary, and the average salary among all
employees.
Q1: SELECT MAX(SALARY),
MIN(SALARY), AVG(SALARY)
FROM EMPLOYEE
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 32
AGGREGATE FUNCTIONS (contd.)
• Query 2: Find the maximum salary, the minimum salary, and the average salary
among employees who work for the 'Research' department.
Q2: SELECT MAX(SALARY),
MIN(SALARY), AVG(SALARY)
FROM EMPLOYEE, DEPARTMENT
WHERE DNO=DNUMBER AND
DNAME='Research'
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 33
• Query 3: Retrieve the total number of employees in the company
• Q3: SELECT COUNT (*)
FROM EMPLOYEE
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 34
GROUPING
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 35
Sample Dataset
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 36
• For each department, retrieve the department number, the number of
employees in the department, and their average salary.
• Select dno, count(*) ,avg(salary) from employee
group by DNO;
For each department, retrieve the department number , department
name, the number of employees in the department, and their average
salary.
• Select dno,dname,count(*),avg(salary) from employee,department
where dno=dnumber
group by dno, dname;
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 37
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 38
GROUPING (contd.)
• Query 5: For each department, retrieve the department number, the number of
employees in the department, and their average salary.
Q5: SELECT DNO, COUNT (*), AVG (SALARY)
FROM EMPLOYEE
GROUP BY DNO
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 39
Illustrating aggregate functions and grouping
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 40
Sample Dataset
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 41
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 42
• Query 6 For each project, retrieve the project number, project name,
and the number of employees who work on that project.
Select Pnumber,Pname, count(*)
from PROJECT, WORKS_ON
WHERE PNUMBER=PNO
GROUP BY PNUMBER,PNAME;
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 43
• Query 6 For each project, retrieve the project number, project name, and the
number of employees who work on that project.
• SELECT PNUMBER, PNAME, COUNT (*)
FROM PROJECT, WORKS_ON
WHERE PNUMBER=PNO
GROUP BY PNUMBER,PNAME
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 44
THE HAVING-CLAUSE
• Sometimes we want to retrieve the values of these functions for only those groups
that satisfy certain conditions
• The HAVING-clause is used for specifying a selection condition on groups (rather
than on individual tuples)
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 45
• Query 7: For each project on which more than two employees work,
retrieve the project number, project name, and the number of
employees who work on that project.
Select Pnumber,Pname, count(*)
from PROJECT, WORKS_ON
WHERE PNUMBER=PNO
GROUP BY PNUMBER,PNAME
HAVING COUNT(*) >2;
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 46
THE HAVING-CLAUSE (contd.)
• Query 7: For each project on which more than two employees work, retrieve the
project number, project name, and the number of employees who work on that
project.
Q7: SELECT PNUMBER, PNAME, COUNT(*)
FROM PROJECT, WORKS_ON
WHERE PNUMBER=PNO
GROUP BY PNUMBER,PNAME
HAVING COUNT (*) > 2
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 47
Query
• For each department that has more than five employees, retrieve the department
number and the number of its employees who are making more than $40,000.
• SELECT S.DNO,COUNT(*) FROM EMPLOYEE S WHERE S.SALARY>40000
AND S.DNO IN
(SELECT E.DNO FROM EMPLOYEE E GROUP BY DNO HAVING
COUNT(*)>5)
GROUP BY S.DNO;
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 48
Query
For each department that has more than five employees, retrieve the department
number and the number of its employees who are making more than $40,000.
SELECT Dno, COUNT (*)
FROM EMPLOYEE
WHERE Salary>40000 AND Dno IN
( SELECT Dno FROM EMPLOYEE
GROUP BY Dno
HAVING COUNT (*) > 5)
GROUP BY Dno;
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 49
SUBSTRING COMPARISON
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 50
ARITHMETIC OPERATIONS
• The standard arithmetic operators '+', '-'. '*', and '/' (for addition, subtraction,
multiplication, and division, respectively) can be applied to numeric values in an
SQL query result
• Query 9: Show the effect of giving all employees who work on the 'ProductX'
project a 10% raise.
Q9: SELECT FNAME, LNAME, 1.1*SALARY
FROM EMPLOYEE, WORKS_ON, PROJECT
WHERE SSN=ESSN AND PNO=PNUMBER
AND PNAME='ProductX’
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 51
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 52
ORDER BY
• The ORDER BY clause is used to sort the tuples in a query result based on the
values of some attribute(s)
• Query 10: Retrieve a list of employees, department they work for ordered by the
employee's department, and within each department ordered alphabetically by
employee last name.
Q10: SELECT DNAME, LNAME, FNAME
FROM DEPARTMENT, EMPLOYEE
WHERE DNUMBER=DNO AND SSN=ESSN
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 53
Order By
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 54
Summary of SQL Queries
• A query in SQL can consist of up to six clauses, but only the first two, SELECT
and FROM, are mandatory. The clauses are specified in the following order:
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 55
Summary of SQL Queries (contd.)
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 56
Specifying Constraints as Assertions and Actions as
Triggers
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 57
Two new feature of SQL
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 58
CREATE ASSERTION
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 59
Sample Dataset
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 60
How to create an assertion?
General constraints: constraints that do not fit in the basic SQL categories
• Mechanism: CREATE ASSERTION
• components include: a constraint name, followed by CHECK, followed by a
condition
• For example, to specify the constraint that the salary of an employee must not be greater than the
salary of the manager of the department that the employee works for in SQL, we can write the
following assertion:
• Create Assertion Employee_Sal CHECK( Not Exist(
Select E.Fname , E.ssn from Employee E , Employee M, Department D
Where E.Dno=D.Dnumber and D.MGR_SSN = M. SSN and E.salary>M.salary))
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 61
Example
• For example, to specify the constraint that the salary of an employee must not be greater
than the salary of the manager of the department that the employee works for in SQL, we
can write the following assertion:
CREATE ASSERTION SALARY_CONSTRAINT CHECK (
NOT EXISTS ( SELECT *
FROM EMPLOYEE E, EMPLOYEE M, DEPARTMENT D WHERE E.Salary>M.Salary
AND E.Dno = D.Dnumber AND D.Mgr_ssn = M.Ssn ) )
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 62
Create Assertion
1. The constraint name SALARY_CONSTRAINT is followed by the keyword
CHECK, which is followed by a condition in parentheses that must hold true on
every database state for the assertion to be satisfied.
2. The constraint name can be used later to disable the constraint or to modify or
drop it. The DBMS is responsible for ensuring that the condition is not violated.
3. Any WHERE clause condition can be used, but many constraints can be
specified using the EXISTS and NOT EXISTS style of SQL conditions.
4. Whenever some tuples in the database cause the condition of an ASSERTION
statement to evaluate to FALSE, the constraint is violated.
5. The constraint is satisfied by a database state if no combination of tuples in that
database state violates the constraint
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 63
• The basic technique for writing such assertions is to specify a query
that selects any tuples that violate the desired condition.
• By including this query inside a NOT EXISTS clause, the assertion
will specify that the result of this query must be empty so that the
condition will always be TRUE.
• Thus,the assertion is violated if the result of the query is not empty.
• In the preceding example,the query selects all employees whose
salaries are greater than the salary of the manager of their department.
• If the result of the query is not empty,the assertion is violated.
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 64
Relational Algebra
a) R1 Employee Join Department
(dno=dnumber)
R2sigma(dname=‘design’)(R1)
Result Pie(fname,address)(R2)
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 66
CREATE TRIGGER statement
• CREATE TRIGGER, which can be used to specify automatic actions that the database
system will perform when certain events and conditions occur.
• This type of functionality is generally referred to as active databases.
• In many cases it is convenient to specify the type of action to be taken when certain
events occur and when certain conditions are satisfied.
• For example,it may be useful to specify a condition that, if violated, causes some user to
be informed of the violation.
• The CREATE TRIGGER statement is used to implement such actions in SQL.
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 67
Syntax for Creating Triggers
CREATE [OR REPLACE ] TRIGGER trigger_name Trigger
{BEFORE | AFTER | INSTEAD OF } Time
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name] Trigger Event
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements Trigger Statement
EXCEPTION
Exception-handling-statements
END;
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 68
Components of Trigger
• A typical trigger has three components:
• Event: When this event happens, the trigger is activated
• Condition (optional): If the condition is true, the trigger executes, otherwise skipped
• Action: The actions performed by the trigger
• The action is to be executed automatically if the condition is satisfied when event occurs.
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 69
Trigger
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 70
Trigger Components
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 71
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 72
Trigger: Condition
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 73
Trigger: Action
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 74
Example
• To create a trigger to check if an employee salary is greater than his immediate supervisor
CREATE TRIGGER SALARY_VIOLATION
BEFORE INSERT OR UPDATE OF Salary, Supervisor_ssn ON EMPLOYEE
FOR EACH ROW
WHEN (NEW.SALARY > (SELECT Salary FROM EMPLOYEE
WHERE Ssn = NEW. Supervisor_Ssn)) INFORM_SUPERVISOR
(NEW.Supervisor.Ssn, New.Ssn)
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 75
Example 2
• Create table student (id int primary key,name varchar(20),m1 int,m2 int,tot int,avgg float,remark
varchar(10));
• Trigger before insert
id name m1 m2 tot avgg remark
create trigger tr6
100 Himanshu 50 70 120 60 first
before insert on student
for each row
Begin insert into student values(100, ‘Himanshu’,50,70);
:new.tot:=:new.m1+:new.m2;
:new.avgg:=:new.tot/2;
IF :new.avgg<33 then
:new.remark:='fail';
ELSIF :new.avgg>=33 and :new.avgg<45 then
:new.remark:='third';
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 76
ELSIF :new.avgg>=45 and :new.avgg<60 then
:new.remark:='second';
ELSE
:new.remark:='first';
END IF;
end;
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 77
Trigger (before insert )
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 78
Advantages
• Trigger is invoked by Oracle engine automatically whenever a specified event occurs.
• Trigger is stored into database and invoked repeatedly, when specific condition match.
• Triggers are stored programs, which are automatically executed or fired when some event
occurs.
ADVANTAGES
Trigger generates some derived column values automatically
Enforces referential integrity
Event logging and storing information on table access
Auditing
Synchronous replication of tables
Imposing security authorizations
Preventing invalid transaction
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 79
Views
A view is a single table that is derived from one or more base tables or
other views
➢ Views neither exist physically nor contain data itself, it depends on
the base tables for its existence
➢ 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.
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 80
How to Create a View?
• The command to specify view is CREATE VIEW.
• The view is given a virtual table name or view name, a list of
attribute names, and a query to specify the contents of the view.
CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 81
Example
CREATE VIEW WORKS_ON1
AS SELECT Fname, Lname, Pname, Hours
FROM EMPLOYEE, PROJECT, WORKS_ON
WHERE Ssn=Essn AND Pno=Pnumber ;
• ➢ We can specify SQL queries on view
DESC WORKS_ON1;
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 82
Example 2
CREATE VIEW DEPT_INFO(Dept_name,no_of_emps,total_sal)AS
SELECT Dname,COUNT(*) ,SUM(Salary)
FROM DEPARTMENT,EMPLOYEE
WHERE Dnumber=Dno
GROUP BY Dname;
View created
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 83
Query on View
Retrieve the Last name and First name of all employees who work on ‘ProductX’
Use works_on1 view
CREATE VIEW WORKS_ON1
AS SELECT Fname, Lname, Pname, Hours
FROM EMPLOYEE, PROJECT, WORKS_ON
WHERE Ssn=Essn AND Pno=Pnumber ;
Q))Select fname,lname from works_on1 where pname=‘product X’;
Q))SELECT Fname, Lname, Pname, Hours
FROM EMPLOYEE, PROJECT, WORKS_ON
WHERE Ssn=Essn AND Pno=Pnumber and Pname=‘ProductX’ ;
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 84
Advantages
To simply the specification of certain queries.
A view always shows up-to-date
If we modify the tuples in the base tables on which the view is defined, the view must
automatically reflect these changes
If we do not need a view any more, we can use the DROP VIEW command
• DROP VIEW WORKS_ON1;
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 85
View Implementation and View Update
• View Implementation
• The problem of efficiently implementing a view for quering is complex
• Two main approaches have been suggested
Query Modification
View Materialization
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 86
Query Modification
• Modifying the view query into a query on the underlying base tables
• Disadvantage: inefficient for views defined via complex queries that are time-
consuming to execute , especially if multiple queries are applied to the view within a
short period of time.
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 87
Example for Query Modification
The query example# would be automatically modified to the following query by the DBMS
Retrieve the Last name and First name of all employees who work on ‘ProductX’
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 88
View Materialization
• Physically create a temporary or permanent view table when the view is first queried
• Keep that table on the assumption that other queries on the view will follow
• Requires efficient strategy for automatically updating the view table when the base tables
are updated, that is Incremental Update
• Incremental Update determines what new tuples must be inserted, deleted, or
modified in a materialized view table when a change is applied to one of the
defining base table
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 89
View Update
• Immediate update- Update the view as soon as the base table are changed
• Lazy view-update the view when needed by a view query.
• Periodic Update-Update the view periodically.
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 90
Update on Views– Issues
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 91
Update the Pname attribute of ‘john smith’ from ‘ProductX’ to
‘ProductY’
UPDATE WORKS_ON1
SET Pname= ‘ProductY’
WHERE Lname=‘smith’ AND Fname=‘john’
AND Pname= ‘ProductX’
• This query can be mapped into several updates on the base relations to give the desired
effect on the view.
Fname Lname Pname Hours
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 92
Sample Dataset
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 93
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 94
Two possible updates (a) and (b) on the base relations corresponding to above
query
a) UPDATE WORKS_ON
b) UPDATE PROJECT
SET Pno= (SELECT Pnumber SET Pname=‘ProductY’
FROM PROJECT WHERE Pname= ‘ProductX’ ;
WHERE Pname= ‘ProductY’)
WHERE Essn IN (SELECT Ssn
FROM EMPLOYEE
WHERE Lname=‘smith’ AND
Fname=‘john’)
AND
Pno= (SELECT Pnumber
FROM PROJECT
WHERE Pname=‘ProductX’ );
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 95
Update
• Update (a) relates ‘john smith’ to the ‘ProductY’ PROJECT tuple in place of the
‘ProductX’ PROJECT tuple and is the most likely update.
Update (b) would also give the desired update effect on the view, but it
accomplishes this by changing the name of the ‘ProductX’ tuple in the PROJECT
relation to ‘ProductY’
Update on a view defined on a single table without any aggregate functions
Can be mapped to an update on underlying base table
View involving joins
Often not possible for DBMS to determine which of the updates is intended
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 96
OBSERVATIONS ON VIEWS
• A view with a single defining table is updatable if the view attributes contain the primary key of
the base relation, as well as all attributes with the NOT NULL constraint that do not have default
values specified
• Views defined on multiple tables using joins are generally not updatable
• Views defined using grouping and aggregate functions are not updatable .
• In SQL, the clause WITH CHECK OPTION must be added at the end of the view definition if a
view is to be updated.
• In-line view is one defined in the FROM clause of an SQL query
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 97
Advantages of Views
Data independence
➢ Improved security
➢ Reduced complexity
➢ Convenience
➢ Customization
➢ Data integrity
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 98
Schema Change Statements in SQL
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 99
Schema Change Statements in SQL
• We give an overview of the schema evolution commands available in SQL, which can be
used to alter a schema by adding or dropping tables, attributes, constraints, and other
schema elements.
• This can be done while the database is operational and does not require recompilation of
the database schema.
• Certain checks must be done by the DBMS to ensure that the changes do not affect the
rest of the database and make it inconsistent.
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 10
1.The DROP Command
• The DROP command can be used to drop named schema elements, such as tables,
domains, or constraints.
• One can also drop a schema.
• For example, if a whole schema is no longer needed, the DROP SCHEMA command can
be used.
There are two drop behaviour options:
• CASCADE
• RESTRICT.
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 10
Cascade vs Restrict Option
• For example, to remove the COMPANY database schema and all its tables, domains, and
other elements, the CASCADE option is used as follows:
• DROP SCHEMA COMPANY CASCADE;
• If the RESTRICT option is chosen in place of CASCADE, the schema is dropped only if
it has no elements in it;
• Else the DROP command will not be executed.
• To use the RESTRICT option, the user must first individually drop each element in the
schema, then drop the schema itself.
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 10
DROP TABLE COMMAND :
• If a base relation within a schema is no longer needed, the relation and its definition can
be deleted by using the DROP TABLE command.
• For example, if we no longer wish to keep track of dependents of employees in the
COMPANY .
• we can get rid of the DEPENDENT relation by issuing the following command:
DROP TABLE DEPENDENT CASCADE;
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 10
• If the RESTRICT option is chosen instead of CASCADE, a table is dropped only if it is
not referenced in any constraints (for example, by foreign key definitions in another
relation) or views or by any other elements.
• With the CASCADE option, all such constraints, views, and other elements that reference
the table being dropped are also dropped automatically from the schema, along with the
table itself.
• Notice that the DROP TABLE command not only deletes all the records in the table if
successful, but also removes the table definition from the catalog.
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 10
2.The ALTER Command
• The definition of a base table or of other named schema elements can be changed by
using the ALTER command.
• For base tables, the possible alter table actions include adding or dropping a column
(attribute),changing a column definition,and adding or dropping table constraints.
• For example, to add an attribute for keeping track of jobs of employees to the
EMPLOYEE base relation in the COMPANY schema , we can use the command.
• ALTER TABLE COMPANY.EMPLOYEE ADD COLUMN Job VARCHAR(12);
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 10
• We must still enter a value for the new attribute Job for each individual EMPLOYEE
tuple.
• This can be done either by specifying a default clause or by using the UPDATE
command individually on each tuple.
• If no default clause is specified, the new attribute will have NULLs in all the tuples of the
relation immediately after the command is executed; hence, the NOT NULL constraint is
not allowed in this case.
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 10
• To drop a column, we must choose either CASCADE or RESTRICT for drop behavior.
• If CASCADE is chosen, all constraints and views that reference the column are dropped
automatically from the schema, along with the column. If RESTRICT is chosen, the
command is successful only if no views or constraints (or other schema elements)
reference the column.
• For example, the following command removes the attribute Address from the
EMPLOYEE base table:
• ALTER TABLE COMPANY.EMPLOYEE DROP COLUMN Address CASCADE default
‘bangalore’;
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 10
• It is also possible to alter a column definition by dropping an existing default clause or by
defining a new default clause.
• The following examples illustrate this clause:
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 10
ALTER
• One can also change the constraints specified on a table by adding or dropping a named
constraint.
• To be dropped, a constraint must have been given a name when it was specified.
• For example, to drop the constraint named EMPSUPERFK from the EMPLOYEE
relation, we write:
• ALTER TABLE COMPANY.EMPLOYEE DROP CONSTRAINT EMPSUPERFK
CASCADE;
• Once this is done, we can redefine a replacement constraint by adding a new constraint to
the relation, if needed.
• This is specified by using the ADD keyword in the ALTER TABLE statement followed by
the new constraint, which can be named or unnamed and can be of any of the table
constraint types
Approved by AICTE |Affiliated to VTU | Recognized by UGC with 2(f) & 12(B) status |Accredited by NBA and NAAC 10