0% found this document useful (0 votes)
12 views106 pages

DBMS U-2

Uploaded by

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

DBMS U-2

Uploaded by

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

DATABASE MANAGEMENT

SYSTEMS

UNIT-II
CH-1 Introduction to relational
model
 INTRODUCTION TO THE RELATIONAL MODEL

• The main construct for representing data in the


relational model is a relation.
• Relation: A relation consists of a relation schema and a
relation instance.
• Relation instance: The relation instance is a table, and
the relation schema describes the column heads for the
table.
• Relation schema: The schema specifies the relation's
name, the name of each field (or column, or attribute),
and the domain of each field.
• Domain: A domain is referred to in a relation schema
by the domain name and has a set of associated values.
sid name Login
• let R(fI:Dl, ... , fn:Dn) be a relation schema, and for each fi, 1<=
i<= n, let Domi be the set of values associated with the domain
named Di.
• An instance of R that satisfies the domain constraints in the
schema is a set of tuples with n fields:
{ (fI : d1,...fn: dn) |dl E Dom1, ... ,dn E Domn}
• (sid: 50000, name:Dave, login: dave@cs, age: 19, gpa:
3.3).
• The circular brackets ( ) identify the fields of a tuple. Using this
notation, the first Students tuple shown in Figure 3.1 is written as
(sid: 50000, name:Dave, login: dave@cs, age: 19, gpa: 3.3).
• The curly brackets {... } denote a set (of tuples, in this definition).
• The vertical bar | should be read 'such that, the symbol E should be
read 'in,' and the expression to the right of the vertical bar is a
condition that must be satisfied by the field values of each tuple in
the set.
• Therefore, an instance of R is defined as a set of tuples.
• Domain constraints are so fundamental in the relational model
that we henceforth consider only relation instances that satisfy
them; therefore, relation instance means relation instance that
satisfies the domain constraints in the relation schema.
• Degree: The degree, also called arity
(The number of arguments or operands taken by a function or
operator), of a relation is the number of fields.
• Cardinality : The cardinality of a relation instance is the
number of tuples in it. In Figure 3.1, the degree of the relation
(the number of columns) is five, and the cardinality of this
instance is six.
• Relational database : A relational database is a collection of
relations with distinct relation names.
• Relational database schema : The relational database schema is
the collection of schemas for the relations in the database.
Data Definition Language (DDL)
• Data Definition Language (DDL) statements are
used to define the database structure or schema.
• Data Definition Language understanding with
database schemas and describes how the data
should consist in the database. DDL is about
"metadata".
• The result of compilation of Data Definition
Language statements is a set of tables that is
stored in a special file called Data Dictionary or
Data Directory
• A Data Dictionary is a file that contains
metadata(data about data). This file is consulted
before actual data is read or modified in the
database.
DDL includes commands such as CREATE, ALTER
and DROP statements.

DDL Commands:
1. CREATE - to create objects in the database
2. ALTER - alters the structure of the database
3. DROP –drop command drops the complete table
from the database.
4. TRUNCATE - truncate Command deletes all the
rows from the existing table, leaving the row
with the column names.
5. COMMENT - add comments to the data
dictionary
6. RENAME - rename an object
DML Commands:

1.INSERT : It inserts data in a


database.
2.SELECT : It retrieves data from a
table.
3.UPDATE : It updates existing data
within a table.
4.DELETE : It deletes all records from
a table, the space for the records
remain.
 Creating and Modifying Relations Using SQL
-The SQL Language uses the word table to denote
relation.
-The subset of SQL that supports the creation , deletion
and modification of tables is called DDL.
-The CREATE TABLE statement is used to define a new
table.
-To create the Students relation, we can use the
following statement:
CREATE TABLE Students ( sid CHAR(20) ,
name CHAR(30) ,
Login CHAR(20) ,
Age INTEGER,
Gpa REAL);
• Tuples are inserted ,using the INSERT command.
• We can insert a single tuple into the Students table as follows:

INSERT
INTO Students (sid, name, login, age, gpa)
VALUES (53688, 'Smith', 'smith@ee', 18, 3.2);
Or
INSERT INTO table-name VALUES (“val1”, val2, val3,…,
“valK”);

We can delete tuples using the DELETE command.


We can delete all Students tuples with name equal to Smith using the
command:
DELETE
FROM Students S
WHERE S.name = 'Smith'
• We can modify the column values in an
existing row using the UPDATE command.
• For example, we can increment the age and
decrement the gpa of the student with sid
53688:
UPDATE Students S
SET S.age = S.age + 1, S.gpa = S.gpa -
1
WHERE S.sid = 53688
(or)
UPDATE Students S
SET S.gpa = S.gpa - 0.1
WHERE S.gpa >= 3.3
 INTEGRITY CONSTRAINTS OVER RELATIONS
