Dbms Unit-II Notes
Dbms Unit-II Notes
Introduction to the Relational Model: Integrity constraint over relations, enforcing integrity
constraints, querying relational data, logical data base design, introduction to views,
destroying/altering tables and views.
Relational Algebra, Tuple relational Calculus, Domain relational calculus
Relational Model:
The Relational Model was developed by E. F. Codd for IBM in 1970 to model data in the form
of relations or tables
Relational Model represents how data is stored in relational databases. A relational database
stores data in the form of Relations (Tables).
After designing the conceptual model of database using ER we need to convert the conceptual
model in the relational model which can be implemented using any RDBMS languages.
RDBMS Languages like SQL Server, My SQL, and Oracle etc.
RDBMS stands for Relational Database Management System. RDBMS is the basis for SQL, and
for all modern database systems like My SQL, SQL Server, IBM DB2, and Microsoft Access. It
is based on relational model.
Ex: student relation consists of attributes (sid, name, age, phone)
A relation model can be represented as a relation or table, each table consists of rows and
columns.
Attribute: column of a relation is called as attribute or field.
Ex: S_id, name, age, phone.
Tuple: Each row of a table is called as record or tuple.
Domain: Each attribute has domain, it specifies type and range of values allowed to store in the
attribute
Ex: Student (S-Id numeric(10), name char(10), age number(2), phone. No number(10))
The main construct for representing data in relational model is relation or table. A relation
consists of relation schema and relation instance. Relation instance is a table, that is set of tuples
or records, and relation schema describes the attribute or column name and domain of a relation.
Relation Schema: It specifies the relation’s name, the name of each fteld (or column, or
attribute), and the domain of each field. A domain is referred to in a relation schema by the
domain name and has a set of associated values.
This says, for instance, that the field named sid has a domain named string. The set of values
associated with domain string is the set of all character strings.
Relation instance: Instance of a relation is a set of tuples, also called records, in which each
tuple has the same number of fields as the relation schema. A relation instance can be thought of
as a table in which each tuple is a row, and all rows have the same number of fields.
Ex: an instance of a student relation.
Sid Name Age Gpa
1201 Suresh 20 3.7
1202 Ramesh 21 3.6
1203 Maesh 19 3.6
1204 Naresh 20 3.8
1205 Haresh 21 3.7
The above relation contains four attributes sid, name, age,gpa and five tuples or records or rows.
Degree of a relation: number of attributes of a relation is called degree of a relation. Degree of
the above student relation is 4.
Cardinality of a relation: number of tuples or records or rows of a relation is called cardinality
of relation, the above student relation is 5.
Column: the set of values of an attribute.
Null Value: Un Known or un available value is called null value.
Key attribute: is an attribute which is used for unique identification of each row of a table.
Properties of a Relation:
1. The relation has name that should be distinct from all names in the relation schema.
2. Each cell of relation should contain only one value.
3. Each attribute of a relation should be distinct.
4. Each tuple of relation should be distinct.
5. The order of attribute has no significance.
SQL: SQL (structured query language) is the most widely used language for creating,
manipulating the relation in relational database. It was developed by ANSI in 1986.
SQL uses these database languages read, store and update the data in the database.
ALTER The ALTER TABLE statement is used to add, delete, or modify columns, to add
and drop various constraints on in an existing table
SQL statement to change the data type of the column named "DateOfBirth" in the
"Persons" table is
SQL statement:
TRUNCATE: It is used to delete all the rows from the table and free the space
containing the table.
Syntax:
TRUNCATE TABLE table_name;
Example:
TRUNCATE TABLE EMPLOYEE;
INSERT: The INSERT statement is a SQL query. It is used to insert data into the row of
a table.
Syntax:
INSERT INTO TABLE_NAME
(col1, col2, col3,.... col N)
VALUES (value1, value2, value3, .... valueN);
Or
INSERT INTO TABLE_NAME
VALUES (value1, value2, value3, .... valueN);
For example:
INSERT INTO javatpoint (Author, Subject) VALUES ("Sonoo", "DBMS");
UPDATE: This command is used to update or modify the value of a column in the table.
Syntax:
UPDATE table_name SET [column_name1= value1,...column_nameN = valueN] [WHE
RE CONDITION]
For example:
UPDATE students
SET User_Name = 'Sonoo'
WHERE Student_Id = '3' ;
Select: The SQL SELECT command is used to fetch data from the MySQL database.
Syntax
SELECT field1, field2,...fieldN
FROM table_name1, table_name2...
[WHERE Clause]
[OFFSET M ][LIMIT N]
Ex:
SELECT * from tutorials_tbl
+-------------+----------------+-----------------+-----------------+
| tutorial_id | tutorial_title | tutorial_author | submission_date |
+-------------+----------------+-----------------+-----------------+
| 1 | Learn PHP | John Poul | 2007-05-21 |
| 2 | Learn MySQL | Abdul S | 2007-05-21 |
| 3 | JAVA Tutorial | Sanjay | 2007-05-21 |
+-------------+----------------+-----------------+-----------------+
Integrity constrains over relations:
An integrity constraint is a condition specified on a database schema and restricts the data that
can be stored in an instance of database.
If a database instance satisfies all the integrity constraints specified on the database schema then
it becomes a legal instance, it is used to maintain the quality of information.
DBMS enforces the integrity constraints to permit only the legal instances to be stored in the
database.
Integrity constraints are specified and enforced on database
1. When the DBA or end user defines a database schema.
2. When a database application is run, the DBMS checks for violation and disallow changes
to the data that violates the specified IC’s.
For example no two students have the same id value.
Key constraints:
A key constraint is a statement, a minimal set of attributes of a relation that uniquely identifies a
tuple of relation. A set of attributes that uniquely identifies a tuple in a relation is called a
candidate key for relation.A relation may have several candidate keys, a database designer can
identifies a primary key out of all candidate keys.
Unique key: it allows only unique value to store into the database it does not allows the
duplicate values to store in to the database.
Example: CREATE table StudentS (SID VARCHAR (10), NAME CHAR (10), AGE
INETEGER, EMAIL VARHAR(20) UNIQUE (EMAIL), SID);
SID NAME AGE EMAIL
101 Ramesh 19 [email protected]
102 Suresh 20 [email protected]
103 Mahesh 18 [email protected]
104 Hareesh 19
EMAIL attribute is defined as unique key for the above relation; it may allow null values but
does not allow the duplicate values.
NOT NULL: Is a key constraint it does not allows the NULL values to store into a relation.
Example: Example: CREATE table Students (SID VARCHAR (10) , NAME CHAR (10) NOT
NULL, AGE INETEGER, EMAIL VARHAR(20) UNIQUE (EMAIL), CONSTRAINT
Students key PRIMARYKEY (SID));
SID NAME AGE EMAIL
101 Ramesh 19 [email protected]
102 Suresh 20 [email protected]
103 Mahesh 18 [email protected]
104 Ramesh 19 [email protected]
Primary key: is a key constraint it allows only unique and not null values to store into a relation.
It won’t allow the duplicate and null values to store into the relation.
Example: CREATE table Students (SID VARCHAR (10), NAME CHAR (10), AGE
INETEGER, EMAIL VARHAR(20) UNIQUE (EMAIL), CONSTRAINT Students key
PRIMARYKEY (SID));
SID NAME AGE EMAIL
101 Ramesh 19 [email protected]
102 Suresh 20 [email protected]
103 Mahesh 18 [email protected]
104 Hareesh 19 [email protected]
SID is the primary key for the above relation; it does not allow the null values and duplicate
values.
Foreign key: foreign key is used to link two tables or relations. The information stored in one
relation is linked to the information stored in another relation. If one of the relation is modified
the other must be checked and modified to keep the database consistent. The key constraint
involving two relations is called foreign key constraint. The foreign key in referencing relation
must matches with primary key of referenced relation.
For example in addition student we have another relation called enrolled, to ensure that only
bonafied students can enroll in course. Any value appear in the SID field of an instance of
enrolled, should also appear in SID field of student relation.
Example: CREATE table Students (SID VARCHAR (10), NAME CHAR (10), AGE
INETEGER, EMAIL VARHAR(20) UNIQUE (EMAIL), CONSTRAINT Students key
PRIMARYKEY (SID));
Ex: CREATE table Enrolled (SID VARCHAR (10), CID CHAR (10), GRADE CHAR(10)
PRIMARY KEY (CID),
FOREIGN KEY (SID) REFERENCES STUDENTS);
Ssn
name lot
Employees
CREATE TABLE Dept_Mgr (ssn CHAR(11), did INTEGER, since DATE, dname
CHAR(10), Budget REAL, PRIMARY KEY (did), FOREIGN KEY (ssn) REFERRENCES
Employees);
Relation Dept_Mgr:
ssn did since dname budget
Works_in
since
pname age
lot
Ssn cost
name
name
Ssn lot
Employees
hours_worked
Contract_id
ISA
houlrly_wages
Hourly_Emps Contract_Emps
oyees
Figure: Class Hierarchy
Employees: ssn name lot
Hourly_Empsoyees: (houlrly_wages, hours_worked, Ssn)
Contract_Emps: (Contract_id, ssn)
7. Translating ER diagram with aggregation into relation
Employees
8.
Monitors
until
Started_on
pid dname budget
pbudget since did
Fig: Aggregation
Employees, Projects, and departments entity sets and sponsors relationship set are
mapped into relations as like Project(pid,stard_on, pbudget), employees(ssn, name, lot),
Dep_sponsors (did, dname, budget, pid since), for monitors relationship set create a
relation with following attributes, key attributes of employees(ssn), key attributes of
sponsors (pid, did), and descriptive attribute of monitors(until).
Monitors(ssn,pi,did,until)
The multivalued attribute is represented by a separate table:
It is not possible to represent in single column, so we should create a new table for Multivalued
attribute of ER model.
Student (Student_ID, Name, DOB, Door, Street, City, State, Pin, Course_Id)
Attends(Student_ID, Course_Id)
Relational Model:
There are some points for converting the ER diagram to the table:
In the given ER diagram, LECTURE, STUDENT, SUBJECT and COURSE forms individual
tables.
In the STUDENT entity, STUDENT_NAME and STUDENT_ID form the column of STUDENT
table. Similarly, COURSE_NAME and COURSE_ID form the column of COURSE table and so
on.
Relational Model:
Example4:
Relational Model:
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. For example, we might want to
find all students younger than 20.
A query language is a specialized language for writing queries.
SQL is the most popular commercial query language for a relational DBMS. We can
retrieve rows corresponding to students who are younger than 20 with the following SQL
query:
SELECT *
FROM Students S
WHERE S.age < 20
The symbol * means that we retain all fields of selected tuples in the result. S is a variable
that takes on the value of each tuple in Students, one tuple after the other. The condition
S.age < 20 in the WHERE clause specifies that we want to select only tuples in which the
age field has a value less than 20.
SID NAME AGE EMAIL
101 Ramesh 19 [email protected]
103 Mahesh 18 [email protected]
104 Hareesh 19 [email protected]
Student realtion:
sid name age marks mobileno
101 Ramesh 21 89 2222555222
102 Mahesh 22 98 8890333322
103 Hareesh 30 92 1233421123
104 Suresh 19 95 1234567321
Enrollmont table
sid name
102 Mahesh
103 Hareesh
104 Suresh
AND: The AND operator displays a record if all the conditions separated by AND are TRUE.
OR: The OR operator displays a record if any of the conditions separated by OR is TRUE.
Answer: the students who got marks between 80 to 90 and age is less than 20
IN: The IN operator allows you to specify multiple values in a WHERE clause.
NOT: The NOT operator displays a record if the condition(s) is NOT TRUE.
BETWEEN: The BETWEEN operator selects values within a given range. The values can be
numbers, text, or dates.
The BETWEEN operator is inclusive: begin and end values are included.
Example:
SELECT * FROM Student WHERE Marks BETWEEN (70, 100)
Enrollment
sid cid grade
101 C1 A
102 C2 B
We can also combine information in the Students and Enrolled relations. If we want to
obtain the names of all students who obtained an A and the id of the course in which they
got an A, we could write the following query:
LIKE: The LIKE operator is used in a WHERE clause to search for a specified pattern in a
column.
There are two wildcards often used in conjunction with the LIKE operator:
Example queries:
SELEC * FROM Student WHERE Name LIKE ‘n%’ OR Mobile no LIKE ‘9%’;
Views: a view is a virtual table whose rows are not explicitly stored in the database, but are
computed as needed from view definition. A view also has rows and columns as they are in a
real table in the database. We can create a view by selecting fields from one or more tables
present in the database. A View can either have all the rows of a table or specific rows based
on certain condition.
Syntax:
CREATE VIEW view_name AS
SELECT column1, column2.....
FROM table_name
WHERE condition;
view_name: Name for the View
table_name: Name of the table
Condition: Condition to select rows
Example:
Consider students and enrolled relations. Suppose if we want to find names, id of students who
got B grade in some course with course id.
CREATE VIEW B-Students (name,sid,course) AS
SELECT S.sname, S.sid, E.cid
FROM Students S, Enrolled E
WHERE S.sid=E.sid AND E.Grade=’B’;
Just like table query, we can query the view to view the data.
SELECT * FROM Viewname;
SELECT * FROM B-Students;
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.
1. The SELECT statement which is used to create the view should not include GROUP
BY clause or ORDER BY clause.
2. The SELECT statement should not have the DISTINCT keyword.
3. The View should have all NOT NULL values.
4. The view should not be created using nested queries or complex queries.
5. The view should be created from a single table. If the view is created using multiple
tables then we will not be allowed to update the view.
We can use the CREATE OR REPLACE VIEW statement to add or remove fields from a
view.
Syntax:
CREATE OR REPLACE VIEW view_name AS
SELECT column1,coulmn2,..
FROM table_name
WHERE condition;
For example, if we want to update the view MarksView and add the field AGE to this View
from StudentMarks Table, we can do this as:
We can insert a row in a View in a same way as we do in a table. We can use the INSERT
INTO statement of SQL to insert a row in a View.Syntax:
INSERT INTO view_name(column1, column2 , column3,..)
VALUES(value1, value2, value3..);
Deleting a row from a View:
Deleting rows from a view is also as simple as deleting rows from a table. We can use the
DELETE statement of SQL to delete rows from a view. Also deleting a row from a view first
delete the row from the actual table and the change is then reflected in the view.
Syntax:
DELETE FROM view_name
WHERE condition;
Example:
In this example we will delete the last row from the view DetailsView which we just added in
the above example of inserting rows.
DELETE FROM DetailsView
WHERE NAME="Suresh";
Destroying Views
A view can be dropped using the DROP VIEW command, which is just like DROP TABLE.
for example, we would use the following command:
DROP VIEW Viewname;
Consider the instances of Students and Clubs relations
cname Jyear mname
Selection(σ): this selection operator is for to select the tuples from a relation. It is denoted by
sigma(σ).
Ex: find the sailors rating is greater than from the instance of sailor’s relation (s2).
σ rating>8 (s2)
2,4,5,6,7,8,9,10,11,12,13,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,36,39,40,
41,42,43,44,45,46,47,48,49,50,51,52,54,56,57,58,59,60,LE-1,2,3,4,6
Projection(π): this selection operator is for to select the attributes from a relation. It is denoted
by pie(π).it can be represented as πa1,a2,….an (R). Here π is projection, a1, a2,.. etc, attributes of
relation and R is the relation.
Π sname, rating(S2)
sname Rating
yuppy 9
Lubber 8
guppy 5
Rusty 10
Ex: find the sname, rating of sailors whose rating is greater than 8 from instance of sailors S2.
Fig S1US2
Intersection: R∩S returns a relation instance containing all tuples that occur in both R and S.
The relations R and S must be union-compatible, and the schema of the result is defined to be
identical to the schema of R.
sid sname rating age
31 Lubber 8 55.5
58 Rusty 10 35.0
Fig: S1∩S2
Set-difference: R−S returns a relation instance containing all tuples that occur in R but not in S.
The relations R and S must be union-compatible, and the schema of the result is defined to be
identical to the schema of R.
Cross-product: RXS returns a relation instance whose schema contains all the fields of R (in the
same order as they appear in R) followed by all the fields of S (in the same order as they appear
in S). The result of R _ S contains one tuple hr; si (the concatenation of tuples r and s) for each
pair of tuples r 2 R; s 2 S. The cross-product opertion is sometimes called Cartesian product.
Sid cid
S1 C1 cid
S2 C1 C1
S1 C2 C2
S3 C2 Table: course (C)
Table: Enrolled (E)
E/C= Π sid (E)- Π sid(( Π sid (E) X C) – E).
Sid Cid
Π sid (E) X C =
S1 C1
S1 C2
S2 C1
S2 C2
S3 C1
S3 C2
( Π sid (E) X C) – E is
Sid Cid
S2 C1
S3 C1
Sid
S2
Π sid (E) is S3
sid
S1
S2
S3
Find the boats which have at least two reservations by different saiors
Ρ( reseserves, , Πsid,bid,bname,bcolor(sailorsxreservesxboats))
ρ (Reservation pairs(1Sid1,2 bid1,3bname, 4bcolor, 5 Sid2, 6
bi2,7bname, 8bcolor , 4bid2), Reservation X Reservations)
Πboats( σ Sid1< >Sid2) ∩ (Bid1 < >Bid2) Resevation pairs
Relational calculus: it is a non procedural language, it provides only description of the query,
but does not provide the methods to solve it. That is it explains what to do, not how to do.
It has two variants
Tuple relational calculus: a tuple variable is a variable that takes the tuples of particular
relation schema as values. Every value assigned to a given tuple variable has same nuber and
type of fields. A TRC a query can be expressed as {T|P (T)}. Where T is tuple variable, P(T) is a
predicate and these are conditions to fetch T. it returns the set of tuples T, such that predicate
P(T) is true for T.
P (T) may have various conditions
AND(∩), OR(V),NOT(┐), implise(
It also uses quantifiers
There exist Tє r(Q(T)), there exist a tupe T in relation r such that predicate Q(t) is true.
For all Tє r(Q(T)), q(t) is true for all tuples in relation r.
In relational calculus there exist and for all are said to bind the variables R.
A variable is said to be free in a formula or sub formula does not contain an occurrence of a
quantifier that binds it. Every variable in a TRC formula appears in a subformula that is atomic.
Syntax of TRC queries:
Let Rel be the relation name, R and S are tuple variables, a be the attributes of R, and b be the
attribute of S.
R€ Rel
R.a op S.b ( here op= <,>,= ,….etc)
R.a op constant
3. Find the sailor name, boat id and reservation date for each reservation.
{P| ∃ R є Reserves ∃ S є Sailors ( R.sid= S.sid ∩ P.bid= R.bid ∩ P. day=R. day ∩
P.sname= S.sname)}
4. Find the names of sailors who have reserved boat 103.
{P|∃ S є Sailors ∃ R є Reserves(R.sid= S.sid ∩ R.bid= 103 ∩ P.sname=S.sname)}
5. Find the names of sailors who have reserved a red boat.
{P|∃ S є Sailors ∃ R є Reserves(R.sid= S.sid ∩ P.sname=S.sname) ∩ ∃ B є
boats(B.bid=R.bid ∩ B.color=’red’)}
6. Find the names of sailors who have reserved at least two boats.
{P|∃ S є Sailors ∃ R1 є Reserves ∃ R2 є Reserves( S.sid=R1.sid ∩ R1.sid= R2.sid ∩
R1.bid != R2.bid ∩ P.sname=S.sname)}
7. Find the names of sailors who have reserved all boats.
{P|∃ S є Sailors ∀ B є boats ∃ R є Reserves(S.sid= R.sid ∩ R.bid=B.bid ∩
P.sname=S.sname)}
8. Find the names of sailors who have reserved all red boats.
{P|∃ S є Sailors ∀ B є boats (B.color=’red’ ⇒(∃ R є Reserves (S.sid= R.sid ∩
R.bid=B.bid))}
Or
{P|∃ S є Sailors ∀B є boats(B.color !=’red’ ∪(∃ R є Reserves (S.sid= R.sid ∩
R.bid=B.bid))}
Domain relational calculus: a domain variable is variable that ranges over the values in the
domain of some attribute.
DRC query can be expressed as {(x1, x2,……, xn )|P(x1, x2,……, xn )}, where x1, x2,……, xn represents
the domain variables, P(x1, x2,……, xn ) represents the condition or formula equivalent to the
predicate calculus.
The predicate calculus formula as TRC it contains:
1. Set of all comparison operators
2. Set of connectivity operators like AND,OR,NOT
3. Set of Quantifiers.
Domain relational calculus Queries on above tables:
1. Find all sailors with a rating above 7.
{(I,N,T,A)| <I,N,T,A> є Sailors ∩ T>7}
2. Find the names of sailors who have reserved boat 103.
{<N> | ∃ I,T,A <I,T,N,A> є Sailors ∩ ∃ Ir, Br, D <Ir, Br, D> є Reserves ( Ir= I ∩ Br=103)}
3. Find the names of sailors who have reserved a red boat.
{<N>|∃ I,T,A <I,T,N,A> є Sailors ∩ <Ir, Br, D> є Reserves ∩ ∃(Br, Bn, ‘red’) є Boats)}
4. Find the names of sailors who have reserved at least two boats.
{<N>|∃ I,T,A <I,T,N,A> є Sailors ∩ ∃ Br1, Br2, D1, D2(I,Br1, D1) є Reserves ∩ (I,Br2, D2) є
Reserves ∩ Br1!= Br2)}
5. Find the names of sailors who have reserved all boats.
{<N> | ∃ I,T,A <I,T,N,A> є Sailors ∩ ∀ B, Bn, C(¬ (B, Bn, C) ) є Boats) ∪ ∃ (<Ir, Br, D> є
Reserves (I=Ir ∩ Br= B)}
6. Find names of sailors who have reserved all red boats.
{(I,N,T,A)| <I,N,T,A> є Sailors ∩ ∀ (B, Bn, C) є Boats (c=’red’ ⇒ ∃ Ir, Br, D <Ir, Br, D> є
Reserves(I=Ir ∩ Br=B)}