0% found this document useful (0 votes)
21 views

Dbms Unit-II Notes

Uploaded by

Chandu Gantala
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Dbms Unit-II Notes

Uploaded by

Chandu Gantala
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

Unit-II

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)

S_id name age Phone. no


1201 ramesh 19 9999999999
1202 suresh 20 8888888888
1203 hareesh 18 7777777777
1204 afreena 20 9848002310

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.

Relation schema of student information in a university database:


Students(sid: string, name: string, age: integer, gpa: real)

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.

1. Data Definition Language (DDL)


DDL is used to define database structure or pattern. It is used to create schema, tables,
indexes, constraints, etc. in the database. DDL statements are used to create structure of the
database. Data definition language is used to store the information of metadata like the number
of tables and schemas, their names, indexes, columns in each table, constraints, etc.
DDL commands are:

 CREATE statement or command is used to create a new database. In structured query


language the create command creates an object in a relational database management
system. The commonly used create command is as follows
Syntax:
CREATE TABLE TABLE_NAME (COLUMN_NAME DATATYPES[,....]);
Example:
CREATE TABLE EMPLOYEE(Name VARCHAR2(20), Email VARCHAR2(100), DO
B DATE);

 DROP statement destroys or deletes database or table. In structured query language, it


also deletes an object from relational database management system. Typically used
DROP statement is
DROP type of object name of object
Syntax
DROP TABLE ;
Example
DROP TABLE EMPLOYEE;

 ALTER The ALTER TABLE statement is used to add, delete, or modify columns, to add
and drop various constraints on in an existing table

To add a column in a table, use the following syntax:

ALTER TABLE table_name


ADD column_name datatype;

To delete a column in a table, use the following syntax:


ALTER TABLE table_name
DROP COLUMN column_name;
To change the data type of a column in a table, use the following syntax:

ALTER TABLE table_name


MODIFY COLUMN column_name datatype;

SQL statement to change the data type of the column named "DateOfBirth" in the
"Persons" table is

SQL statement:

ALTER TABLE Persons


MODIFY COLUMN DateOfBirth year;

 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;

 RENAME statement is used to rename a database. It’s statement is as follows


RENAME TABLE old name of table to new name of table
Syntax:
ALTER TABLE table_name RENAME TO new_table_name;
Columns can be also be given new name with the use of ALTER TABLE.
ALTER TABLE table_name
RENAME COLUMN old_name TO new_name;

Data Manipulation Language (DML)


It is used for accessing and manipulating data in a database. Here are some commands that come
under DML:

 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' ;

 DELETE: It is used to remove one or more row from a table.


Syntax:
DELETE FROM table_name [WHERE condition];
For example:
DELETE FROM javatpoint
WHERE Author="Sonoo";

 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);

CID GRADE SID SID NAME AGE EMAIL


C1 A 101 101 Ramesh 19 [email protected]
C2 B 102 102 Suresh 20 [email protected]
C3 A 103 103 Mahesh 18 [email protected]
C4 C 104 104 Hareesh 19 [email protected]

Table: Enrolled Table: Students