• An integrity constraint (IC) is a condition specified on a
database schema and restricts the data that can be stored in an
instance of the database.
• If a database instance satisfies all the integrity constraints
specified on the database schema, it is a legal instance.
• A DBMS enforces integrity constraints, in that it permits only
legal instances to be stored in the database.
• Integrity constraints are specified and enforced at different
times:
1. When the DBA or end user defines a database schema, he or she
specifies the ICs that must hold on any instance of this database.
2. When a database application is run, the DBMS checks for
violations and disallows changes to the data that violate the
specified ICs.
WHAT ARE DBMS KEYS ? WHY WE NEED THEM ? WHAT ARE
DIFFERENT TYPES OF KEYS ?
Here, If I need to find out the email address of a student named
“Adam “ . It’s not possible because we have 2 Adams. OR If you
need to find out student of C.S branch, again there will be many
students of C.S branch
8 Secondary key
SUPER KEY:
Super Key is the superset of primary key. The
super key contains a set of attributes, including
the primary key, which can uniquely identify any
data row in the table.
We can choose any one of these as a candidate key
ALTERNATE KEY :

SECONDARY KEY –
Only one of the candidate keys is selected as the
primary key. The rest of them are known as
secondary keys
FOREIGN KEY:
This way while making a new student entry a wrong
branch name cannot be entered
If any single attribute of a table is not
capable of being the key i.e it cannot
identify a row uniquely, then we combine
two or more attributes to form a key. This
is known as a composite key
 Specifying candidate Key Constraints in SQL
• In SQL, we can declare that a subset of the columns of
a table constitute a key by using the UNIQUE
constraint.
• example table
CREATE TABLE Students ( sid CHAR(20) ,
name CHAR (30) ,
login CHAR(20) ,
age INTEGER,
gpa REAL,
Unique(sid),UNIQUE (name, age))
 Specifying Primary Key Constraints in SQL
• One of the candidate key which has no Null values is
selected as Primary Key.
• example table
CREATE TABLE Students ( sid CHAR(20) ,
name CHAR (30) ,
login CHAR(20) ,
age INTEGER,
gpa REAL,
constraint studentkeyprimary key (sid));

• we can name a constraint by preceding it with CONSTRAINT


constraint-name. If the constraint is violated, the constraint name is
returned and can be used to identify the error.
 Foreign Key Constraints
• Sometimes the information stored in a relation is linked
to the information stored in another relation.
• If one of the relations is modified, the other must be
checked, and perhaps modified, to keep the data
consistent.
• An IC involving both relations must be specified if a
DBMS is to make such checks.
• The most common IC involving two relations is a
foreign key constraint.
• Suppose that, in addition to Students, we have a second
relation:
Enrolled(studid: string, cid: string, grade: string)
• To ensure that only bonafide students can enroll
in courses, any value that appears in the studid
field of an instance of the Enrolled relation
should also appear in the sid field of some tuple
in the Students relation.
• The st'udid field of Enrolled is called a foreign
key and refers to Students.
• The foreign key in the referencing relation must
match the primary key of the referenced relation
that is it must have the same compatible data
types, although the column names can be
different.
 Specifying Foreign Key Constraints in SQL

Let us define Enrolled(studid: string, cid: string,


grade: string):

CREATE TABLE Enrolled ( studid CHAR(20) ,


cid CHAR(20),
grade CHAR(10),
PRIMARY KEY (studid),
FOREIGN KEY (studid)
REFERENCES Students(sid));
 General Constraints
• Domain, primary key, and foreign key constraints are considered to
be a fundamental part of the relational data model and are given
special attention in most commercial systems.
• Sometimes, however, it is necessary to specify more general
constraints.
• For example, we may require that student ages be within a certain
range of values; given such an IC specification, the DBMS rejects
inserts and updates that violate the constraint.
• This is very useful in preventing data entry errors.
• Current relational database systems support such general constraints
in the form of table constraints and assertions.
• Table constraints are associated with a single table and checked
whenever that table is modified.
• In contrast, assertions involve several tables and are checked
whenever any of these tables is modified.
SQL Constraints
• SQL constraints are used to specify rules for
the data in a table.
• Constraints are used to limit the type of data
that can go into a table. This ensures the
accuracy and reliability of the data in the table.
If there is any violation between the constraint
and the data action, the action is aborted.
• Constraints can be column level or table level.
Column level constraints apply to a column,
and table level constraints apply to the whole
table.
The following constraints are commonly used in SQL:
•NOT NULL - Ensures that a column cannot have a NULL
value
•UNIQUE - Ensures that all values in a column are different
•PRIMARY KEY - A combination of a NOT NULL and UNIQUE.
Uniquely identifies each row in a table
•FOREIGN KEY - Prevents actions that would destroy links
between tables
•CHECK - Ensures that the values in a column satisfies a
specific condition
•DEFAULT - Sets a default value for a column if no value is
specified
•CREATE INDEX - Used to create and retrieve data from the
database very quickly

