SlideShare a Scribd company logo
1 of 159
DATABASE MANAGEMENT SYSTEMS
UNIT-3
Syllabus:-
SQL Schema Definition, SQL Data Definition and Data Types , Specifying constraints
in SQL, Basic retrieval queries in SQL, Additional features of SQL ,More complex
SQL Queries, Insert, Delete and Update statements in SQL, Joined Tables in SQL
and Outer Joins, Aggregate functions , The GROUP BY and HAVING Clauses,
Specifying Constraints as Assertions and Triggers, Views (Virtual Tables) in SQL,
Schema Change Statement in SQL.
1
2
SQL Data Definition and Data Types
An SQL schema is identified by a schema name and includes an
authorization identifier to indicate the user or account who owns the
schema, as well as descriptors for each element in the schema.
 Schema elements include tables, types, constraints, views, domains,
and other constructs (such as authorization grants) that describe the
schema.
 A schema is created via the CREATE SCHEMA statement, which can
include all the schema elements’ definitions.
Example:- The following statement creates a schema called COMPANY
owned by the user with authorization identifier ‘Jsmith’
Syn:-CREATE SCHEMA COMPANY AUTHORIZATION ‘Jsmith’;
3
In general, not all users are authorized to create schemas and
schema elements. The privilege to create schemas, tables, and other
constructs must be explicitly granted to the relevant user accounts by the
system administrator or DBA.
 catalog—a named collection of schemas.
 A catalog always contains a special schema called
INFORMATION_SCHEMA, which provides information on all the
schemas in the catalog and all the element descriptors in these
schemas.
4
The CREATE TABLE Command in SQL
 CREATE TABLE command is used to specify a new relation by giving it a
name and specifying its attributes and initial constraints.
 The attributes are specified first, and each attribute is given a name, a
data type to specify its domain of values, and possibly attribute constraints,
such as NOT NULL.
 The key, entity integrity, and referential integrity constraints can be
specified within the CREATE TABLE statement after the attributes are
declared, or they can be added later using the ALTER TABLE command.
 Figure 6.1 shows sample data definition statements in SQL for the
COMPANY relational database schema shown below
5
6
7
 In SQL, the attributes in a base table are considered to be ordered in
the sequence in which they are specified in the CREATE TABLE
statement.
8
Attribute Data Types and Domains in SQL
9
SQL Operators-
The symbols which are used to perform logical and
mathematical operations in SQL are called SQL operators.
Three types of operators used in SQL are as follows:
10
11
12
13
Specifying Constraints in SQL
Specifying Attribute Constraints and Attribute Defaults
Because SQL allows NULLs as attribute values, a constraint NOT NULL
may be specified if NULL is not permitted for a particular attribute. This
is always implicitly specified for the attributes that are part of the primary
key of each relation, but it can be specified for any other attributes whose
values are required not to be NULL, as shown in Figure 6.1.
 It is also possible to define a default value for an attribute by
appending the clause DEFAULT <value> to an attribute definition. The
default value is included in any new tuple if an explicit value is not provided
for that attribute.
14
15
Another type of constraint can restrict attribute or domain values using
the CHECK clause following an attribute or domain definition.
Example:-suppose that department numbers are restricted to integer
numbers between 1 and 20; then, we can change the attribute
declaration of Dnumber in the DEPARTMENT table (see Figure 6.1) to the
following:
Dnumber INT NOT NULL CHECK (Dnumber > 0 AND Dnumber < 21);
16
Specifying Key and Referential Integrity Constraints
Some examples to illustrate the specification of keys and referential
integrity are shown in Figure 6.1
17
 The PRIMARY KEY clause specifies one or more attributes that make
up the primary key of a relation.
 For example, the primary key of DEPARTMENT can be specified as
follows (instead of the way it is specified in Figure 6.1):
Dnumber INT PRIMARY KEY,
The UNIQUE clause specifies alternate (unique) keys, also known as
candidate key as illustrated in the DEPARTMENT and PROJECT table
declarations in Figure 6.1.
The UNIQUE clause can also be specified directly for a unique key if it is
a single attribute, as in the following example:
Dname VARCHAR(15) UNIQUE
18
FOREIGN KEY – Ensure the referential integrity of the data in one
table to match values in another table.
 The options include SET NULL, CASCADE, and SET DEFAULT. An
option must be qualified with either ON DELETE or ON UPDATE.
19
The action for CASCADE ON DELETE is to delete all the referencing
tuples, whereas the action for CASCADE ON UPDATE is to change the
value of the referencing foreign key attribute(s) to the updated (new)
primary key value for all the referencing tuples
Giving Names to Constraints
Figure 6.2 also illustrates how a constraint may be given a constraint
name, following the keyword CONSTRAINT.
The names of all constraints within a particular schema must be unique.
A constraint name is used to identify a particular constraint in case the
constraint must be dropped later and replaced with another constraint.
20
21
Basic Retrieval Queries in SQL
SQL has one basic statement for retrieving information from a database:
the SELECT statement.
22
23
Query 0. Retrieve the birth date and address of the employee(s) whose
name is 'John B. Smith'.
QUERY
SELECT Bdate, Address
FROM EMPLOYEE
WHERE Fname = 'John' AND Minit = 'B' AND Lname = 'Smith';
OUTPUT:
24
Query 1. Retrieve the name and address of all employees who work for
the 'Research' department.
Query
SELECT Fname, Lname, Address
FROM EMPLOYEE, DEPARTMENT
WHERE Dname = 'Research' AND Dnumber = Dno;
OUTPUT:
25
Query 2. For every project located in ‘Stafford’, list the project
number, the controlling department number, and the department
manager’s last name, address, and birth date.
Query
SELECT Pnumber, Dnum, Lname, Address, Bdate
FROM PROJECT, DEPARTMENT, EMPLOYEE
WHERE Dnum = Dnumber AND Mgr_ssn = Ssn AND Plocation = 'Stafford';
OUTPUT:
26
Ambiguous Attribute Names, Aliasing, Renaming, and Tuple Variables
In SQL, the same name can be used for two (or more) attributes as
long as the attributes are in different tables.
If this is the case, and a multitable query refers to two or more
attributes with the same name, we must qualify the attribute name
with the relation name to prevent ambiguity.
This is done by prefixing the relation name to the attribute name and
separating the two by a period
27
Query 8. For each employee, retrieve the employee’s first and last
name and the first and last name of his or her immediate supervisor.
Query
SELECT E.Fname, E.Lname, S.Fname, S.Lname
FROM EMPLOYEE E, EMPLOYEE S
WHERE E.Super_ssn = S.Ssn;
OUTPUT:
28
29
Unspecified WHERE Clause and Use of the Asterisk
30
31
Query Q1C retrieves all the attribute values of any EMPLOYEE who
works in DEPARTMENT number 5
Query
SELECT *
FROM EMPLOYEE
WHERE Dno = 5;
32
Query Q1D retrieves all the attributes of an EMPLOYEE and the
attributes of the DEPARTMENT in which he or she works for every
employee of the ‘Research’ department,
Query
SELECT *
FROM EMPLOYEE, DEPARTMENT
WHERE Dname = ‘Research’ AND Dno = Dnumber;
33
OUTPUT:
Q11 Q11A
34
SQL has directly incorporated some of the set operations from
mathematical set theory, which are also part of relational algebra.
There are set union (UNION), set difference (EXCEPT), and set
intersection (INTERSECT) operations.
The relations resulting from these set operations are sets of tuples; that
is, duplicate tuples are eliminated from the result.
These set operations apply only to type compatible relations, so we
must make sure that the two relations on which we apply the operation
have the
same attributes
attributes appear in the same order in both relations.
The next example illustrates the use of UNION.
Tables as Sets in SQL
35
36
37
( SELECT DISTINCT Pnumber
FROM PROJECT, DEPARTMENT, EMPLOYEE
WHERE Dnum = Dnumber AND Mgr_ssn = Ssn AND Lname = 'Smith' )
UNION
( SELECT DISTINCT Pnumber
FROM PROJECT, WORKS_ON, EMPLOYEE
WHERE Pnumber = Pno AND Essn = Ssn AND Lname = 'Smith' );
38
39
Find the fnames of employees who are working in ProductX or
ProductY
select e1.fname from employee e1,works_on w1,project p1
where e1.ssn=w1.essn and w1.pno=p1.pnumber and p1.pname='ProductX'
union
select e2.fname from employee e2,works_on w2,project p2
where e2.ssn=w2.essn and w2.pno=p2.pnumber and p2.pname='ProductY';
40
Find the fnames of employees who are working in ProductX or
ProductY(UNION ALL)
select e1.fname from employee e1,works_on w1,project p1
where e1.ssn=w1.essn and w1.pno=p1.pnumber and p1.pname='ProductX'
Union ALL
select e2.fname from employee e2,works_on w2,project p2
where e2.ssn=w2.essn and w2.pno=p2.pnumber and p2.pname='ProductY';
41
Find the fnames of employees who are working in both ProductX
and ProductY
select e1.fname from employee e1,works_on w1,project p1
where e1.ssn=w1.essn and w1.pno=p1.pnumber and p1.pname='ProductX'
Intersect
select e2.fname from employee e2,works_on w2,project p2
where e2.ssn=w2.essn and w2.pno=p2.pnumber and
p2.pname='ProductY';
42
Find the fnames of employees who are working in ProductY but not
in ProductX
select e2.fname from employee e2,works_on w2,project p2
where e2.ssn=w2.essn and w2.pno=p2.pnumber and p2.pname='ProductY'
minus
select e1.fname from employee e1,works_on w1,project p1
where e1.ssn=w1.essn and w1.pno=p1.pnumber and p1.pname='ProductX';
43
Substring Pattern Matching and Arithmetic Operators
The first feature allows comparison conditions on only parts of a character
string, using the LIKE comparison operator.
This can be used for string pattern matching
 Partial strings are specified using two reserved characters
 % replaces an arbitrary number of zero or more characters,
 (_) replaces a single character. For example, consider the following query.