If we try to insert SID in Enrolled, it validates the integrity constraint, SID in students relation it
does not allow a tuple to insert in enrolled relation if SID is not in Students relation and it does
not allows a tuple to delete from students relation.
Domain constraints: defines the valid set of values for an attribute. The type of domain includes
string, integer, char, varchar, time, date and range of values it is allowed to be stored.
EX: if we define an attribute SID int(5), it allows only integer with maximum length 5 to store,
it does not allows the char or string to store into the database.
General constraints: relational database supports the general constraints in the form table
constraints and assertions. Table constraint are associated with single table, although the
conditional expression in the CHECK clause can refer to other tables. Table constraints are
required to hold only if the associated table is nonempty. We can specify table constraints using
CHECK conditional expression.
Ex: to ensure that rating must be an integer in the range 1 to 10.
CREATE TABLE Sailors( sid INTEGER, sname CHAR(10), rating INTEGER, age REAL,
PRIMARY KEY (sid),
CHECK (rating >=1 AND rating <=10));
When a constraint involves two or more tables assertions are used.
Ex: CREATE TABLE Sailors(sid INTEGER, sname CHAR(10), rating INTEGER, age REAL,
PRIMARY KEY (sid),
CHECK(rating>=1 AND rating <=10)
CHECK((SELECT COUNT (s.sid) FROM Sailors S) + (SELECT COUNT (B.bid) FROM Boats
B) < 100));
Enforcing Integrity constraints:
Integrity constraints are specified when relation is created and enforced when relation is
modified. Every integrity constraints violation is generally checked at the end of sql statement
execution.
Ex: INSERT INTO Students (sid , name, age) VALUES (null, ‘mahesh’,20);
This insertion violates the constraint that the primary key cannot contain null.
Ex: UPDATE students S SET s.sid=1204 WHERE S.sid=1203;
This update violates the primary key constraint because there is already a tuple with sid 1204.
Referential integrity enforcement:
Insertion and deletion of tuples do not violate the integrity constraints.
Deletion of enrolled tuples do not violate the referential integrity, but insertions of enrolled
tuples could violate the integrity constraints.
Insertion of student tuples do not violate referential integrity, and deletion of students tuple could
cause violations.
SQL provides several alternative ways to handle foreign key violations:
1. If an enrolled row is inserted, with a sid that column value does not appear in any row of
students table. The INSERT command is simply rejected.
Ex: INSERT INTO Enrolled(cid,grade,sid) VALUES (‘dbms01’,ramesh,1271);
This insertion is illegal, because there is no students tuple with sid 1271.
2. If a students row is deleted
 Delete all enrolled rows that refer to the deleted student row
 Disallow the deletion of the student row if an enrolled row references to it.
3. If the primary key value of student row is updated
We can specify when a student row is deleted all enrolled rows refer to it are to be
deleted as well, but when the sid column of a student row is modified, this update is to be
rejected if an enrolled row refers to the modified students row.
CREATE TABLE Enrolled(sid char(20) cid char(20), grade char(10), PPRIMARY KEY
(sid,cid), FOREIGN KEY (sid) REFERENCES Students ON DELETE CASCADE ON
UPDATE NO ACTION);
The options are specified as part of foreign key declarations, the default option is NO
ACTION.
SQL also allows the use of null as the default value by specifying ON DELETE SET
NULL.
Transactions and constraints:
A program that runs against a database called a transaction, and it can contains several
statements that access the database. If a statement in a transaction violates the integrity
constraints then that statement is rejected.
To change a constraints validation granularity to the value in another column, we have to
explicitly declare a constraint as deferrable. The constraint deferrable allows a transaction to
differ validation until commit.
Consider the variants of following 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(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), FORIGN KEY (grader) REFERENCES Students (sid));
While inserting values into the above relations one cannot be inserted without the other. T he
only way to accomplish this insertion is to defer the constraint checking that would be normally
carried out at the end of an INSERT statement.
SQL allows constraint to be in DEFERRED or IMMEADIATE mode.
SET CONSTRAINT honors DEFERRED.
SET CONSTRAINT grader DEFERRED.
Logical database design: The ER model is convenient for representing in a high level database
design. Data organized in the database in the form of relations in relational model, Logical
database design describes how to convert an E-R Model to Relational Model.
Steps to convert an E-R Model to relational database schema or Relational Model
1. Entity sets to relations
2. Relationship sets (without constraints) to tables
3. Relationship set with key constraints into relation
4. Translating relationship sets with participation constraints
5. Translating weak entity sets into a relation
6. Translating class hierarchies into a relation
7. Translating ER diagram with aggregation into relation
1. Entity sets to relations :
An entity set in a ER diagram is mapped in to relation, each attribute of the entity set
becomes an attribute of the table by specifying the domain of each attribute and key of an
entity set. For example consider an Employee entity set with attributes ssn, name, and lot.

Ssn
name lot

Employees