•Example Query :
• create table employee(sno int(3), empno varchar(5)
primary key, empname char(10) unique, branch char(5),
salary INT(10) not null, designation varchar(20), place
char(10) default ‘Hyderabad’, age varchar(2) check (age
>=18));
 ENFORCING INTEGRITY CONSTRAINTS
• ICs are specified when a relation is created and
enforced when a relation is modified.
• The impact of domain, PRIMARY KEY, and
UNIQUE constraints is straightforward:
• If an insert, delete, or update command causes a
violation, it is rejected.
• Every potential IC violation is generally
checked at the end of each SQL statement
execution, although it can be deferred until the
end of the transaction executing the statement.
• PRIMARY KEY CONSTRAINTS:
• The following insertion violates the primary key constraint because
there is already a tuple with the sid 53688, and it will be rejected by
the DBMS:
INSERT
INTO Students (sid, name, login, age, gpa)
VALUES (53688, 'Mike', 'mike@ee', 17,3.4);
• The following insertion violates the constraint that the primary key
cannot contain null:
INSERT
INTO Students (sid, name, login, age, gpa)
VALUES (null, 'Mike', 'mike@ee', 17,3.4);
• UPDATE Students S
SET S.sid = 50000

WHERE S.sid = 53688


• This update violates the primary key constraint because there is
already a tuple with sid 50000.
Integrity Rule 1 (Entity Integrity Rule or
Constraint)
➢ The Integrity Rule 1 is also called Entity Integrity
Rule or Constraint.
➢ This rule states that no attribute of primary key will
contain a null value.
➢ If a relation have a null value in the primary key
attribute, then uniqueness property of the primary
key cannot be maintained.
➢ Consider the example below-
DOMAIN COMSTRAINTS:
• Of course, a similar problem arises whenever we try to insert a tuple with a
value in a field that is not in the domain associated with that field, that is,
whenever we violate a domain constraint.
• Deletion does not cause a violation of domain, primary key or unique
constraints.
• However, an update can cause violations, similar to an insertion:
• Domain Constraints specifies that what set of values an attribute can take.
• Value of each attribute X must be an atomic value from the domain of X.
• The data type associated with domains include integer, character, string,
date, time, currency etc.
• An attribute value must be available in the corresponding domain.
• Consider the example below –
Difference between Primary
Key and Unique Key
• Examples of Candidate Key/Primary
Key Constraint Checking
CANDIDATE KEY CONSTRAINT:

create table student(sid int(4),sname varchar(10), marks


int(4), unique(sid));
• Query OK, 0 rows affected (0.03 sec)

• insert into student values(1,'abc',60);


Query OK, 1 row affected (0.02 sec)

• insert into student values(2,'abc',60);


Query OK, 1 row affected (0.02 sec)

insert into student values(1,'pqr',80);


• ERROR 1062 (23000): Duplicate entry '1' for key 'sid'
create table student1(sid int(4),sname varchar(10), marks int(4),
unique(sid,sname));
Query OK, 0 rows affected (0.06 sec)

mysql> insert into student1 values(1,'pqr',80);


• Query OK, 1 row affected (0.01 sec)

• mysql> insert into student1 values(1,'pqr',80);


• ERROR 1062 (23000): Duplicate entry '1-pqr' for key 'sid’

• mysql> insert into student1 values(1,'lmn',80);


• Query OK, 1 row affected (0.02 sec)

• mysql> insert into student1 values(2,'pqr',80);