44
Query 12. Retrieve all employees whose address is in Houston.
QUERY
SELECT Fname, Lname
FROM EMPLOYEE
WHERE Address LIKE ‘%Houston%’;
OUTPUT:
45
Query 12A. Find all employees who were born during the 1950s
QUERY
SELECT Fname, Lname
FROM EMPLOYEE
WHERE Bdate LIKE '_______5_';
OUTPUT:
46
SELECT E.Fname, E.Lname, 1.1 * E.Salary AS Increased_sal
FROM EMPLOYEE E, WORKS_ON W, PROJECT P
WHERE E.Ssn = W.Essn AND W.Pno = P.Pnumber AND P.Pname ='ProductX';
OUTPUT:
47
48
Ordering of Query Results
Query 15. Retrieve a list of employees and the projects they are working
on, ordered by department and, within each department, ordered
alphabetically by last name, then first name.
49
INSERT, DELETE, and UPDATE Statements in SQL
 In SQL, three commands can be used to modify the database: INSERT,
DELETE, and UPDATE.
 The INSERT Command
 INSERT is used to add a single tuple (row) to a relation (table).
 We must specify the relation name and a list of values for the tuple
The values should be listed in the same order in which the
corresponding attributes were specified in the CREATE TABLE
command.
 Example:-to add a new tuple to the EMPLOYEE relation
50
DBMS that fully implements SQL should support and enforce all the
integrity constraints that can be specified in the DDL.
For example, if we issue the command in U2 on the database shown in
Figure 5.6, the DBMS should reject the operation because no
DEPARTMENT tuple exists in the database with Dnumber = 2. Similarly,
U2A would be rejected because no Ssn value is provided and it is the
primary key, which cannot be NULL.
51
If you want to create a table D5EMPS with a similar structure to the
EMPLOYEE table and load it with the rows of employees who work in
department 5, we can write the following SQL.
CREATE TABLE D5EMPS1 as select * from EMPLOYEE where e.dno=5;
52
The DELETE command removes tuples from a relation. It includes a
WHERE clause, similar to that used in an SQL query, to select the tuples to
be deleted.
Tuples are explicitly deleted from only one table at a time.
 A missing WHERE clause specifies that all tuples in the relation are to be
deleted.
 We must use the DROP TABLE command to remove the table definition
The DELETE Command
53
The UPDATE Command
 The UPDATE command is used to modify attribute values of one or
more selected tuples.
As in the DELETE command, a WHERE clause in the UPDATE command
selects the tuples to be modified from a single relation.
 An additional SET clause in the UPDATE command specifies the
attributes to be modified and their new values.
Actual table
54
 Several tuples can be modified with a single UPDATE command.
Example:-
example is to give all employees in the ‘Research’ department a 10%
raise in salary, as shown in U6
55
Joined Tables in SQL and Outer Joins
 The concept of a joined table (or joined relation) was incorporated into
SQL to permit users to specify a table resulting from a join operation in the
FROM clause of a query.
56
If the user requires that all employees be included, a different type of join called
OUTER JOIN must be used explicitly.
57
LEFT OUTER JOIN (every tuple in the left table must appear in the
result; if it does not have a matching tuple, it is padded with NULL values
for the attributes of the right table)
RIGHT OUTER JOIN (every tuple in the right table must appear in the
result; if it does not have a matching tuple, it is padded with NULL values
for the attributes of the left table)
 The keyword CROSS JOIN is used to specify the CARTESIAN PRODUCT
operation.
 It is also possible to nest join specifications; that is, one of the tables in a
join may itself be a joined table. This allows the specification of the join of
three or more tables as a single joined table, which is called a multiway
join
Joins
Hyperlink to local document
58
59
Aggregate Functions in SQL
 Aggregate functions are used to summarize information from
multiple tuples into a single-tuple summary.
 A number of built-in aggregate functions exist: COUNT, SUM, MAX,
MIN, and AVG.
 COUNT function returns the number of tuples or values as specified in a
query.
 These functions can be used in the SELECT clause or in a HAVING
clause.
60
Query 19. Find the sum of the salaries of all employees, the maximum
salary, the minimum salary, and the average salary.
QUERY
SELECT SUM (Salary), MAX (Salary), MIN (Salary), AVG (Salary)
FROM EMPLOYEE;
INPUT
61
Q19A:
SELECT SUM (Salary) Total_Sal, MAX (Salary) Highest_Sal,
MIN (Salary) Lowest_Sal, AVG (Salary) Average_Sal
FROM EMPLOYEE;
62
Query 20. Find the sum of the salaries of all employees of the
‘Research’ department, as well as the maximum salary, the minimum
salary, and the average salary in this department.
63
Queries 21 and 22. Retrieve the total number of employees in the
company
(Q21) and the number of employees in the ‘Research’ department
(Q22).
64
Query 23. Count the number of distinct salary values in the database
65
Grouping: The GROUP BY and HAVING Clauses
In many cases we want to apply the aggregate functions to
subgroups of tuples in a relation, where the subgroups are based on
some attribute values.
 example, we may want to find the average salary of employees in
each department or the number of employees who work on each
project.
 SQL has a GROUP BY clause for this purpose.
 The GROUP BY clause specifies the grouping attributes, which