Figure: The Employees Entity set


The employees entity set is represented in a table format .
ssn name Lot
123-22 suresh 48
321-21 ramesh 30
131-24 maheh 20
Fig: An instance of Entity set
The following SQL statement captures the preceding information, including the domain
constraints and key information:
CREATE TABLE Employees (ssn CHAR(10), name CHAR(20), lot INTEGER, PRIMARY
KEY (ssn));
2. Relationship sets (without constraints) to tables:
A relationship set, like an entity set directly mapped into a relation in the relational model by
identifying each participating entity and giving the values to the descriptive attributes of the
relation.
The attributes of the relation include:
 The primary key attribute of each participating entity set, as foreign key fields.
 The descriptive attributes of the relationship set.
budget
Did dname
Ssn e
name since
lot

Employees Works_in Departments

Address Locations capacity

Fig: A ternary relationship set


All the information about works_in relationship into works-in relation is captured by the
following SQL definition:
CREATE TABLE works_in (ssn CHAR(10), did INTEGER, address CHAR(20), since DATE,
PRIMARY KEY (ssn,did, address), FOREIGN KEY (ssn) REFERENCES Employees,
FOREIGN KEY (did) REFERENCES Departments,
FOREIGN KEY (address) REFERENCES Locations);
3. Relationship set with key constraints into relation
If a relationship involves n entity sets and some m of them are connected with arrow in the ER
diagram, key for any one 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.
Did
ssn dname budget
name lot since

Employees Manages Departments

Fig: Key constraints on Manages