• Query OK, 1 row affected (0.03 sec)
• mysql> create table student3(sid int(4),sname varchar(10),
smarks int(4), unique(sid),unique(sname,smarks));
Query OK, 0 rows affected (0.03 sec)
• mysql> insert into student3 values(1,'pqr',80);
Query OK, 1 row affected (0.01 sec)
• mysql> insert into student3 values(1,'lmn',80);
ERROR 1062 (23000): Duplicate entry '1' for key 'sid’
• mysql> insert into student3 values(2,'xyz',90);
Query OK, 1 row affected (0.03 sec)
• mysql> insert into student3 values(3,'xyz',90);
ERROR 1062 (23000): Duplicate entry 'xyz-90' for key 'sname’
• mysql> insert into student3 values(3,'xyz',100);
Query OK, 1 row affected (0.05 sec)
• mysql> insert into student3 values(4,’aaa’,80);
Query OK, 1 row affected (0.02 sec)
PRIMARY KEY CONSTRAINT:

• mysql> create table student5(sid int(10), name varchar(10),


age int(3), primary key(sid));
Query OK, 0 rows affected (0.03 sec)
• mysql> insert into student5 values(1,'abc',23);
Query OK, 1 row affected (0.03 sec)
• mysql> insert into student5 values(1,'pqr',23);
ERROR 1062 (23000): Duplicate entry '1' for key 'PRIMARY’
• mysql> insert into student5 values(2,'abc',23);
Query OK, 1 row affected (0.03 sec)
• mysql> insert into student5 values(null,'xyz',25);
ERROR 1048 (23000): Column 'sid' cannot be null
• FOREIGN KEY CONSTRAINTS
• It is an attribute or set of attributes that references to
primary key of same table or other table(relation)
• It maintains referential Integrity

Primary Key Foreign Key

Roll_no Name Address Course_ C_name Roll_No


ID
1 A HYD C1 DBMS 1
2 B Delhi
C2 OS 2
3 A Chennai

Course relation
Student Relation
referencing
referenced table
table
• What is Integrity ?
• One value every where throughout the database.
• As the students get added in student table course table will
also be updated according to roll no.
• Course table cannot have a roll no “5” as the roll no “5” is
not present in students table. Here the insertion of “5” in
course table will be violated.
• First roll no “5” should be in students table inorder to be in
course table. As Course table is taking a reference from
student table’s primary key .
• Course table is called as “referencing table” and student
table is called as “referenced table”
• To create a foreign key :
• Create table course(course_id varchar(10), c_name
varchar(20), roll_no int(10) references student(roll_no));
Constraints for referenced table.
• If anything is inserted in referenced table NO violation.

4 D Goa

• If anything is deleted in referenced table then there occurs a


Violation
• Ex: If roll_no 1 is to be deleted from student relation , but roll
no 1 is studying a course in course table. This loses Integrity.
So, Deletion may cause violation.
• Solution : Manually delete the roll_no 1 from student table and
course table too. But, if this has to be done automatically ?
REFERENCED RELATION :
SQL allows to choose any of the 4 options:

1) ON DELETE CASCADE:
• The cascade keyword says that if a student row was
deleted all the course rows that refer to it are also
deleted.
• If roll_no 1 is deleted from student relation,
automatically row holding roll_no 1 in course table will
also be deleted.
• To create such a foreign key :
• Create table course(course_id varchar(10), c_name
varchar(20), roll_no int(10) references student(roll_no)
on delete cascade);
2) ON DELETE SET NULL:
When primary key is deleted each of the referenced foreign key
is set to NULL.
• To create such a foreign key :
• Create table course(course_id varchar(10), c_name varchar(20),
roll_no int(10) references student(roll_no) on delete set NULL);

NU
LL

• But at times a scenario can arise, the referencing table’s foreign


key can also be the primary key of that table. In that case, this
solution cannot be adopted as primary key CANNOT be NULL.
3) ON DELETE NO ACTION:
This states that when the primary key is deleted from
the referenced relation NO ACTION is being
performed. When the deletion is done this gives an
error and the deletion is strictly violated here. No
change is done in either of the tables.
4) ON UPDATE CASCADE:
If any updation is to be done in the referenced
relation , then that change should be reflected in
referencing relation too. If the roll no in students
table is updated then the course table roll no should
also be updated.
• REFERENCING TABLE :
• INSERT : Inserting any data in referencing table
which is not in referenced table may cause violation
• DELETE: Deleting any data in referencing table will
NOT cause violation
• UPDATE : Updating foreign key data in referencing
table which is not in referenced table may cause
violation

• THIS IS HOW REFERENTIAL INTEGRITY IS