should also appear in the SELECT clause, so that the value resulting
from applying each aggregate function to a group of tuples appears
along with the value of the grouping attribute(s).
66
Query 24. For each department, retrieve the department number, the
number of employees in the department, and their average salary
67
Query 25. For each project, retrieve the project number, the project
name, and the number of employees who work on that project.
68
Query 26.
For each project on which more than two employees work, retrieve
the project number, the project name, and the number of employees
who work on the project.
69
Query 27. For each project, retrieve the project number, the project
name, and the number of employees from department 5 who work on
the project
70
Suppose that we want to count the total number of employees whose
salaries exceed $40,000 in each department, but only for departments
where more than five employees work.
Hint:-Here, the condition (SALARY > 40000) applies only to the COUNT
function in the SELECT clause. Suppose that we write the following
incorrect query:
71
Specifying Constraints as Assertions and Actions as Triggers
 Each assertion is given a constraint name and is specified via a
condition similar to the WHERE clause of an SQL query.
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:
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.
72
A manager may want to be informed if an employee’s travel expenses
exceed a certain limit by receiving a message whenever this occurs. The
action that the DBMS must take in this case is to send an appropriate
message to that user. The condition is thus used to monitor the database
The CREATE TRIGGER statement is used to implement such actions in
SQL.
Trigger: A trigger is a stored procedure in database which
automatically invokes whenever a special event in the database
occurs.
For example, a trigger can be invoked when a row is inserted into a
specified table or when certain table columns are being updated.
Syntax:
create trigger [trigger_name]
[before | after]
{insert | update | delete}
on [table_name]
[for each row]
[trigger_body]
Introduction to Triggers in SQL
73
create trigger [trigger_name]: Creates or replaces an existing
trigger with the trigger_name.
[before | after]: This specifies when the trigger will be fired.
{insert | update | delete}: This specifies the DML operation.
on [table_name]: This specifies the name of the table associated
with the trigger.
[for each row]: This specifies a row-level trigger, i.e., the trigger will
be executed for each row being affected.
[trigger_body]: This provides the operation to be performed as
trigger is fired Each trigger is attached to a single, specified table in
the database
74
We have two types of triggers:
1.Row-level triggers—these are executed for each row
2.Statement-level triggers—at one time, triggers are
executed.
75
76
77
78
79
Create trigger:
The following trigger will display the salary difference between the old
values and new values:
SQL> 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;
/
Trigger created.
80
INSERT INTO customers VALUES (7,'Karthik',22,‘VRSEC',87000);
When a record is created in CUSTOMERS table, above create trigger
display_salary_changes will be fired and it will display the following result:
Output:-
SQL> INSERT INTO customers VALUES (7,'Karthik',22,‘VRSEC',87000);
Old salary:
New salary: 87000
Salary difference:
1 row created.
81
Views (Virtual Tables) in SQL
 A view in SQL terminology is a single table that is derived from
other tables.
 These other tables can be base tables or previously defined views.
 A view does not necessarily exist in physical form; it is considered
to be a virtual table, in contrast to base tables, whose tuples are always
physically stored in the database.
Specification of Views in SQL.
 In SQL, the command to specify a 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.
82
V1:
CREATE VIEW WORKS_ON1
AS SELECT Fname, Lname, Pname, Hours
FROM EMPLOYEE, PROJECT, WORKS_ON
WHERE Ssn = Essn AND Pno = Pnumber;
83
84
V2 :
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;
OUTPUT:
85
We can now specify SQL queries on a view—or virtual table—in the
same way we specify queries involving base tables.
Query: To retrieve the last name and first name of all employees who
work on the ‘ProductX’ project,
we can utilize the WORKS_ON1 view and specify the query as in QV1:
QV1:
SELECT Fname, Lname
FROM WORKS_ON1
WHERE Pname = ‘ProductX’;
86
If we do not need a view anymore,
we can use the DROP VIEW command to dispose of it.
For example, to get rid of the view V1, we can use the SQL statement in
V1A:
DROP VIEW WORKS_ON1;
Different strategies as to when a materialized view is updated are
possible.
The immediate update strategy updates a view as soon as the base
tables are changed;
lazy update strategy updates the view when needed by a view query;
 periodic update strategy updates the view periodically (in the latter
strategy, a view query may get a result that is not up-to-date).
87
However, issuing an INSERT, DELETE, or UPDATE command on a view
table is in many cases not possible.
 Views defined on multiple tables using joins are generally not
updatable.
Views defined using grouping and aggregate functions are not
updatable.
Views as Authorization Mechanisms
CREATE VIEW DEPT5EMP AS
SELECT *
FROM EMPLOYEE
WHERE Dno = 5;
CREATE VIEW BASIC_EMP_DATA AS
SELECT Fname, Lname, Address
FROM EMPLOYEE;
88
Schema Change Statements in SQL
The DROP Command
 The DROP command can be used to drop named schema elements,
such as tables, domains, types, or constraints.
One can also drop a whole schema if it is no longer needed by using
the DROP SCHEMA command.
 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; otherwise, 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.
89
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 (see Figure 6.1),
we can use the command
ALTER TABLE COMPANY.EMPLOYEE ADD COLUMN Job VARCHAR(12);
90
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.
example, the following command removes the attribute Address from the
EMPLOYEE base table:
ALTER TABLE COMPANY.EMPLOYEE DROP COLUMN Address CASCADE;
91
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:
ALTER TABLE COMPANY.DEPARTMENT ALTER COLUMN Mgr_ssn DROP
DEFAULT;
ALTER TABLE COMPANY.DEPARTMENT ALTER COLUMN Mgr_ssn
SET DEFAULT ‘333445555’;
One can also change the constraints specified on a table by adding or
dropping a named constraint.
ALTER TABLE COMPANY.EMPLOYEE DROP CONSTRAINT EMPSUPERFK
CASCADE;
Functional Dependencies
The single most important concept in relational schema design is
a functional dependency.
A Functional Dependency describes a relationship between
attributes within a single relation
An attribute is functionally dependent on another if we can use
the value of one attribute to determine the value of another.
Formally, functional dependency is defined as;
Functional dependency – In a given relation R, X and Y are attributes.
Attribute Y is functionally dependent on attribute X if each value of X
determines exactly one value of Y. This is represented as X → Y.
For example, consider the following relation
Reports(Student#, Course#, CourseName, Iname, Room#, Marks, Grade)
In this relation, {Student#, Course#} together can determine exactly one
value of Marks. This can be symbolically represented as
{Student#, Course#} → Marks
This type of dependency is called as functional dependency. In the above
example Marks is functionally dependent on {Student#, Course#}.
Other functional dependencies in the above example are:
Course# → CourseName
Course# → Iname ( Assuming one course is taught by one and
only one instructor)
Iname → Room# (Assuming each instructor has his/her own
room)
Marks → Grade
Course# → Room#
VRSEC-CSE-DBMS-III-B-VR_20 95
VRSEC-CSE-DBMS-III-B-VR_20 96
VRSEC-CSE-DBMS-III-B-VR_20 97
VRSEC-CSE-DBMS-III-B-VR_20 98
VRSEC-CSE-DBMS-III-B-VR_20 99
VRSEC-CSE-DBMS-III-B-VR_20 100
VRSEC-CSE-DBMS-III-B-VR_20 101
VRSEC-CSE-DBMS-III-B-VR_20 102
Full Functional Dependency - In a given relation R, X and Y are
attributes. Attribute Y is fully functionally dependent on attribute X
only if it is not functionally dependent on sub-set of X where X is
composite in nature.
In the above example, Marks is fully functionally dependent on
{Student#, Course#} and not on sub-set of {Student#, Course#}.
This means Marks cannot be determined either by Student# or by
Course#. It can be determined using Student# and Course#
together. Hence, Marks is fully functionally dependent on
{Student#, Course#}.
For example,
suppose there is a relation R (A, B, C, D) with
functional dependency set (A->BC).
The relational R is decomposed into
R1(ABC)
R2(AD)
Solution:
It id dependency preserving
because FD A->BC is a part of relation R1(ABC).
VRSEC-CSE-DBMS-III-B-VR_20 131
FOURTH NORMAL FORM-4NF
A multivalued dependency X → Y specified on relation schema R, where
X and Y are both subsets of R, specifies the following constraint on any
relation state r of R:
If two tuples t1 and t2 exist in r such that t1[X] = t2[X], then two tuples t3
and t4 should also exist in r with the following properties, where we use Z
to denote (R − (X ∪ Y)):
Definition:
A Relation R is in 4NF if and only if the following conditions are satisfied
(i) R is in already BCNF or 3NF
(ii) R contains no MVDs
VRSEC-CSE-DBMS-III-B-VR_20 132
VRSEC-CSE-DBMS-III-B-VR_20 133
VRSEC-CSE-DBMS-III-B-VR_20 134
VRSEC-CSE-DBMS-III-B-VR_20 135
VRSEC-CSE-DBMS-III-B-VR_20 136
VRSEC-CSE-DBMS-III-B-VR_20 137
VRSEC-CSE-DBMS-III-B-VR_20 138
VRSEC-CSE-DBMS-III-B-VR_20 139
VRSEC-CSE-DBMS-III-B-VR_20 140
VRSEC-CSE-DBMS-III-B-VR_20 141
VRSEC-CSE-DBMS-III-B-VR_20 142
VRSEC-CSE-DBMS-III-B-VR_20 143
VRSEC-CSE-DBMS-III-B-VR_20 144
VRSEC-CSE-DBMS-III-B-VR_20 145
VRSEC-CSE-DBMS-III-B-VR_20 146
VRSEC-CSE-DBMS-III-B-VR_20 147
VRSEC-CSE-DBMS-III-B-VR_20 148
VRSEC-CSE-DBMS-III-B-VR_20 149
VRSEC-CSE-DBMS-III-B-VR_20 150
VRSEC-CSE-DBMS-III-B-VR_20 151
Keeping both the relations separately will results a Good database design
VRSEC-CSE-DBMS-III-B-VR_20 152
VRSEC-CSE-DBMS-III-B-VR_20 153
VRSEC-CSE-DBMS-III-B-VR_20 154
VRSEC-CSE-DBMS-III-B-VR_20 155
VRSEC-CSE-DBMS-III-B-VR_20 156
VRSEC-CSE-DBMS-III-B-VR_20 157
FIFTH NORMAL FORM-5NF
VRSEC-CSE-DBMS-III-B-VR_20 158
This is in
5NF
VRSEC-CSE-DBMS-III-B-VR_20 159

More Related Content

Similar to UNIT-3.pptx

Adbms 21 sql 99 schema definition constraints and queries
Adbms 21 sql 99 schema definition constraints and queriesAdbms 21 sql 99 schema definition constraints and queries
Adbms 21 sql 99 schema definition constraints and queriesVaibhav Khanna
 
6_SQL.pdf
6_SQL.pdf6_SQL.pdf
6_SQL.pdfLPhct2
 
DBMS MODULE 3 NOTES ENGINEERING CSE .pdf
DBMS MODULE 3 NOTES ENGINEERING CSE .pdfDBMS MODULE 3 NOTES ENGINEERING CSE .pdf
DBMS MODULE 3 NOTES ENGINEERING CSE .pdfraki082m
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxBhupendraShahi6
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSabrinaShanta2
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSaiMiryala1
 
Module 3.1.pptx
Module 3.1.pptxModule 3.1.pptx
Module 3.1.pptxANSHVAJPAI
 
Chapter 07 ddl_sql
Chapter 07 ddl_sqlChapter 07 ddl_sql
Chapter 07 ddl_sqlNazir Ahmed
 
Web app development_my_sql_09
Web app development_my_sql_09Web app development_my_sql_09
Web app development_my_sql_09Hassen Poreya
 
2. DBMS Experiment - Lab 2 Made in SQL Used
2. DBMS Experiment - Lab 2 Made in SQL Used2. DBMS Experiment - Lab 2 Made in SQL Used
2. DBMS Experiment - Lab 2 Made in SQL UsedTheVerse1
 
Sql tutorial
Sql tutorialSql tutorial
Sql tutorialamitabros
 

Similar to UNIT-3.pptx (20)

Adbms 21 sql 99 schema definition constraints and queries
Adbms 21 sql 99 schema definition constraints and queriesAdbms 21 sql 99 schema definition constraints and queries
Adbms 21 sql 99 schema definition constraints and queries
 
Query
QueryQuery
Query
 
6_SQL.pdf
6_SQL.pdf6_SQL.pdf
6_SQL.pdf
 
Assignment#07
Assignment#07Assignment#07
Assignment#07
 
DBMS MODULE 3 NOTES ENGINEERING CSE .pdf
DBMS MODULE 3 NOTES ENGINEERING CSE .pdfDBMS MODULE 3 NOTES ENGINEERING CSE .pdf
DBMS MODULE 3 NOTES ENGINEERING CSE .pdf
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
 
SQL Query
SQL QuerySQL Query
SQL Query
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
 
Module 3.1.pptx
Module 3.1.pptxModule 3.1.pptx
Module 3.1.pptx
 
Interview Questions.pdf
Interview Questions.pdfInterview Questions.pdf
Interview Questions.pdf
 
Unit04 dbms
Unit04 dbmsUnit04 dbms
Unit04 dbms
 
Chapter 07 ddl_sql
Chapter 07 ddl_sqlChapter 07 ddl_sql
Chapter 07 ddl_sql
 
Sql 2006
Sql 2006Sql 2006
Sql 2006
 
Sql
SqlSql
Sql
 
Select To Order By
Select  To  Order BySelect  To  Order By
Select To Order By
 
Web app development_my_sql_09
Web app development_my_sql_09Web app development_my_sql_09
Web app development_my_sql_09
 
Oracle sql material
Oracle sql materialOracle sql material
Oracle sql material
 
2. DBMS Experiment - Lab 2 Made in SQL Used
2. DBMS Experiment - Lab 2 Made in SQL Used2. DBMS Experiment - Lab 2 Made in SQL Used
2. DBMS Experiment - Lab 2 Made in SQL Used
 
Sql tutorial
Sql tutorialSql tutorial
Sql tutorial
 

Recently uploaded

Call me @ 9892124323 Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
Call me @ 9892124323  Cheap Rate Call Girls in Vashi with Real Photo 100% SecureCall me @ 9892124323  Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
Call me @ 9892124323 Cheap Rate Call Girls in Vashi with Real Photo 100% SecurePooja Nehwal
 
VidaXL dropshipping via API with DroFx.pptx
VidaXL dropshipping via API with DroFx.pptxVidaXL dropshipping via API with DroFx.pptx
VidaXL dropshipping via API with DroFx.pptxolyaivanovalion
 
Best VIP Call Girls Noida Sector 22 Call Me: 8448380779
Best VIP Call Girls Noida Sector 22 Call Me: 8448380779Best VIP Call Girls Noida Sector 22 Call Me: 8448380779
Best VIP Call Girls Noida Sector 22 Call Me: 8448380779Delhi Call girls
 
Cheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 night
Cheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 nightCheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 night
Cheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 nightDelhi Call girls
 
Best VIP Call Girls Noida Sector 39 Call Me: 8448380779
Best VIP Call Girls Noida Sector 39 Call Me: 8448380779Best VIP Call Girls Noida Sector 39 Call Me: 8448380779
Best VIP Call Girls Noida Sector 39 Call Me: 8448380779Delhi Call girls
 
Data-Analysis for Chicago Crime Data 2023
Data-Analysis for Chicago Crime Data  2023Data-Analysis for Chicago Crime Data  2023
Data-Analysis for Chicago Crime Data 2023ymrp368
 
Zuja dropshipping via API with DroFx.pptx
Zuja dropshipping via API with DroFx.pptxZuja dropshipping via API with DroFx.pptx
Zuja dropshipping via API with DroFx.pptxolyaivanovalion
 
Halmar dropshipping via API with DroFx
Halmar  dropshipping  via API with DroFxHalmar  dropshipping  via API with DroFx
Halmar dropshipping via API with DroFxolyaivanovalion
 
Smarteg dropshipping via API with DroFx.pptx
Smarteg dropshipping via API with DroFx.pptxSmarteg dropshipping via API with DroFx.pptx
Smarteg dropshipping via API with DroFx.pptxolyaivanovalion
 
CebaBaby dropshipping via API with DroFX.pptx
CebaBaby dropshipping via API with DroFX.pptxCebaBaby dropshipping via API with DroFX.pptx
CebaBaby dropshipping via API with DroFX.pptxolyaivanovalion
 
BPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptx
BPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptxBPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptx
BPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptxMohammedJunaid861692
 
Ravak dropshipping via API with DroFx.pptx
Ravak dropshipping via API with DroFx.pptxRavak dropshipping via API with DroFx.pptx
Ravak dropshipping via API with DroFx.pptxolyaivanovalion
 
BabyOno dropshipping via API with DroFx.pptx
BabyOno dropshipping via API with DroFx.pptxBabyOno dropshipping via API with DroFx.pptx
BabyOno dropshipping via API with DroFx.pptxolyaivanovalion
 
Delhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Callshivangimorya083
 
BigBuy dropshipping via API with DroFx.pptx
BigBuy dropshipping via API with DroFx.pptxBigBuy dropshipping via API with DroFx.pptx
BigBuy dropshipping via API with DroFx.pptxolyaivanovalion
 
Carero dropshipping via API with DroFx.pptx
Carero dropshipping via API with DroFx.pptxCarero dropshipping via API with DroFx.pptx
Carero dropshipping via API with DroFx.pptxolyaivanovalion
 
Determinants of health, dimensions of health, positive health and spectrum of...
Determinants of health, dimensions of health, positive health and spectrum of...Determinants of health, dimensions of health, positive health and spectrum of...
Determinants of health, dimensions of health, positive health and spectrum of...shambhavirathore45
 

Recently uploaded (20)

Call me @ 9892124323 Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
Call me @ 9892124323  Cheap Rate Call Girls in Vashi with Real Photo 100% SecureCall me @ 9892124323  Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
Call me @ 9892124323 Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
 
VidaXL dropshipping via API with DroFx.pptx
VidaXL dropshipping via API with DroFx.pptxVidaXL dropshipping via API with DroFx.pptx
VidaXL dropshipping via API with DroFx.pptx
 
Best VIP Call Girls Noida Sector 22 Call Me: 8448380779
Best VIP Call Girls Noida Sector 22 Call Me: 8448380779Best VIP Call Girls Noida Sector 22 Call Me: 8448380779
Best VIP Call Girls Noida Sector 22 Call Me: 8448380779
 
Cheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 night
Cheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 nightCheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 night
Cheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 night
 
Best VIP Call Girls Noida Sector 39 Call Me: 8448380779
Best VIP Call Girls Noida Sector 39 Call Me: 8448380779Best VIP Call Girls Noida Sector 39 Call Me: 8448380779
Best VIP Call Girls Noida Sector 39 Call Me: 8448380779
 
Abortion pills in Doha Qatar (+966572737505 ! Get Cytotec
Abortion pills in Doha Qatar (+966572737505 ! Get CytotecAbortion pills in Doha Qatar (+966572737505 ! Get Cytotec
Abortion pills in Doha Qatar (+966572737505 ! Get Cytotec
 
Data-Analysis for Chicago Crime Data 2023
Data-Analysis for Chicago Crime Data  2023Data-Analysis for Chicago Crime Data  2023
Data-Analysis for Chicago Crime Data 2023
 
Zuja dropshipping via API with DroFx.pptx
Zuja dropshipping via API with DroFx.pptxZuja dropshipping via API with DroFx.pptx
Zuja dropshipping via API with DroFx.pptx
 
Halmar dropshipping via API with DroFx
Halmar  dropshipping  via API with DroFxHalmar  dropshipping  via API with DroFx
Halmar dropshipping via API with DroFx
 
CHEAP Call Girls in Saket (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Saket (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Saket (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Saket (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Smarteg dropshipping via API with DroFx.pptx
Smarteg dropshipping via API with DroFx.pptxSmarteg dropshipping via API with DroFx.pptx
Smarteg dropshipping via API with DroFx.pptx
 
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in Kishangarh
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in  KishangarhDelhi 99530 vip 56974 Genuine Escort Service Call Girls in  Kishangarh
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in Kishangarh
 
CebaBaby dropshipping via API with DroFX.pptx
CebaBaby dropshipping via API with DroFX.pptxCebaBaby dropshipping via API with DroFX.pptx
CebaBaby dropshipping via API with DroFX.pptx
 
BPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptx
BPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptxBPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptx
BPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptx
 
Ravak dropshipping via API with DroFx.pptx
Ravak dropshipping via API with DroFx.pptxRavak dropshipping via API with DroFx.pptx
Ravak dropshipping via API with DroFx.pptx
 
BabyOno dropshipping via API with DroFx.pptx
BabyOno dropshipping via API with DroFx.pptxBabyOno dropshipping via API with DroFx.pptx
BabyOno dropshipping via API with DroFx.pptx
 
Delhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
 
BigBuy dropshipping via API with DroFx.pptx
BigBuy dropshipping via API with DroFx.pptxBigBuy dropshipping via API with DroFx.pptx
BigBuy dropshipping via API with DroFx.pptx
 
Carero dropshipping via API with DroFx.pptx
Carero dropshipping via API with DroFx.pptxCarero dropshipping via API with DroFx.pptx
Carero dropshipping via API with DroFx.pptx
 
Determinants of health, dimensions of health, positive health and spectrum of...
Determinants of health, dimensions of health, positive health and spectrum of...Determinants of health, dimensions of health, positive health and spectrum of...
Determinants of health, dimensions of health, positive health and spectrum of...
 

UNIT-3.pptx

  • 1. DATABASE MANAGEMENT SYSTEMS UNIT-3 Syllabus:- SQL Schema Definition, SQL Data Definition and Data Types , Specifying constraints in SQL, Basic retrieval queries in SQL, Additional features of SQL ,More complex SQL Queries, Insert, Delete and Update statements in SQL, Joined Tables in SQL and Outer Joins, Aggregate functions , The GROUP BY and HAVING Clauses, Specifying Constraints as Assertions and Triggers, Views (Virtual Tables) in SQL, Schema Change Statement in SQL. 1
  • 2. 2 SQL Data Definition and Data Types An SQL schema is identified by a schema name and includes an authorization identifier to indicate the user or account who owns the schema, as well as descriptors for each element in the schema.  Schema elements include tables, types, constraints, views, domains, and other constructs (such as authorization grants) that describe the schema.  A schema is created via the CREATE SCHEMA statement, which can include all the schema elements’ definitions. Example:- The following statement creates a schema called COMPANY owned by the user with authorization identifier ‘Jsmith’ Syn:-CREATE SCHEMA COMPANY AUTHORIZATION ‘Jsmith’;
  • 3. 3 In general, not all users are authorized to create schemas and schema elements. The privilege to create schemas, tables, and other constructs must be explicitly granted to the relevant user accounts by the system administrator or DBA.  catalog—a named collection of schemas.  A catalog always contains a special schema called INFORMATION_SCHEMA, which provides information on all the schemas in the catalog and all the element descriptors in these schemas.
  • 4. 4 The CREATE TABLE Command in SQL  CREATE TABLE command is used to specify a new relation by giving it a name and specifying its attributes and initial constraints.  The attributes are specified first, and each attribute is given a name, a data type to specify its domain of values, and possibly attribute constraints, such as NOT NULL.  The key, entity integrity, and referential integrity constraints can be specified within the CREATE TABLE statement after the attributes are declared, or they can be added later using the ALTER TABLE command.  Figure 6.1 shows sample data definition statements in SQL for the COMPANY relational database schema shown below
  • 5. 5
  • 6. 6
  • 7. 7  In SQL, the attributes in a base table are considered to be ordered in the sequence in which they are specified in the CREATE TABLE statement.
  • 8. 8 Attribute Data Types and Domains in SQL
  • 9. 9
  • 10. SQL Operators- The symbols which are used to perform logical and mathematical operations in SQL are called SQL operators. Three types of operators used in SQL are as follows: 10
  • 11. 11
  • 12. 12
  • 13. 13 Specifying Constraints in SQL Specifying Attribute Constraints and Attribute Defaults Because SQL allows NULLs as attribute values, a constraint NOT NULL may be specified if NULL is not permitted for a particular attribute. This is always implicitly specified for the attributes that are part of the primary key of each relation, but it can be specified for any other attributes whose values are required not to be NULL, as shown in Figure 6.1.  It is also possible to define a default value for an attribute by appending the clause DEFAULT <value> to an attribute definition. The default value is included in any new tuple if an explicit value is not provided for that attribute.
  • 14. 14
  • 15. 15 Another type of constraint can restrict attribute or domain values using the CHECK clause following an attribute or domain definition. Example:-suppose that department numbers are restricted to integer numbers between 1 and 20; then, we can change the attribute declaration of Dnumber in the DEPARTMENT table (see Figure 6.1) to the following: Dnumber INT NOT NULL CHECK (Dnumber > 0 AND Dnumber < 21);
  • 16. 16 Specifying Key and Referential Integrity Constraints Some examples to illustrate the specification of keys and referential integrity are shown in Figure 6.1
  • 17. 17  The PRIMARY KEY clause specifies one or more attributes that make up the primary key of a relation.  For example, the primary key of DEPARTMENT can be specified as follows (instead of the way it is specified in Figure 6.1): Dnumber INT PRIMARY KEY, The UNIQUE clause specifies alternate (unique) keys, also known as candidate key as illustrated in the DEPARTMENT and PROJECT table declarations in Figure 6.1. The UNIQUE clause can also be specified directly for a unique key if it is a single attribute, as in the following example: Dname VARCHAR(15) UNIQUE
  • 18. 18 FOREIGN KEY – Ensure the referential integrity of the data in one table to match values in another table.  The options include SET NULL, CASCADE, and SET DEFAULT. An option must be qualified with either ON DELETE or ON UPDATE.
  • 19. 19 The action for CASCADE ON DELETE is to delete all the referencing tuples, whereas the action for CASCADE ON UPDATE is to change the value of the referencing foreign key attribute(s) to the updated (new) primary key value for all the referencing tuples Giving Names to Constraints Figure 6.2 also illustrates how a constraint may be given a constraint name, following the keyword CONSTRAINT. The names of all constraints within a particular schema must be unique. A constraint name is used to identify a particular constraint in case the constraint must be dropped later and replaced with another constraint.
  • 20. 20
  • 21. 21 Basic Retrieval Queries in SQL SQL has one basic statement for retrieving information from a database: the SELECT statement.
  • 22. 22
  • 23. 23 Query 0. Retrieve the birth date and address of the employee(s) whose name is 'John B. Smith'. QUERY SELECT Bdate, Address FROM EMPLOYEE WHERE Fname = 'John' AND Minit = 'B' AND Lname = 'Smith'; OUTPUT:
  • 24. 24 Query 1. Retrieve the name and address of all employees who work for the 'Research' department. Query SELECT Fname, Lname, Address FROM EMPLOYEE, DEPARTMENT WHERE Dname = 'Research' AND Dnumber = Dno; OUTPUT:
  • 25. 25 Query 2. For every project located in ‘Stafford’, list the project number, the controlling department number, and the department manager’s last name, address, and birth date. Query SELECT Pnumber, Dnum, Lname, Address, Bdate FROM PROJECT, DEPARTMENT, EMPLOYEE WHERE Dnum = Dnumber AND Mgr_ssn = Ssn AND Plocation = 'Stafford'; OUTPUT:
  • 26. 26 Ambiguous Attribute Names, Aliasing, Renaming, and Tuple Variables In SQL, the same name can be used for two (or more) attributes as long as the attributes are in different tables. If this is the case, and a multitable query refers to two or more attributes with the same name, we must qualify the attribute name with the relation name to prevent ambiguity. This is done by prefixing the relation name to the attribute name and separating the two by a period
  • 27. 27 Query 8. For each employee, retrieve the employee’s first and last name and the first and last name of his or her immediate supervisor. Query SELECT E.Fname, E.Lname, S.Fname, S.Lname FROM EMPLOYEE E, EMPLOYEE S WHERE E.Super_ssn = S.Ssn; OUTPUT:
  • 28. 28
  • 29. 29 Unspecified WHERE Clause and Use of the Asterisk
  • 30. 30
  • 31. 31 Query Q1C retrieves all the attribute values of any EMPLOYEE who works in DEPARTMENT number 5 Query SELECT * FROM EMPLOYEE WHERE Dno = 5;
  • 32. 32 Query Q1D retrieves all the attributes of an EMPLOYEE and the attributes of the DEPARTMENT in which he or she works for every employee of the ‘Research’ department, Query SELECT * FROM EMPLOYEE, DEPARTMENT WHERE Dname = ‘Research’ AND Dno = Dnumber;
  • 34. 34 SQL has directly incorporated some of the set operations from mathematical set theory, which are also part of relational algebra. There are set union (UNION), set difference (EXCEPT), and set intersection (INTERSECT) operations. The relations resulting from these set operations are sets of tuples; that is, duplicate tuples are eliminated from the result. These set operations apply only to type compatible relations, so we must make sure that the two relations on which we apply the operation have the same attributes attributes appear in the same order in both relations. The next example illustrates the use of UNION. Tables as Sets in SQL
  • 35. 35
  • 36. 36
  • 37. 37 ( SELECT DISTINCT Pnumber FROM PROJECT, DEPARTMENT, EMPLOYEE WHERE Dnum = Dnumber AND Mgr_ssn = Ssn AND Lname = 'Smith' ) UNION ( SELECT DISTINCT Pnumber FROM PROJECT, WORKS_ON, EMPLOYEE WHERE Pnumber = Pno AND Essn = Ssn AND Lname = 'Smith' );
  • 38. 38
  • 39. 39 Find the fnames of employees who are working in ProductX or ProductY select e1.fname from employee e1,works_on w1,project p1 where e1.ssn=w1.essn and w1.pno=p1.pnumber and p1.pname='ProductX' union select e2.fname from employee e2,works_on w2,project p2 where e2.ssn=w2.essn and w2.pno=p2.pnumber and p2.pname='ProductY';
  • 40. 40 Find the fnames of employees who are working in ProductX or ProductY(UNION ALL) select e1.fname from employee e1,works_on w1,project p1 where e1.ssn=w1.essn and w1.pno=p1.pnumber and p1.pname='ProductX' Union ALL select e2.fname from employee e2,works_on w2,project p2 where e2.ssn=w2.essn and w2.pno=p2.pnumber and p2.pname='ProductY';
  • 41. 41 Find the fnames of employees who are working in both ProductX and ProductY select e1.fname from employee e1,works_on w1,project p1 where e1.ssn=w1.essn and w1.pno=p1.pnumber and p1.pname='ProductX' Intersect select e2.fname from employee e2,works_on w2,project p2 where e2.ssn=w2.essn and w2.pno=p2.pnumber and p2.pname='ProductY';
  • 42. 42 Find the fnames of employees who are working in ProductY but not in ProductX select e2.fname from employee e2,works_on w2,project p2 where e2.ssn=w2.essn and w2.pno=p2.pnumber and p2.pname='ProductY' minus select e1.fname from employee e1,works_on w1,project p1 where e1.ssn=w1.essn and w1.pno=p1.pnumber and p1.pname='ProductX';
  • 43. 43 Substring Pattern Matching and Arithmetic Operators The first feature allows comparison conditions on only parts of a character string, using the LIKE comparison operator. This can be used for string pattern matching  Partial strings are specified using two reserved characters  % replaces an arbitrary number of zero or more characters,  (_) replaces a single character. For example, consider the following query.
  • 44. 44 Query 12. Retrieve all employees whose address is in Houston. QUERY SELECT Fname, Lname FROM EMPLOYEE WHERE Address LIKE ‘%Houston%’; OUTPUT:
  • 45. 45 Query 12A. Find all employees who were born during the 1950s QUERY SELECT Fname, Lname FROM EMPLOYEE WHERE Bdate LIKE '_______5_'; OUTPUT:
  • 46. 46 SELECT E.Fname, E.Lname, 1.1 * E.Salary AS Increased_sal FROM EMPLOYEE E, WORKS_ON W, PROJECT P WHERE E.Ssn = W.Essn AND W.Pno = P.Pnumber AND P.Pname ='ProductX'; OUTPUT:
  • 47. 47
  • 48. 48 Ordering of Query Results Query 15. Retrieve a list of employees and the projects they are working on, ordered by department and, within each department, ordered alphabetically by last name, then first name.
  • 49. 49 INSERT, DELETE, and UPDATE Statements in SQL  In SQL, three commands can be used to modify the database: INSERT, DELETE, and UPDATE.  The INSERT Command  INSERT is used to add a single tuple (row) to a relation (table).  We must specify the relation name and a list of values for the tuple The values should be listed in the same order in which the corresponding attributes were specified in the CREATE TABLE command.  Example:-to add a new tuple to the EMPLOYEE relation
  • 50. 50 DBMS that fully implements SQL should support and enforce all the integrity constraints that can be specified in the DDL. For example, if we issue the command in U2 on the database shown in Figure 5.6, the DBMS should reject the operation because no DEPARTMENT tuple exists in the database with Dnumber = 2. Similarly, U2A would be rejected because no Ssn value is provided and it is the primary key, which cannot be NULL.
  • 51. 51 If you want to create a table D5EMPS with a similar structure to the EMPLOYEE table and load it with the rows of employees who work in department 5, we can write the following SQL. CREATE TABLE D5EMPS1 as select * from EMPLOYEE where e.dno=5;
  • 52. 52 The DELETE command removes tuples from a relation. It includes a WHERE clause, similar to that used in an SQL query, to select the tuples to be deleted. Tuples are explicitly deleted from only one table at a time.  A missing WHERE clause specifies that all tuples in the relation are to be deleted.  We must use the DROP TABLE command to remove the table definition The DELETE Command
  • 53. 53 The UPDATE Command  The UPDATE command is used to modify attribute values of one or more selected tuples. As in the DELETE command, a WHERE clause in the UPDATE command selects the tuples to be modified from a single relation.  An additional SET clause in the UPDATE command specifies the attributes to be modified and their new values. Actual table
  • 54. 54  Several tuples can be modified with a single UPDATE command. Example:- example is to give all employees in the ‘Research’ department a 10% raise in salary, as shown in U6
  • 55. 55 Joined Tables in SQL and Outer Joins  The concept of a joined table (or joined relation) was incorporated into SQL to permit users to specify a table resulting from a join operation in the FROM clause of a query.
  • 56. 56 If the user requires that all employees be included, a different type of join called OUTER JOIN must be used explicitly.
  • 57. 57 LEFT OUTER JOIN (every tuple in the left table must appear in the result; if it does not have a matching tuple, it is padded with NULL values for the attributes of the right table) RIGHT OUTER JOIN (every tuple in the right table must appear in the result; if it does not have a matching tuple, it is padded with NULL values for the attributes of the left table)  The keyword CROSS JOIN is used to specify the CARTESIAN PRODUCT operation.  It is also possible to nest join specifications; that is, one of the tables in a join may itself be a joined table. This allows the specification of the join of three or more tables as a single joined table, which is called a multiway join Joins Hyperlink to local document
  • 58. 58
  • 59. 59 Aggregate Functions in SQL  Aggregate functions are used to summarize information from multiple tuples into a single-tuple summary.  A number of built-in aggregate functions exist: COUNT, SUM, MAX, MIN, and AVG.  COUNT function returns the number of tuples or values as specified in a query.  These functions can be used in the SELECT clause or in a HAVING clause.
  • 60. 60 Query 19. Find the sum of the salaries of all employees, the maximum salary, the minimum salary, and the average salary. QUERY SELECT SUM (Salary), MAX (Salary), MIN (Salary), AVG (Salary) FROM EMPLOYEE; INPUT
  • 61. 61 Q19A: SELECT SUM (Salary) Total_Sal, MAX (Salary) Highest_Sal, MIN (Salary) Lowest_Sal, AVG (Salary) Average_Sal FROM EMPLOYEE;
  • 62. 62 Query 20. Find the sum of the salaries of all employees of the ‘Research’ department, as well as the maximum salary, the minimum salary, and the average salary in this department.
  • 63. 63 Queries 21 and 22. Retrieve the total number of employees in the company (Q21) and the number of employees in the ‘Research’ department (Q22).
  • 64. 64 Query 23. Count the number of distinct salary values in the database
  • 65. 65 Grouping: The GROUP BY and HAVING Clauses In many cases we want to apply the aggregate functions to subgroups of tuples in a relation, where the subgroups are based on some attribute values.  example, we may want to find the average salary of employees in each department or the number of employees who work on each project.  SQL has a GROUP BY clause for this purpose.  The GROUP BY clause specifies the grouping attributes, which should also appear in the SELECT clause, so that the value resulting from applying each aggregate function to a group of tuples appears along with the value of the grouping attribute(s).
  • 66. 66 Query 24. For each department, retrieve the department number, the number of employees in the department, and their average salary
  • 67. 67 Query 25. For each project, retrieve the project number, the project name, and the number of employees who work on that project.
  • 68. 68 Query 26. For each project on which more than two employees work, retrieve the project number, the project name, and the number of employees who work on the project.
  • 69. 69 Query 27. For each project, retrieve the project number, the project name, and the number of employees from department 5 who work on the project
  • 70. 70 Suppose that we want to count the total number of employees whose salaries exceed $40,000 in each department, but only for departments where more than five employees work. Hint:-Here, the condition (SALARY > 40000) applies only to the COUNT function in the SELECT clause. Suppose that we write the following incorrect query:
  • 71. 71 Specifying Constraints as Assertions and Actions as Triggers  Each assertion is given a constraint name and is specified via a condition similar to the WHERE clause of an SQL query. 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: 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.
  • 72. 72 A manager may want to be informed if an employee’s travel expenses exceed a certain limit by receiving a message whenever this occurs. The action that the DBMS must take in this case is to send an appropriate message to that user. The condition is thus used to monitor the database The CREATE TRIGGER statement is used to implement such actions in SQL.
  • 73. Trigger: A trigger is a stored procedure in database which automatically invokes whenever a special event in the database occurs. For example, a trigger can be invoked when a row is inserted into a specified table or when certain table columns are being updated. Syntax: create trigger [trigger_name] [before | after] {insert | update | delete} on [table_name] [for each row] [trigger_body] Introduction to Triggers in SQL 73
  • 74. create trigger [trigger_name]: Creates or replaces an existing trigger with the trigger_name. [before | after]: This specifies when the trigger will be fired. {insert | update | delete}: This specifies the DML operation. on [table_name]: This specifies the name of the table associated with the trigger. [for each row]: This specifies a row-level trigger, i.e., the trigger will be executed for each row being affected. [trigger_body]: This provides the operation to be performed as trigger is fired Each trigger is attached to a single, specified table in the database 74
  • 75. We have two types of triggers: 1.Row-level triggers—these are executed for each row 2.Statement-level triggers—at one time, triggers are executed. 75
  • 76. 76
  • 77. 77
  • 78. 78
  • 79. 79 Create trigger: The following trigger will display the salary difference between the old values and new values: SQL> 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; / Trigger created.
  • 80. 80 INSERT INTO customers VALUES (7,'Karthik',22,‘VRSEC',87000); When a record is created in CUSTOMERS table, above create trigger display_salary_changes will be fired and it will display the following result: Output:- SQL> INSERT INTO customers VALUES (7,'Karthik',22,‘VRSEC',87000); Old salary: New salary: 87000 Salary difference: 1 row created.
  • 81. 81 Views (Virtual Tables) in SQL  A view in SQL terminology is a single table that is derived from other tables.  These other tables can be base tables or previously defined views.  A view does not necessarily exist in physical form; it is considered to be a virtual table, in contrast to base tables, whose tuples are always physically stored in the database. Specification of Views in SQL.  In SQL, the command to specify a 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.
  • 82. 82 V1: CREATE VIEW WORKS_ON1 AS SELECT Fname, Lname, Pname, Hours FROM EMPLOYEE, PROJECT, WORKS_ON WHERE Ssn = Essn AND Pno = Pnumber;
  • 83. 83
  • 84. 84 V2 : 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; OUTPUT:
  • 85. 85 We can now specify SQL queries on a view—or virtual table—in the same way we specify queries involving base tables. Query: To retrieve the last name and first name of all employees who work on the ‘ProductX’ project, we can utilize the WORKS_ON1 view and specify the query as in QV1: QV1: SELECT Fname, Lname FROM WORKS_ON1 WHERE Pname = ‘ProductX’;
  • 86. 86 If we do not need a view anymore, we can use the DROP VIEW command to dispose of it. For example, to get rid of the view V1, we can use the SQL statement in V1A: DROP VIEW WORKS_ON1; Different strategies as to when a materialized view is updated are possible. The immediate update strategy updates a view as soon as the base tables are changed; lazy update strategy updates the view when needed by a view query;  periodic update strategy updates the view periodically (in the latter strategy, a view query may get a result that is not up-to-date).
  • 87. 87 However, issuing an INSERT, DELETE, or UPDATE command on a view table is in many cases not possible.  Views defined on multiple tables using joins are generally not updatable. Views defined using grouping and aggregate functions are not updatable. Views as Authorization Mechanisms CREATE VIEW DEPT5EMP AS SELECT * FROM EMPLOYEE WHERE Dno = 5; CREATE VIEW BASIC_EMP_DATA AS SELECT Fname, Lname, Address FROM EMPLOYEE;
  • 88. 88 Schema Change Statements in SQL The DROP Command  The DROP command can be used to drop named schema elements, such as tables, domains, types, or constraints. One can also drop a whole schema if it is no longer needed by using the DROP SCHEMA command.  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; otherwise, 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.
  • 89. 89 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 (see Figure 6.1), we can use the command ALTER TABLE COMPANY.EMPLOYEE ADD COLUMN Job VARCHAR(12);
  • 90. 90 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. example, the following command removes the attribute Address from the EMPLOYEE base table: ALTER TABLE COMPANY.EMPLOYEE DROP COLUMN Address CASCADE;
  • 91. 91 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: ALTER TABLE COMPANY.DEPARTMENT ALTER COLUMN Mgr_ssn DROP DEFAULT; ALTER TABLE COMPANY.DEPARTMENT ALTER COLUMN Mgr_ssn SET DEFAULT ‘333445555’; One can also change the constraints specified on a table by adding or dropping a named constraint. ALTER TABLE COMPANY.EMPLOYEE DROP CONSTRAINT EMPSUPERFK CASCADE;
  • 92. Functional Dependencies The single most important concept in relational schema design is a functional dependency. A Functional Dependency describes a relationship between attributes within a single relation An attribute is functionally dependent on another if we can use the value of one attribute to determine the value of another. Formally, functional dependency is defined as;
  • 93. Functional dependency – In a given relation R, X and Y are attributes. Attribute Y is functionally dependent on attribute X if each value of X determines exactly one value of Y. This is represented as X → Y. For example, consider the following relation Reports(Student#, Course#, CourseName, Iname, Room#, Marks, Grade) In this relation, {Student#, Course#} together can determine exactly one value of Marks. This can be symbolically represented as {Student#, Course#} → Marks This type of dependency is called as functional dependency. In the above example Marks is functionally dependent on {Student#, Course#}. Other functional dependencies in the above example are:
  • 94. Course# → CourseName Course# → Iname ( Assuming one course is taught by one and only one instructor) Iname → Room# (Assuming each instructor has his/her own room) Marks → Grade Course# → Room#
  • 103. Full Functional Dependency - In a given relation R, X and Y are attributes. Attribute Y is fully functionally dependent on attribute X only if it is not functionally dependent on sub-set of X where X is composite in nature. In the above example, Marks is fully functionally dependent on {Student#, Course#} and not on sub-set of {Student#, Course#}. This means Marks cannot be determined either by Student# or by Course#. It can be determined using Student# and Course# together. Hence, Marks is fully functionally dependent on {Student#, Course#}.
  • 104.
  • 105.
  • 106.
  • 107.
  • 108.
  • 109.
  • 110.
  • 111.
  • 112.
  • 113.
  • 114.
  • 115. For example, suppose there is a relation R (A, B, C, D) with functional dependency set (A->BC). The relational R is decomposed into R1(ABC) R2(AD) Solution: It id dependency preserving because FD A->BC is a part of relation R1(ABC).
  • 116.
  • 117.
  • 118.
  • 119.
  • 120.
  • 121.
  • 122.
  • 123.
  • 124.
  • 125.
  • 126.
  • 127.
  • 128.
  • 129.
  • 130.
  • 131. VRSEC-CSE-DBMS-III-B-VR_20 131 FOURTH NORMAL FORM-4NF A multivalued dependency X → Y specified on relation schema R, where X and Y are both subsets of R, specifies the following constraint on any relation state r of R: If two tuples t1 and t2 exist in r such that t1[X] = t2[X], then two tuples t3 and t4 should also exist in r with the following properties, where we use Z to denote (R − (X ∪ Y)): Definition: A Relation R is in 4NF if and only if the following conditions are satisfied (i) R is in already BCNF or 3NF (ii) R contains no MVDs
  • 151. VRSEC-CSE-DBMS-III-B-VR_20 151 Keeping both the relations separately will results a Good database design