So the manages has the attributes ssn, did, since, each department has at most one manager, no
two tuples can have the same did value but differ on ssn value, so did is act as key for manages
relation.
CREATE TABLE Manages(ssn CHAR(11), did INTEGER, since DATE, PRIMARY KEY
(did), FOREIGN KEY (did) REFERRENES Departments, FOREIGN KEY (ssn)
REFERRENCES Employees.
Manages:
ssn did since
Another approach is instead of creating a distinct table for the relationship set, include the
information about the relationship set in the table corresponding to the entity set with key. In this
example, because department has atmost one manager, we can add the key fields of employees
relation denoting the manager and since attribute to the departments relation.

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

4. Translating relationship sets with participation constraints to relations

ssn did dname budget


name s
since
lot

Employees Manages Departments

Works_in

since

Fig: Manages and works_in


CREATE TABLE Dept_Mgr (ssn CHAR(11) NOT NULL, did INTEGER, since DATE,
dname CHAR(10), Budget REAL, PRIMARY KEY (did), FOREIGN KEY (ssn)
REFERRENCES Employees ON DELETE NO ACTION);
It captures the participating constraint that every department must have a manager, because of
ssn cannot take on null values, each tuple of Dept_mgr identifies a tuple in employees(who is
manager).An employee tuple cannot be deleted while it is pointed to dept_mgr tuple. If we wish
to delete such an employee tuple, we must first change the dept_mgr tuple to have a new
employee as manager. (we could have specified CASCADE instead of NO ACTION).
There are many participating constraints that we cannot capture using SQL, short of using table
constraints or assertions. To ensure total participation of Departments in works_in we need an
assertion, to guarantee that every did value in departments appears in a tuple of works_in.
The tuples of works_in must also have not null values.
We can also capture participating constraints using key and foreign key constraints if a
relationship set in which all participating entity sets have key constraints and total participation
by mapping all the entities as well as relationship into a single table.
5. Translating weak entity sets into a relation
A weak entity set always participates in a one-to-many binary relationship and has a key
constraint and total participation. Weak entity has only partial key and also when owner entity is
deleted, we must want all the weak entities to be deleted.
Consider dependents weak entity set with a partial key pname. A dependents entity can be
identified uniquely if we take the key of owning employees entity and the pname of dependents
entity, and dependents entity must be deleted if the owning employees entity is deleted.

pname age

lot
Ssn cost
name

Employees Policy Dependents

Fig: Departments weak entity set


CREATE TABLE Dep_Policy (Pname CHAR(20), age INTEGER, cost REAL, ssn
CHAR(11), PRIMARY KEY (pname,ssn), FOREIGN KEY (ssn) REFERRENCES
Employees ON DELETE CASCADE);
6. Translating class hierarchies into a relation
We can map each of the entity sets Employees, hourly_emps, contract_emps to distinct relation.
The relation for hourly_emps includes hourly_wages and hours_worked attributes and also key
attribute of super class ssn.
The relation for contract_emps includes Contractid attributes and also key attribute of super class
ssn. If supper class employee tuple is deleted the delete must cascade to Hourly_emps relation
and contract_emps relation.
Another approach is we can create to relations hourly_emps, contract_emps by including all the
attributes of super class employees entity set along with the its own attributes.
The second approach is not applicable if we have employees who are neither hourly employees
nor contract employees.

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

Ssn name lot

Employees
8.

Monitors
until

Started_on
pid dname budget
pbudget since did

Projects sponsors Departments

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.

Examples on Logical data base design:

Student (Student_ID, Name, DOB, Door, Street, City, State, Pin, Course_Id)

Lecturer (Lecturer_Id, Lecturer_Name, Course_Id)

Subject (Subject_Id, Subject_Name, Lecturer_Id)

Course (Course_Id, Course_Name)


Stud_Hobby(Student_ID, Hobby)

Attends(Student_ID, Course_Id)

Takes (Lecturer_Id, Course_Id)

Teaches (Lecturer_Id, Subject_Id, Student_ID)

Relational Model:

There are some points for converting the ER diagram to the table:

A key attribute of the entity type represented by the primary key.

In the given ER diagram, COURSE_ID, STUDENT_ID, SUBJECT_ID, and LECTURE_ID are


the key attribute of the entity.

Entity type becomes a table.

In the given ER diagram, LECTURE, STUDENT, SUBJECT and COURSE forms individual
tables.

All single-valued attribute becomes a column for the table.

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.

Composite attribute represented by components.


In the given ER diagram, student address is a composite attribute. It contains CITY, PIN,
DOOR#, STREET, and STATE. In the STUDENT table, these attributes can merge as an
individual column.
Derived attributes are not considered in the table.
In the STUDENT table, Age is the derived attribute. It can be calculated at any point of time by
calculating the difference between current date and Date of Birth.
Using these rules, you can convert the ER diagram to tables and columns and assign the mapping
between the tables.
Tables for the given ER diagram is as below:
Example2:

Relational Model for above ER Model:


Example3:

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 cid grade


101 Coo2 A
SELECT Sid, Name, Marks FROM Student;

SELECT Sid, Name, Marks FROM Student where age< 20;


sid name marks
104 sureh 95

SELECT Sid, Name FROM Student WHERE marks>90;

sid name
102 Mahesh
103 Hareesh
104 Suresh

Age is <20 and marks>90

SELECT DISTINCT Sname FROM Student;

AND: The AND operator displays a record if all the conditions separated by AND are TRUE.

SELEC * FROM Student WHERE marks>80 AND marks<95;

OR: The OR operator displays a record if any of the conditions separated by OR is TRUE.

SELEC * FROM Student WHERE age>20 OR marks>90;

The students whose age above 20 or got marks higher than 90

SELEC * FROM Student WHERE marks>80 AND marks<90 AN age<20;

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.

The IN operator is a shorthand for multiple OR conditions.

SELECT * FROM STUDENT WHERE name IN ‘ma’,’he’;

NOT: The NOT operator displays a record if the condition(s) is NOT TRUE.

SELECT * FROM STUDENT WHERE name NOT IN ‘ma’;

SELECT * FROM STUDENT WHERE marks NOT IN ‘89’;

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

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)

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

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:

SELECT name, cid


FROM Students S , Enrollement E
WHERE S. sid = E.sid AND E.grade = ‘A’

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:

The percent sign ( % ) represents zero, one, or multiple characters

The underscore sign ( _ ) represents one, single character

Example queries:

SELEC * FROM Student WHERE Name LIKE ‘%n’;

SELEC * FROM Student WHERE Name LIKE ‘n%’;

SELEC * FROM Student WHERE Name LIKE ‘n_’;

SELEC * FROM Student WHERE Name LIKE ‘_n’;

SELEC * FROM Student WHERE Name LIKE ‘S_ _ _ _h’;

SELEC * FROM Student WHERE Name LIKE ‘S%h’;

SELEC * FROM Student WHERE Name LIKE ‘%Sh%’;

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:

CREATE VIEW StudentNames AS


SELECT S_ID, NAME
FROM StudentDetails
ORDER BY NAME;

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:

CREATE OR REPLACE VIEW MarksView AS


SELECT StudentDetails.NAME, StudentDetails.ADDRESS, StudentMarks.MARKS,
StudentMarks.AGE
FROM StudentDetails, StudentMarks
WHERE StudentDetails.NAME = StudentMarks.NAME;
Example:
CREATE VIEW GoodStudents (sid, gpa)
AS SELECT S.sid, S.gpa
FROM Students S
WHERE S.gpa > 3.0
We can modify the Good Students row, we can delete Good Students row by deleting
corresponding row from base table students. We can insert a Good Students row by inserting a
row into base table students.
A tuple in Clubs denotes that the student called mname has been a member of the club cname
since the date jyear.4 Suppose that we are often interested in _nding thenames and logins of
students with a gpa greater than 3 who belong to at least one club, along with the club name and
the date they joined the club.
We can define a view for this purpose:
CREATE VIEW ActiveStudents (name, login, club, since)
AS SELECT S.sname, S.login, C.cname, C.jyear
FROM Students S, Clubs C
WHERE S.sname = C.mname AND S.gpa > 3
Inserting a row in a view:

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

Sailing 1996 Dave


Hiking 1997 Smith
Rowing 1998 Smith
Figure: An Instance C of Clubs

sid name Login age gpa


50000 Dave dave@cs 19 3.3
53666 Jones jones@cs 18 3.4
53688 Smith smith@ee 18 3.2
53650 Smith smith@math 19 3.8
Figure 3.20 An Instance S3 of Students

name Login Club since