MAINTAINED IN FOREIGN KEY
Referential integrity enforcement steps taken by the
DBMS
• Deletions of Enrolled tuples do not violate referential
integrity, but insertions of Enrolled tuples could.
• The following insertion is illegal because there is no
Students tuple with sid 51111:
INSERT INTO Enrolled (cid, grade, studid) VALUES ('Hindi101', 'B’,
51111)
• On the other hand, insertions of Students tuples do not
violate referential integrity, and deletions of Students
tuples could cause violations.
• Further, updates on either Enrolled or Students that
change the studid (respectively, sid) value could
potentially violate referential integrity.
SQL provides several alternative ways to handle foreign key
violations. We must consider three basic questions:
1. What should we do if an Enrolled row is inserted, with a
studid column
value that does not appear in any row of the Students table?
In this case, the INSERT command is simply rejected.

2. What should we do if a Students row is deleted?


The options are:
• Delete all Enrolled rows that refer to the deleted Students
row.
• Disallow the deletion of the Students row if an Enrolled
row refers to it.
Integrity Rule 2(Referential Integrity
Rule / Constraint)
➢ The integrity Rule 2 is also called the Referential Integrity
Constraints.
➢ This rule states that if a foreign key in Table 1 refers to the
Primary Key of Table 2, then every value of the Foreign Key in
Table 1 must be null or be available in Table 2. For example
Transactions and Constraints

• A program that runs against a database is


called a transaction, and it can contain
several statements (queries, inserts, updates,
etc.) that access the database.
• If (the execution of) a statement in a
transaction violates an integrity constraint,
should the DBMS detect this right away or
should all constraints be checked together
just before the transaction completes?
• By default, a constraint is checked at the end
of every SQL statement that could lead to a
violation, and if there is a violation, the
statement is rejected.
• Sometimes this approach is too inflexible.
Consider the following variants of the
Students and Courses relations; every student
is required to have an honors course, and every
course is required to have a grader, who is
some student.
CREATE TABLE Students ( sid CHAR(20) ,
name CHAR(30),
login CHAR (20) ,
age INTEGER,
honors CHAR(10) NOT NULL,
gpa REAL)
PRIMARY KEY (sid),
FOREIGN KEY (honors) REFERENCES
Courses (cid))
CREATE TABLE Courses (cid CHAR(10),
cname CHAR ( 10) ,
credits INTEGER,
grader CHAR(20) NOT NULL,
PRIMARY KEY (cid)
FOREIGN KEY (grader) REFERENCES
Students (sid))
• Whenever a Students tuple is inserted, a check is made
to see if the honors course is in the Courses relation, and
whenever a Courses tuple is inserted, a check is made to
see that the grader is in the Students relation.
• How we are going to insert the very first course or
student tuple? One cannot be inserted without the other.
• The only way to accomplish this insertion is to defer the
constraint checking that would normally be carried out at
the end of an INSERT statement.
• SQL allows a constraint to be in DEFERRED or
IMMEDIATE mode.
• SET CONSTRAINT ConstraintFoo DEFERRED
• A constraint in deferred mode is checked at commit time.
• In our example, the foreign key constraints on
honors and graders can both be declared to be in
deferred mode. We can then insert? honors with a
nonexistent grader (temporarily making the
database inconsistent), insert the honors (restoring
consistency), then commit and check that both
constraints are satisfied.
(N)-tuple a set of (n) attribute-value pairs representing a single
instance of a relation’s mapping between its domains.
Degree the number of attributes a relation has.
Cardinality a number of tuples a relation has.
Roles several attributes can have the same domain; the attributes
indicate different roles in the relation.
Key (SuperKey) a set of attributes whose values together uniquely
identify every tuple in a relation. Let t1 and t2 be two tuples on
relation r of relation schema R, and sk be a set of attributes whose
values are the key for the relation schema R, then t1[sk]  t2[sk].
(Candidate) Key a (super)key that is minimal, i.e. has no proper
subsets that still uniquely identify every tuple in a relation. There can
be several for one relation.
Primary Key a candidate key chosen to be the main key for the
relation. There is only one for each relation.
Foreign Key a candidate key of relation A situated in relation B.
Database a set of relations.
 QUERYING RELATIONAL DATA
• A relational database query (query, for short) is
a question about the data, and the answer
consists of a new relation containing the result.
• A query language is a specialized language for
writing queries.
• SQL is the most popular commercial query
language for a relational DBMS.
SELECT *
FROM Students S
WHERE S.age < 18
SELECT S.name, S.login
FROM Students S
WHERE S.age < 18
LOGICAL DATABASE DESIGN: ER TO
RELATIONAL
• The ER model is convenient for representing an initial,
high-level database design.
 Entity Sets to Tables
CREATE TABLE
Employees
( ssn CHAR(11),
name CHAR(30),
lot INTEGER,
PRIMARY KEY
(ssn));
 Relationship Sets (without Constraints) to