Dave dave@cs Sailing 1996
Smith smith@ee Hiking 1997
Smith smith@ee Rowing 1998
Smith smith@math Hiking 1997
Smith smith@math Rowing 1998
Figure 3.21 Instance of ActiveStudents
Relational Algebra:
Relational algebra is one of the two formal query languages associated with the relational
model. A fundamental property is that every operator in the algebra accepts (one or two) relation
instances as arguments and returns a relation instance as the result. the basic operators of the
algebra (selection, projection, union, cross-product,and difference. It describes a step-by-step
procedure for computing the desired answer, based on the order in which operators are applied in
the query.

Consider these instances of relations for writing queries

sid sname rating age sid sname rating age


22 Dustin 7 45.0 28 yuppy 9 35.0
31 Lubber 8 55.5 31 Lubber 8 55.5
58 Rusty 10 35.0 44 guppy 5 35.0
Figure Instance S1 of Sailors 58 Rusty 10 35.0

Figure: Instance S2 of Sailors


sid bid day
22 101 10/10/96
58 103 11/12/96
Figure: Instance R1 of Reserves

Selection(σ): this selection operator is for to select the tuples from a relation. It is denoted by
sigma(σ).

it can be represented as σ p R. Here σ is selection, p is condition, R is relation.

Ex: find the sailors rating is greater than from the instance of sailor’s relation (s2).
σ rating>8 (s2)

id sname rating age


28 yuppy 9 35.0
58 Rusty 10 35.0

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.

Ex: find the sname, rating from instance of sailors S2.

Π 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.

Π sname, rating(σ rating>8 (s2))


sname Rating
yuppy 9
Rusty 10
Set Operations
The following standard operations on sets are also available in relational algebra:
union(U),intersection(∩),set-di_erence (−), and cross-product (X).
Union: RUS returns a relation instance containing all tuples that occur in either relation instance
R or relation instance S (or both). R and S must be union compatible,and the schema of the result
is defined to be identical to the schema of R.
Two relation instances are said to be union-compatible if the following conditions hold:
{ they have the same number of the fields, and
{ corresponding fields, taken in order from left to right, have the same domains.

sid sname rating age


22 Dustin 7 45.0
31 Lubber 8 55.5
58 Rusty 10 35.0
28 yuppy 9 35.0
44 guppy 5 35.0

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.

sid sname rating age


22 Dustin 7 45.0
Fig: S1-S2

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 sname rating age sid bid day


22 Dustin 7 45.0 22 101 10/10/96
22 Dustin 7 45.0 58 103 11/12/96
31 Lubber 8 55.5 22 101 10/10/96
31 Lubber 8 55.5 58 103 11/12/96
58 Rusty 10 35.0 22 101 10/10/96
58 Rusty 10 35.0 58 103 11/12/96
Fig S1XR1
Rename: rename operator is used to give another name to relation. It is dented by rho(p).
The expression p(R(F),E) it takes an arbitrary relational algebra expression E and returns an
instance of new relation called R. R contains same tuples as the result of E and same schema as
E, but some field are renamed. The field names in relation R are same as in E, except for fields
renamed in the renaming list, which is list term having the form old namenew name or
position  new name.
Syntax: p(C(1sid1,5sid2), S1 X R1)
It returns the relation contains the tuples( sid1:integer, sname:string,rating:integer,age :real,
sid2:integer, bid: integer, day:date).
For example If we want to create a relation student_names with roll_no and name from student it
can be done using rename operator as:
P(student_names,π(rollnoo,name)(student)).
Division: this operator use full when a query contains ‘all’. For example find the names of
sailors who have reserved all boats. It is denoted slash (/).
Consider two relation instances A and B in which A has two fields x and y, and B has just one
field y with same domain as in A. The division operation (A/B) return set of x values for every y
value (a tuple of) B, there is tuple (x, y) in A.
The division operation (A/B) can be defined as
Π x (A)- Π x(( Π x (A) X B) – A).
Ex: consider the relation student (s), course (C)relations and find sid’s of students enrolled in all
or Every course.

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(( Π sid (E) X C) – E is

Sid
S2
Π sid (E) is S3

sid
S1
S2
S3

(E/C) = Π sid (E)- Π sid(( Π sid (E) X C) – E)


=s1
Output: S1
Consider relations for the writing queries
sid sname rating age
22 Dustin 7 45.0 si bid Day
29 Brutus 1 33.0 d
31 Lubber 8 55.5 22 101 10/10/98
32 Andy 8 25.5 22 102 10/10/98
58 Rusty 10 35.0 22 103 10/8/98
64 Horatio 7 35.0 22 104 10/7/98
71 Zorba 10 16.0 31 102 11/10/98
74 Horatio 9 35.0 31 103 11/6/98
85 Art 3 25.5 31 104 11/12/98
95 Bob 3 63.5 64 101 9/5/98
Fig: Instance of Sailors (S3) 64 102 9/8/98
74 103 9/8/98

Fig: Instance of Reserves R2

bid bname color


101 Interlake Blue
102 Interlake Red
103 Clipper Green
104 Marine Red
Fig: instance of Boats (B1)
Relational algebra queries on above tables:
Find the boats reserved by sailors with id 567
Πboats((σ sid=567 sailors)x Ressevesxboats)
1. Find the names of sailors who have reserved at least two boats.
ρ (Reservations, , Πsid,Sname,bid(SailorsX Reserves))
ρ (Reservation pairs(1Sid1, 2Sname1,3 bid1, 4 Sid2, 5Sname2, 6bid2),
Reservation X Reservations)
Πsname1( σ Sid1=Sid2) ∩ (Bid1 <>Bid2) Resevation pairs

Find the boats which have at least two reservations by different saiors
Ρ( reseserves, , Πsid,bid,bname,bcolor(sailorsxreservesxboats))
ρ (Reservation pairs(1Sid1,2 bid1,3bname, 4bcolor, 5 Sid2, 6
bi2,7bname, 8bcolor , 4bid2), Reservation X Reservations)
Πboats( σ Sid1< >Sid2) ∩ (Bid1 < >Bid2) Resevation pairs

2. Find the names of sailors who reserved boat 103.


Πsname ((σ bid=103 Reserves) X Sailors)
Or
Πsname (σ bid=103 (Reserves X Sailors))
Or
ρ (Temp1, σ bid=103 Reserves)
ρ (Temp2, Temp1X Sailors)
Πsname (Temp2)

3. Find the names of sailors who have reserved a red a boat.


Πsname (σ color=’red’ Boats) X Reserves X Sailors)
4. Find the colors of boats reserved by Lubber.
Πcolor((σ sname=’Luber’ Sailors) X reserves X boats)
5. Find the names of sailors who have reserved at least one boat.
Πsname (Sailors X Reserves)
6. Find the names of sailors who have reserved a red or green boat.
ρ (Tempboats,( σ color=’red’Boats) U ,( σ color=’green’Boats))
Πsname (Tempboats X Reserves X Sailors)
Or
ρ (Tempred, Πsid ((σ color=’red’ Boats) X Reserves ))
ρ (Tempgreen, Πsid ((σ color=’green’ Boats) X Reserves ))
Πsname((Tempred U Tempgreen) X Sailors)
7. Find the names of sailors who have reserved a red and green boat.
ρ (Tempboats( σ color=’red’Boats) ∩ ( σ color=’green’Boats))
Πsname (Tempboats X Reserves X Sailors)
8. Find the names of sailors who have reserved at least two boats.
ρ (Reservations, , Πsid,Sname,bid(SailorsX Reserves))
ρ (Reservation pairs(1Sid1, 2Sname1,3 bid1, 4 Sid2, 5Sname2, 6bid2),
Reservation X Reservations)
Πsname1( σ Sid1=Sid2) ∩ (Bid1 <>Bid2) Resevation pairs
9. Find the Sid’s of Sailors with age over 20 and who have not Reserved a red boat.
Πsid(σ age>20 Sailors)- Πsid((σ color=’red’Boats) X Reserves X Saulors)
10. Find names of sailors who have reserved all boats.
ρ (TempSid,( ΠSid,Bid Reserves)/ (ΠBid Boats))
Πsname(TempSid X Sailors)
11. Find the names of sailors who have reserved all boats called Interlake.
ρ (TempSid,,( ΠSid,Bid Reserves)/ (ΠBid (σ bname=’Interlake Boats))
Πsname(TempSids X Sailors)

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

Semantics of TRC Queries:


A tuple value F evaluates to true if one of the following holds:
 F is an atomic formula R€ Rel, R is assigned a tuple in the instance of relation Rel.
 F is a comparison R.a op S.b, R.a op constant, or constant op R.a, and the tuples assigned
to R and S have the field values R.a and S.b makes the comparison true.
 F is of the form negation P and p is not true, or of the form P∩Q, both p and q are true,
PUQ and one of them or true, P implise Q and q is true when p is true.
 F is of the form ,There exist R(p(R)) p® is true.
 F is of the form for all R(p(R)) and there is some assignment of tuple to the free variables
in p® that makes the formula p(R) true
Tuple relational calculus Queries on above tables:

1. Find sailors with the rating above 7.

{S|S є Sailors c S.rating>7}


2. Find the names and ages of sailors with a rating above 7.

{P|∃ S є Sailors (S.rating>7 ∩ P.sname=S.sname ∩ P.age=S.age)}


12. Find the names of sailors who have reserved a red or green boat.

{P|∃ S є Sailors,B є boats, R є Reserves ((B.color=’red’ U (B.color=green)) (S.sid=


R.sid ∩ R.bid=B.bid) ∩ P.sname=S.sname }

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)}

You might also like