Tables
• A relationship set, like an entity set, is mapped to
a relation in the relational model.
• To represent a relationship, we must be able to
identify each participating entity and give values
to the descriptive attributes of the relationship.
• Thus, the attributes of the relation include:
 The primary key attributes of each participating
entity set, as foreign key fields.
 The descriptive attributes of the relationship set.
CREATE TABLE Works_In2
( ssn CHAR(11),
did INTEGER,
address CHAR(20) ,
since DATE,
PRIMARY KEY (ssn, did, address),
FOREIGN KEY (ssn) REFERENCES Employees
FOREIGN KEY (address) REFERENCES Locations,
FOREIGN KEY (did) REFERENCES Departments)
 Translating Relationship Sets with Key Constraints
• If a relationship set involves n entity sets and some of them
are linked via arrows in the ER diagram, the key for anyone
of these m entity sets constitutes a key for the relation to
which the relationship set is mapped.
• Hence we have m candidate keys, and one of these should
be designated as the primary key.

Key Constraint on Manages


CREATE TABLE Manages (ssn CHAR (11) ,
did INTEGER,
since DATE,
PRIMARY KEY (did),
FOREIGN KEY (ssn) REFERENCES
Employees,
FOREIGN KEY (did) REFERENCES
Departments)
second approach to translating a relationship set with key
constraints is
often superior because it avoids creating a distinct table for the
relationship set. The idea is to include the information about the
relationship set in the table corresponding to the entity set with the
key, taking advantage of the key constraint. In the Manages
example, because a department has at most one manager, we can
add the key fields of the Employees tuple denoting the manager and
the since attribute to the Departments tuple.
CREATE TABLE Departments ( did INTEGER,
dname CHAR(20),
budget REAL,
ssn CHAR (11) ,
since DATE,
PRIMARY KEY (did),
FOREIGN KEY (ssn) REFERENCES Employees)
This approach eliminates the need for a separate
Manages relation, and queries asking for a
department's manager can be answered without
combining information from two relations. The only
drawback to this approach is that space could be
wasted if several departments have no managers. In
this case the added fields would have to be filled with
null values. The first translation (using a separate table
for Manages) avoids this inefficiency, but some
important queries require us to combine information
from two relations, which can be a slow operation.
Note that ssn can take on null values.
 Translating Relationship Sets with Participation
Constraints
• Every department is required to have a manager, due to the
participation constraint, and at most one manager, due to
the key constraint.
• The NO ACTION specification, which is the default
and need not be explicitly specified, ensures that an
Employees tuple cannot be deleted while it is
pointed to by a Dept-Mgr tuple. If we wish to delete
such an Employees tuple, we must first change the
DeptMgr tuple to have a new employee as
manager.
 Translating Weak Entity Sets
• A weak entity set always participates in a one-to-
many binary relationship and has a key constraint
and total participation.
CREATE TABLE Dep_Policy (pname CHAR(20) ,
age INTEGER,
cost REAL,
ssn CHAR (11) ,
PRIMARY KEY (pname, ssn),
FOREIGN KEY (ssn) REFERENCES Employees
ON DELETE CASCADE )

Observe that the primary key is (pname, ssn) , since Dependents is a weak
entity. We have to ensure that every Dependents entity is associated
with an Employees entity (the owner), as per the total participation
constraint
on Dependents. That is, ssn cannot be null. This is ensured because SSN,
is
part of the primary key. The CASCADE option ensures that information
about
an employee's policy and dependents is deleted if the corresponding
Employees
tuple is deleted.
 Translating Class Hierarchies
1. We can map each of the entity sets Employees, Hourly_Emps, and ContractEmps
to a distinct relation.
The Employees relation is created as Hourlyemps here;
ContractEmps is handled similarly.
The relation for Hourly_Emps includes the hourly_wages
and hours_worked attributes of Hourly_Emps. It also contains the key attributes
of the superclass (ssn, in this example), which serve as the primary
key for Hourly_Emps, as well as a foreign key referencing the superclass
(Employees). For each Hourly_Emps entity, the value of the name and
lot attributes are stored in the corresponding row of the superclass (Employees).
Note that if the superclass tuple is deleted, the delete must be
cascaded to HourlyEmps.
2. Alternatively, we can create just two relations, corresponding to Hourly_Emps
and ContractEmps. The relation for Hourlyemps includes all the attributes
of Hourly_Emps as well as all the attributes of Employees (i.e.,
ssn, name, lot, hOurly_ wages, hours_worked.
 Translating ER Diagrams with Aggregation

monito
rs
• The Employees, Projects, and Departments entity
sets and the Sponsors relationship set are mapped
as described in previous sections. For the Monitors
relationship set, we create a relation with the
following attributes: the key attributes of
Employees (ssn), the key attributes of Sponsors
(did, pid), and the descriptive attributes of Monitors
until.
 ER to Relational: Additional Examples
CREATE TABLE Policies
( policyid INTEGER,
cost REAL,
ssn CHAR (11) NOT NULL,
PRIMARY KEY (policyid),
FOREIGN KEY (ssn) REFERENCES Employees
ON DELETE CASCADE )
CREATE TABLE Dependents (pname CHAR(20) ,
ssn CHAR (11) ,
age INTEGER,
policyid INTEGER NOT NULL,
PRIMARY KEY (pname, policyid, ssn),
FOREIGN KEY (policyid, ssn) REFERENCES Policies
ON DELETE CASCADE )
• We can use the key constraints to combine
Purchaser information with Policies and Beneficiary
information with Dependents, and translate it into
the relational model.
• Notice how the deletion of an employee leads to
the deletion of all policies owned by the employee
and all dependents who are beneficiaries of those
policies.
Introduction To Views In
Sql:
• Views are derived or virtual tables, they derive their data
from the original relation.
• A view also contains rows and columns and to create the
view, we can select the fields from one or more tables
present in the database.
• In view rows are not explicitly stored in the database but
are computed as needed from a view definition.
• A view can either have specific rows based on certain
condition or all the rows of a table.
• Views allows the user to see only the part of data but not all
data.
• Views are dynamic in nature i.e. the changes made to the
views are reflected back to the original table and vice versa.
Creation of Views
Syntax:
CREATE VIEW View-name (field1,field2….fieldn)
AS SELECT(attribute1,attribute2….attributen)
FROM table1,table2…tablen
WHERE <condition>;
Example
Consider the CUSTOMERS table having the following records −

SQL > CREATE VIEW CUSTOMERS_VIEW AS


SELECT name, age
FROM CUSTOMERS;
SQL > SELECT * FROM CUSTOMERS_VIEW;
The WITH CHECK OPTION
The WITH CHECK OPTION is a CREATE VIEW statement option.
The purpose of the WITH CHECK OPTION is to ensure that all
UPDATE and INSERTs satisfy the condition(s) in the view definition.
If they do not satisfy the condition(s), the UPDATE or INSERT returns an
error.
The following code block has an example of creating same view
CUSTOMERS_VIEW with the WITH CHECK OPTION.
CREATE VIEW CUSTOMERS_VIEW AS
SELECT name, age
FROM CUSTOMERS
WHERE age IS NOT NULL
WITH CHECK OPTION;
The WITH CHECK OPTION in this case should deny the entry of any
NULL values in the view's AGE column, because the view is defined by
data that does not have a NULL value in the AGE column.
Updating a View
A view can be updated under certain conditions which are given below −
• The SELECT clause may not contain the keyword DISTINCT.
• The SELECT clause may not contain set functions.
• The SELECT clause may not contain set operators.
• The SELECT clause may not contain an ORDER BY clause.
• The FROM clause may not contain multiple tables.
• The WHERE clause may not contain subqueries.
• The query may not contain GROUP BY or HAVING.
• Calculated columns may not be updated.
• All NOT NULL columns from the base table must be included in the view in
order for the INSERT query to function.
So, if a view satisfies all the above-mentioned rules then you can update that view.
The following code block has an example to update the age of Ramesh.
SQL > UPDATE CUSTOMERS_VIEW
SET AGE = 35
WHERE name = 'Ramesh';
This would ultimately update the base table CUSTOMERS and the same
would reflect in the view itself. Now, try to query the base table and the
SELECT statement would produce the following result.
Inserting Rows into a View
Rows of data can be inserted into a view. The same rules that apply to the UPDATE
command also apply to the INSERT command.
Here, we cannot insert rows in the CUSTOMERS_VIEW because we have not
included all the NOT NULL columns in this view, otherwise you can insert rows in a
view in a similar way as you insert them in a table.
Deleting Rows into a View
Rows of data can be deleted from a view.
The same rules that apply to the UPDATE
and INSERT commands apply to the DELETE command.
Following is an example to delete a record having AGE = 22.
SQL > DELETE FROM CUSTOMERS_VIEW
WHERE age = 22;
This would ultimately delete a row from the base table
CUSTOMERS and the same would reflect in the view itself.
Now, try to query the base table and the SELECT statement
would produce the following result.
Student Marks
Creating view from single table
create view details as
select name, address from student
where S_ID<5;
-Just like table query we can query the view to display the
data stored in the views.
Select * from details;

CREATE
VIEW
• CREATE VIEW StudentNames AS
SELECT S_ID, NAME FROM Student
ORDER BY NAME;

• SELECT * FROM StudentNames;


Creating view from
multiple tables
• Create view marksview as
• select student.name, student.address, marks.marks
from student, marks where student.name=marks. name
• SELECT * FROM marksView;
student marks
marksview
 Views, Data Independence, Security
• The physical schema for a relational database describes how the
relations in the conceptual schema are stored, in terms of the file
organizations and indexes used.
• The conceptual schema is the collection of schemas of the relations
stored in the database.
• Additional relations in the external schema can be defined using the
view mechanism.
• The view mechanism thus provides the support for logical data
independence in the relational model.
• That is, it can be used to define relations in the external schema
that mask changes in the conceptual schema of the database from
applications.
• For example, if the schema of a stored relation is changed, we can
define a view with the old schema and applications that expect to
see the old schema can now use this view.
• Views are also valuable in the context of security: We
can define views that give a group of users access to
just the information they are allowed to see.
• For example, we can define a view that allows
students to see the other students names, age but not
gpa, & allows all students to access this VIEW but not
the underlying students table.
UPDATING VIEWS
• There are certain conditions needed to be satisfied to
update a view.
• If any one of these conditions is not met, then we will
not be allowed to update the view.
The SELECT statement which is used to create the
view should not have the DISTINCT keyword.
The View should have all NOT NULL values.
The view should not be created using nested queries
or complex queries.
All NOT NULL columns from the base table must be
included in the view in order for the INSERT query to
function.
mysql> select * from faculty;
+------+-------+--------+
| fid | fname | salary |
+------+-------+--------+
| 1 | abc | 20000 |
| 2 | lmn | 25000 |
| 3 | xyz | 50000 |
| 4 | fgh | 40000 |
| 5 | aaa | 45000 |
+------+-------+--------+
5 rows in set (0.00 sec)

mysql> create view f1 as select fid,fname from faculty order by


fname;
Query OK, 0 rows affected (0.02 sec)
mysql> select * from mysql> insert into f1 values(6,'rrr‘);
f1; Query OK, 1 row affected (0.00 sec)

+------+-------+
mysql> select * from faculty;
| fid | fname | +------+-------+
+------+-------+ | fid | fname |
| 5 | aaa | +------+-------+
| 1 | abc |
| 1 | abc | | 2 | lmn |
| 4 | fgh | | 3 | xyz |
| 2 | lmn | | 4 | fgh |
| 5 | aaa |
| 3 | xyz |
| 6 | rrr |
+------+-------+ +------+-------+
5 rows in set (0.02 sec) 6 rows in set (0.00 sec)
mysql> delete from f1 where fid=6;
Query OK, 1 row affected (0.00 sec)

mysql> select * from faculty;


+------+-------+--------+
| fid | fname | salary |
+------+-------+--------+
| 1 | abc | 20000 |
| 2 | lmn | 25000 |
| 3 | xyz | 50000 |
| 4 | fgh | 40000 |
| 5 | aaa | 4500 |
+------+-------+--------+
5 rows in set (0.00 sec)
mysql> update f1 set fname='bbb' where fid=5;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0

mysql> select * from faculty;


+------+-------+--------+
| fid | fname | salary |
+------+-------+--------+
| 1 | abc | 20000 |
| 2 | lmn | 25000 |
| 3 | xyz | 50000 |
| 4 | fgh | 40000 |
| 5 | bbb | 45000 |
+------+-------+--------+
5 rows in set (0.00 sec)

mysql>
 DESTROYING/ALTERING TABLES AND
VIEWS
• If we decide that we no longer need a base table and want
to destroy it (i.e., delete all the rows and remove the table
definition information), we can use the DROP TABLE
command.
• For example, DROP TABLE Faculty RESTRICT destroys
the Faculty table unless some view or integrity constraint
refers to Faculty; if so, the command fails.
• If the keyword RESTRICT is replaced by CASCADE,
Faculty is dropped and any referencing views or integrity
constraints
• ALTER TABLE modifies the structure of an existing
table. To add a column called maiden-name to
Students, for example, we would use the following
command.

ALTER TABLE Students


ADD COLUMN maiden-name CHAR(10)

Dropping Views
Obviously, where you have a view, you need a way to
drop the view if it is no longer needed.
The syntax is very simple and is given below −
DROP VIEW view_name;

You might also like