0% found this document useful (0 votes)
18 views173 pages

1 5 Lect1 18, Tut1 6

This document provides an introduction to the Database Systems course taught by Prof. R. Gururaj at BITS Pilani Hyderabad Campus. It discusses key concepts like database systems and their significance, DBMS components and architecture, data models, data independence, database users, and DBMS client-server architecture. The goals of the course are to understand fundamental database concepts and how databases and DBMS help businesses perform operations efficiently.

Uploaded by

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

1 5 Lect1 18, Tut1 6

This document provides an introduction to the Database Systems course taught by Prof. R. Gururaj at BITS Pilani Hyderabad Campus. It discusses key concepts like database systems and their significance, DBMS components and architecture, data models, data independence, database users, and DBMS client-server architecture. The goals of the course are to understand fundamental database concepts and how databases and DBMS help businesses perform operations efficiently.

Uploaded by

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

Database Systems

(CS F212)
Prof.R.Gururaj
BITS Pilani CS&IS Dept.
Hyderabad Campus
Introduction DBMS Concepts and
Architecture(Ch.1 & 2 of T1)
Content
 Database Systems and Significance
 Database System Applications
 DBMS
 Database system environment
 Advantages of DBMS over traditional file systems
Data model
 Data abstraction and three-schema architecture
Data independence
 Database users
 Other issues

Prof.R Gururaj Database Systems BITS Pilani, Hyderabad Campus


Database Systems

Databases and Systems to manage them have become significant


components of any present day business of any nature.
These databases help businesses to perform their day-to-day
activities in an efficient and effective manner.

• Banking, Finance
• E-business
• Science and Engg
• Sports
Etc.

In all these sort of SW, some program access the database.

Prof.R Gururaj Database Systems BITS Pilani, Hyderabad Campus


Advances in technology has given raise to new concepts-

 Multimedia databases
 GIS
 Web data
 Data warehousing and mining
 Big Data
 No SQL Databases
 Distributed databases
 In memory databases
etc.

Prof.R Gururaj Database Systems BITS Pilani, Hyderabad Campus


Data: Known fact that can be recorded and that has
implicit meaning.
Ex. Name, Tel_no, city etc.

This data can be stored in a file on a computer.

Database: Is a collection of related data.

 It is a collection of logically related data.

 A database is designed, built and populated with


data for a specific purpose.

Prof.R Gururaj Database Systems BITS Pilani, Hyderabad Campus


DBMS
DBMS: Is a collection of programs that enables users to create and maintain
databases in a convenient and effective manner.

DBMS is a software system that facilitates the following:

1.Defining the database: This includes defining the structures, data types,
constraints, indexes etc.
Database catalog/Data dictionary/ called as Meta-data

2.Constructing the database: This means storing data into the database
structures and storing on some storage medium.

3.Manipulating database for various applications: This encompasses activities


like – querying the database, inserting new records into the database, updating
some data items, and deleting certain items from the database.

What is DBMS?
What is a Database System?

Prof.R Gururaj Database Systems BITS Pilani, Hyderabad Campus


Prof.R Gururaj Database Systems BITS Pilani, Hyderabad Campus
Traditional file Systems Vs. Database systems
(w.r.t., storing data)
If we take the example of savings bank enterprise,
information about customers and savings accounts need to
be stored.

One way to keep the information on computers is to store


in files provided by operating system (OS).

But using Database systems is more effective.


(will be discussed in Tutorials)

Prof.R Gururaj Database Systems BITS Pilani, Hyderabad Campus


Data model
Is a collection of concepts that can be used to describe the structure of the database.
Structure means data types, relationships, constraints etc.

DBMS allows a user to define the data to be stored in terms of a data model.

i) high-level data models (ii) low-level data models, (iii) representational or


implementation data models

High-level Data Models: Use set of concepts to describe the database, where the
descriptions are close to user views. High-level data models are also known as
conceptual models.
In conceptual data modeling we use concepts like – entity, attributes, relationship etc.

Low-level Data Models: give details about how the data is stored in a computers
(storage level details).

Prof.R Gururaj Database Systems BITS Pilani, Hyderabad Campus


Representational/Implementation Data Models:

This is in between high-level and low-level data models.

Here we represent the concepts described in conceptual


model using a specific structures like, networks, objects,
tables, trees etc.

Ex: Relational Model, NW Model, Hierarchical Model, Object


Model, Object relational model etc.

Prof.R Gururaj Database Systems BITS Pilani, Hyderabad Campus


The following are some important representational data models (DBMS Specific)

1. Network Model: Though the basic structure is a record,


the relationships are captured using links.
The database can be seen as an arbitrary network of records connected by links.
Ex.: GE’s Integrated Data store (IDS), in Early 1960s
2. Hierarchical Model: The records containing data are organized
as a collection of trees. Ex.: IBMs IMS (Information Management System),
in late 1960s
3. Relational Model: (early 1970s)Data & relationships are captured as tables & keys.
Ex.: Oracle, IBMs DB2, MySQL, Informix, Sybase, MS Access, Ingress, MySQL etc.
The basic storage structure is a record.
4. Object Data Model: Objects created through object–oriented programs
can be stored in database.
Ex. Object Store, ONTOS, POET etc
5. Object Relational Model: Objects can be stores in tables.
Ex.: Oracle, Informix

Prof.R Gururaj Database Systems BITS Pilani, Hyderabad Campus


Relational Model

Prof.R Gururaj Database Systems BITS Pilani, Hyderabad Campus


Hierarchical Model:

Network Model

Prof.R Gururaj Database Systems BITS Pilani, Hyderabad Campus


Database Schema
Database Schema: Description of a database is called as Database Schema

Three-Schema Architecture
A database can be described using three different levels of abstractions.
Description at each level can be defined by a schema. For each abstraction we
focus on one of the specific issues such as user views, concepts, storage etc.

1. External schema: Used to describe the database at external level.


Also described in terms of the data model of that DBMS. This allows data
access to be customized at the level of individual users/groups/applications.
Any external schema has one or more views and relations from the conceptual
schema. This schema design is guided by end user requirements.
2. Conceptual schema (logical schema) Describes the stored data in terms of the
data model specific to that DBMS. In RDBMS conceptual schema describes
all relations that are stored in the database. Arriving at good choice of
relations, fields and constraints is known as conceptual database design.
3. Physical schema: Describes the physical storage strategy for the database.

Prof.R Gururaj Database Systems BITS Pilani, Hyderabad Campus


Three Schema Architecture

External Schema 1 External Schema 2 External Schema 3


External Level

Conceptual Level Conceptual Schema

Physical Schema
Physical/Internal
Level

Storage

Three schema architecture of


DBMS

Prof.R Gururaj Database Systems BITS Pilani, Hyderabad Campus


Data Independence
Data Independence:
The three-level architecture which is the result of the three-level
abstraction on database, leads to data independence.

1. Logical data independence: changes in conceptual level schema


should not affect the application level or external level schemas.

2. Physical data independence: The changes in physical features of


storage, i.e., changes to the physical storage format should not affect
schema at conceptual level.

The above data independence is one of the important advantages of


DBMS.
Metadata:
The DBMS stores the description of schema constructs, the constraints,
and other related info about the data in the DB. These descriptions are
called as metadata. Otherwise it can be seen as data about data.
Prof.R Gururaj Database Systems BITS Pilani, Hyderabad Campus
DBMS Structure
Web form Application SQL
front end interface

SQL
Command
s

Query Engine

Transaction
Manager
Recovery
Buffer / Disk / File Manager
Lock Manager
Manager

Concurrency
control manager

DBMS

Index files
/system
catalog /data
blocks

Prof.R Gururaj Database Systems BITS Pilani, Hyderabad Campus


Users of Database Systems

 Naïve users
 Application Programmers
 Sophisticated users
 DBA

DBA:
1. Design of physical & Conceptual schemas
2. Security and authorization
3. Data availability , recovery and backup
4. Monitoring space
5. Monitoring jobs
4. Database tuning- modifying the schemas to meet
the requirements
Prof.R Gururaj Database Systems BITS Pilani, Hyderabad Campus
DBMS Client-Server
Architecture

DBMS and Client-server Architectre:

1. Centralized:

2. Client server:

two-tier
three-tier

(will be discussed in Tutorials)

Prof.R Gururaj Database Systems BITS Pilani, Hyderabad Campus


Prof.R Gururaj Database Systems BITS Pilani, Hyderabad Campus
Prof.R Gururaj Database Systems BITS Pilani, Hyderabad Campus
Prof.R Gururaj Database Systems BITS Pilani, Hyderabad Campus
Summary
 What is Data, Database, and DBMS
 Importance of DBMS
 Advantages of DBMS over traditional file systems
 What is a data model
 What is abstraction
 What is three schema architecture of a DBMS
 What is data independence
 Components of a DBMS
 Users of DBS
 Database Client server Architectures

Prof.R Gururaj Database Systems BITS Pilani, Hyderabad Campus


CS F212
Database Systems

Prof.R.Gururaj
BITS Pilani CS&IS Dept.
Hyderabad Campus
Relational Data Model & Relational
Constraints (Ch.3 of T1)

Content

1. What is Relational model


2. Characteristics
3. Relational constrains
4. Representation of schemas
5. Operations on relations and constraints

Prof.R.Gururaj CSF 212 Database Systems BITS Pilani, Hyderabad Campus


Relational Model
Edgar Codd proposed Relational Data Model in 1970.
It is a representational or implementation data model.

Using this representational (or implementation) model we


represent a database as collection of relations.

The notion of relation here is different from the notion of


relationship used in ER modeling.

Relation is the main construct for representing data in


relational model.
Every relation consists of a relation schema and relation
state.

Prof.R.Gururaj CSF 212 Database Systems BITS Pilani, Hyderabad Campus


R (A1, A2, A3,……,An)
Relation Schema is denoted by
Relation name Attribute list

The number of columns in a relation is known as its degree or arity’.

Relation State (r) of R (thought of as a table) is set on n tuples of R


Each tuple in the table represents a collection of related data.
Each tuple contains facts about some entity of some entity-set.

R = (A1, A2, A3,……., An)


r(R) is a set of n tuples in R
r = {t1, t2, t3,…….,tn}
r is state of R, and each t is a tuple and is a ordered list of values.

t = (v1 , v2 ,…, vn ) where vi is an element of domain of Ai

Prof.R.Gururaj CSF 212 Database Systems BITS Pilani, Hyderabad Campus


Entities of each type/set are stored as rows in a single relation.

Hence in general, a relation corresponds to a single entity type in


ER diagram.
In some cases a relationship between two entities can have some
specific attributes which can be captured in a relation (table).

A row is called a tuple.


The columns of the table represent attributes of that entity type.

The column header is known as attribute or field.


Data type or format of an attribute: is the format of data for that
attribute. Ex. Character strings, numeric, alphanumeric etc.

Values that can appear in a column for any row is called the
domain of that attribute.
Prof.R.Gururaj CSF 212 Database Systems BITS Pilani, Hyderabad Campus
Relational Database Schema is denoted by

S ={R1, R2, ……,Rn}

Database Relations in the


name database (tables)

Prof.R.Gururaj CSF 212 Database Systems BITS Pilani, Hyderabad Campus


Attribute A of relation R is accessed by notation- R.A

Ex: Student (name, age, branch). Here Student is the relation name.
Student.age - denotes age attribute of Student relation.

Characteristics of a Relation:

Ordering of tuples is not significant.

Ordering of values in a tuple is important.

Values in a tuple under each column must be atomic (simple


& single).

Prof.R.Gururaj CSF 212 Database Systems BITS Pilani, Hyderabad Campus


Prof.R.Gururaj CSF 212 Database Systems BITS Pilani, Hyderabad Campus
Relational Model Terminology

Informal Terms Formal Terms


Table Relation
Column Header Attribute
All possible Column Domain
Values
Row Tuple
Table Definition Schema of a Relation
Populated Table(set of State of the Relation
valid tuples)

Prof.R.Gururaj CSF 212 Database Systems BITS Pilani, Hyderabad Campus


Relational Constraints
Constraints are restrictions on data of a relation.

Domain level Constrains –


Format of data Ex. Character numeric etc.
Semantic – Not NULL etc.
Range
Entity integrity constraints –
Primary key, unique key

Referential integrity constraints–


Foreign key

Prof.R.Gururaj CSF 212 Database Systems BITS Pilani, Hyderabad Campus


Relational Constraints

Dependencies –
Functional dependency : What attributes value
defines the value of another attribute is known
as dependency.

This concept is used in database design.

Prof.R.Gururaj CSF 212 Database Systems BITS Pilani, Hyderabad Campus


Referential integrity

The Referential Integrity constraint is specified


between two relations and is used to maintain
consistency among the tuples of two relations.
FK
PK
R1 R2
a b c p q r

c in R1 refers to p in R2

Prof.R.Gururaj CSF 212 Database Systems BITS Pilani, Hyderabad Campus


Referential integrity
The value of FK in a tuple t of R1 either occurs as a
value under p in R2 for some tuple, or is a NULL.

R1  is known as referencing relation


R2 is known as referenced relation

Constraints can be specified while defining the structure


& also as triggers.

Prof.R.Gururaj CSF 212 Database Systems BITS Pilani, Hyderabad Campus


Relational Schema
Representation

Prof.R.Gururaj CSF 212 Database Systems BITS Pilani, Hyderabad Campus


Relational Schema
Representation

Prof.R.Gururaj CSF 212 Database Systems BITS Pilani, Hyderabad Campus


Summary
 What are basics of relational model
 Relation instance
 Relational data constraints
Referential integrity
Relational scheme representation
Operations on relations and constraints

Prof.R.Gururaj CSF 212 Database Systems BITS Pilani, Hyderabad Campus


Database Systems
(CSF 212)
Prof.R.Gururaj
BITS Pilani CS&IS Dept.
Hyderabad Campus
Structured Query Language
(SQL)
Content

 Introduction to SQL
 Features of SQL
 DDL Statements
 DML commands
 Nested queries and correlated nested queries
 Use of EXISTS and NOT EXISTS
 Explicit join operations
 Aggregate functions
 Group by and Having classes
 Insert/ Update / Delete operations
 Views in SQL

CSF 212 Database Systems Prof.R.Gururaj BITS Pilani, Hyderabad Campus


Introduction to SQL

SQL (Structured Query language) is the most widely used


commercial query language for relational databases.

SQL was introduced by IBM(1970).

 We study SQL -3 or SQL – 99 which was introduced in 1999 by


ANSI (American National Standards Institute) and ISO
jointly.
SQL is a user friendly query language.

 Now-a-days almost all relational databases like – Oracle,


MySQL, IBM’s DB2, Informix etc., support SQL.

CSF 212 Database Systems Prof.R.Gururaj BITS Pilani, Hyderabad Campus


SQL is a high-level declarative language to specify data retrieval
requests for data stored in relational databases.

 Its declarative because we just specify what to be extracted,


rather than how to do it.

SQL is relationally complete, meaning that any query that is


expressed in relational algebra or calculus can also be written
in SQL.

SQL also supports additional features that are not existing in


formal languages.

SQL is a standard and many vendors implement it in their own


way without deviating from the standard specifications.

CSF 212 Database Systems Prof.R.Gururaj BITS Pilani, Hyderabad Campus


Features of SQL
1. DDL (Data Definition Language) Set of commands to support creation,
deletion and modification of table structures and views.

2. DML (Data Manipulation Language) Set of commands to pose queries,


insert new tuples, and update/delete existing tuples.

3. Embedded SQL: Allows users to call SQL code from host languages like
C, C++ & Java.

4. Triggers: Actions executed by the DBMS whenever changes to the


database meet specified conditions. Action to be performed and the set of
conditions can be defined in “Triggers”.

5. Transaction Management: to perform roll-back / commit actions.

6. Indexes: Indexes can be created to speed up the access to data stored in


DB.

CSF 212 Database Systems Prof.R.Gururaj BITS Pilani, Hyderabad Campus


DEPT (dnum, dname, dloc)

EMP (eid, ename, esal, dno, ecity)

PROJ(pnum, pname)

EMP_PROJ (eno, pno, hrs)

CSF 212 Database Systems Prof.R.Gururaj BITS Pilani, Hyderabad Campus


DDL Commands

CREATE TABLE DEPT( DNUM INT, DNAME VARCHAR(5), DLOC


VARCHAR(10), PRIMARY KEY (DNUM), UNIQUE (DNAME));

CREATE TABLE EMP( EID INT PRIMARY KEY, ENAME VARCHAR(20),


ESAL INT, DNO INT, ECITY VC(10), FOREIGN KEY (DNO)
REFERENCES DEPT(DNUM));

CREATE TABLE PROJ( PNUM INT PRIMARY KEY, PNAME


VARCHAR(10));

CREATE TABLE EMP_PROJ( ENO INT , PNO INT, HRS INT, PRIMARY
KEY (ENO, PNO), FOREIGN KEY (ENO) REFERENCES EMP(EID),
FOREIGN KEY (PNO) REFERENCES PROJ(PNUM));

ALTER TABLE EMPLOYEE ADD CONSTRINT EMPFK FOREIGN KEY (DNO)

CSF 212 Database Systems Prof.R.Gururaj BITS Pilani, Hyderabad Campus


DROPPING TABLE EMP
Drop table EMP;

Adding New column to EMP

ALTER TABLE EMP ADD ‘CITY’ VARCHAR (20);

TO DROP A COLUMN

ALTER TABLE EMP DROP AGE CASCADE/RESTRICT;

We can also give names to constraints and later use


the names to access those constraints and alter them.
CSF 212 Database Systems Prof.R.Gururaj BITS Pilani, Hyderabad Campus
DML Commands

DML (Data Manipulation)

Selecting tuples, columns


(querying)
Inserting new tuples
Updating existing tuples
Deleting existing tuples

CSF 212 Database Systems Prof.R.Gururaj BITS Pilani, Hyderabad Campus


DEPT (dnum, dname, dloc)

EMP (eid, ename, esal, dno, ecity)

PROJ(pnum, pname)

EMP_PROJ (eno, pno, hrs)

CSF 212 Database Systems Prof.R.Gururaj BITS Pilani, Hyderabad Campus


Basic Query Statements
SQL has ‘SELECT’ statement for retrieving information from the database.
This SELECT has no relationship with select () operation in relational
algebra. All the queries mentioned here are specified on the COMPANY
database given in Fig. 3.1.

THE SELECT – FROM – WHERE CONSTRUCT:

SELECT < attribute list> // attribute names to be retrieved


FROM < table list > // names of relation involved
WHERE < condition> // Boolean expression to identify the
tuples to be extracted.

CSF 212 Database Systems Prof.R.Gururaj BITS Pilani, Hyderabad Campus


SQL> select * from emp;

EID ENAME ESAL DNO CITY


---------- -------------------- ---------- ---------- ----------
101 Raju 29000 10 Hyderabad
102 Kiran 35000 20 Chennai
104 Abdul 25000 20 Hyderabad
106 John 20000 10 Mumbai
109 Murali 30000 Mumbai

SQL> select * from dept;

DNUM DNAME DLOC


---------- ---------- ----------
10 HR Chennei
20 ACCT Mumbai
30 MARK Delhi

CSF 212 Database Systems Prof.R.Gururaj BITS Pilani, Hyderabad Campus


SQL> select * from emp;

SQL> select dno from emp;

SQL> select all dno from emp;

SQL> select distinct dno from emp;

SQL> select * from emp where dno=null;


Joining tables on FK:
SQL> select * from emp, dept where dno=dnum;

CSF 212 Database Systems Prof.R.Gururaj BITS Pilani, Hyderabad Campus


Ex. Get eid, esal for name ‘John’

Ex. Get eid , ename for those working in ACCT department

Ex.

SELECT eid, dname


FROM EMP, DEPT;

Applying AND OR in where clause

Ex. SELECT *
FROM EMP
WHERE dno = 10 OR city=‘Chennai’;

CSF 212 Database Systems Prof.R.Gururaj BITS Pilani, Hyderabad Campus


Substring Comparisons in SQL
The character ‘%’ replaces an arbitrary number of characters, and ‘_‘
(underscore) replaces a single character.
Ex: get all employees whose name ends with ‘n’.
Ex: get the emp details where the name has exactly 4 letters.

Ex. To retrieve the resulting salaries if every employee working in the


‘ACCT’ dept is given a 10% hike.

SELECT eid, ename, 1.1* esal


FROM EMP, DEPT
WHERE dno = dnum AND AND dname = ‘ACCT’;

Using between and to check range of numeric attributes


Get details of all employees whose salary is between 30,000
and 40,000.
CSF 212 Database Systems Prof.R.Gururaj BITS Pilani, Hyderabad Campus
We also have following operations in SQL
Union (for Union)
MINUS (for Difference)
Intersect (for Intersection)

Duplicate tuples are eliminated from the result.

CSF 212 Database Systems Prof.R.Gururaj BITS Pilani, Hyderabad Campus


SQL> (select * from emp where dno=10) INTERSECT (select * from emp
where esal>25000);
EID ENAME ESAL DNO CITY
---------- -------------------- ---------- ---------- ----------
101 Raju 29000 10 Hyderabad
SQL> (select * from emp where dno=10) UNION (select * from emp where
esal>25000);
EID ENAME ESAL DNO CITY
---------- -------------------- ---------- ---------- ----------
101 Raju 29000 10 Hyderabad
102 Kiran 35000 20 Chennai
106 John 20000 10 Mumbai
109 Murali 30000 Mumbai
SQL> (select * from emp where dno=10) MINUS (select * from emp where
esal>25000);
EID ENAME ESAL DNO CITY
---------- -------------------- ---------- ---------- ----------
106 John 20000 10 Mumbai
CSF 212 Database Systems Prof.R.Gururaj BITS Pilani, Hyderabad Campus
Using Order By:
The default ordering of the result is ascending.
We can specify the key word DESC if we wish a descending order of
values.
EX1: GET EMP DETAILS ORDERED ON NAME.
SQL> SELECT * FROM EMP ORDER BY ENAME;
SQL> SELECT * FROM EMP ORDER BY ENAME DESC;

WE CAN ALSO ORDER THE RESULTS BASED ON MULTIPLE COLUMNS.


SQL> SELECT * FROM EMP ORDER BY DNO,ENAME;

EID ENAME ESAL DNO CITY


---------- -------------------- ---------- ---------- ----------
106 JOHN 20000 10 MUMBAI
101 RAJU 29000 10 HYDERABAD
104 ABDUL 25000 20 HYDERABAD
102 KIRAN 35000 20 CHENNAI
109 MURALI 30000 MUMBAI

CSF 212 Database Systems Prof.R.Gururaj BITS Pilani, Hyderabad Campus


SQL> select * from emp order by dno asc,ename desc;

EID ENAME ESAL DNO CITY


---------- -------------------- ---------- ---------- ----------
101 Raju 29000 10 Hyderabad
106 John 20000 10 Mumbai
102 Kiran 35000 20 Chennai
104 Abdul 25000 20 Hyderabad
109 Murali 30000 Mumbai

CSF 212 Database Systems Prof.R.Gururaj BITS Pilani, Hyderabad Campus


Nested Queries

Ex. Retrieve the id and name of employees whose department


name is located in Chennai

SELECT E.eid, E.ename


FROM EMP AS E
WHERE E.dno IN(SELECT DNUM FROM DEPT
WHERE DLOC = ‘Chennai’;

Correlated Nested Queries:

Whenever a condition in the WHERE clause of a nested query


references some attribute of a relation declared in the outer query, then
the two queries are said to be correlated.

CSF 212 Database Systems Prof.R.Gururaj BITS Pilani, Hyderabad Campus


Use of NOT EXISTS clause
Ex.
Retrieve the id, salary of employees who have no projects

SELECT E.eid, E. esal


FROM EMP AS E
WHERE NOT EXISTS (SELECT * FROM EMP_PROJ AS EP WHERE
E.EID = EP.ENO);

We can also use ‘EXISTS’ to check the existence of at least one tuple
in the result.

It is also possible to use an explicit set of values in the WHERE –


clause.
We can also check whether a value is NULL

CSF 212 Database Systems Prof.R.Gururaj BITS Pilani, Hyderabad Campus


Renaming Attributes in the Result
Ex. 3
SELECT ename AS Emp_name
FROM EMP
WHERE Dno = 10;

CSF 212 Database Systems Prof.R.Gururaj BITS Pilani, Hyderabad Campus


Join Operation
We can also perform
Join – using key word ‘JOIN’
Natural join – using key word ‘NATURAL JOIN’
Left outer join – using key word ‘LEFT OUTER JOIN’
Right outer join – using key word ‘RIGHT OUTER JOIN’

Ex: Select * from (Emp join Dept on dno=dnum) where dname=‘HR’;

Aggregate Functions and Grouping


COUNT
SUM
MAX
MIN
AVG

CSF 212 Database Systems Prof.R.Gururaj BITS Pilani, Hyderabad Campus


SQL> select * from emp, dept where dno=dnum;
SQL> set linesize 300
SQL> select * from emp, dept where dno=dnum;

EID ENAME ESAL DNO CITY DNUM DNAME DLOC


---------- -------------------- ---------- ---------- ---------- ---------- ---------- ----------
101 Raju 29000 10 Hyderabad 10 HR Chennai
102 Kiran 35000 20 Chennai 20 ACCT Mumbai
104 Abdul 25000 20 Hyderabad 20 ACCT Mumbai
106 John 20000 10 Mumbai 10 HR Chennai

CSF 212 Database Systems Prof.R.Gururaj BITS Pilani, Hyderabad Campus


SQL> select * from (emp left outer join dept on dno=dnum);

EID ENAME ESAL DNO CITY DNUM DNAME DLOC


---------- -------------------- ---------- ---------- ---------- ---------- ---------- ----------
106 John 20000 10 Mumbai 10 HR Chennai
101 Raju 29000 10 Hyderabad 10 HR Chennai
104 Abdul 25000 20 Hyderabad 20 ACCT Mumbai
102 Kiran 35000 20 Chennai 20 ACCT Mumbai
109 Murali 30000 Mumbai

SQL> select * from (emp right outer join dept on dno=dnum);

SQL> select * from (emp full outer join dept on dno=dnum);

CSF 212 Database Systems Prof.R.Gururaj BITS Pilani, Hyderabad Campus


Ex. SELECT SUM (esal), AVG (esal) from EMP;

Ex. To retrieve number of rows in Employee table


SELECT count (*)
FROM EMP;

Ex. Retrieve the eid and name of employees who have two or more
Projects

SELECT eid, ename


FROM EMP
WHERE (SELECT COUNT (*) FROM EMP_PROJ WHERE ENO =
EID) > = 2;

CSF 212 Database Systems Prof.R.Gururaj BITS Pilani, Hyderabad Campus


Group by

Ex. For each department retrieve the department number and no of


employees.
SELECT dno, count (*)
FROM EMP
GROUP BY Dno;
Group by and Having clause

Ex. Retrieve the department number and no of employees for the


departments which have more than 5 employees working for it.

SELECT dno, count (*)


FROM EMP
GROUP BY Dno
HAVING count(*)>5;
CSF 212 Database Systems Prof.R.Gururaj BITS Pilani, Hyderabad Campus
INSERT operation
For Inserting a new tuple into the relation
General Form
INSERT INTO <table name>
VALUES(v1, v2, v3,………….vn);

Ex. INSERT INTO DEPT


VALUES(10, ‘HR’, ‘MUMBAI’);
Deleting a tuple

Ex. DELETE FROM <table name>


WHERE <condition>;

Ex. DELETE FROM DEPT


WHERE dnum=10;
If we don’t specify the condition all tuples are deleted.
CSF 212 Database Systems Prof.R.Gururaj BITS Pilani, Hyderabad Campus
Update command

Ex. UPDATE EMP


SET esal = 60000
WHERE eid = 104;

CSF 212 Database Systems Prof.R.Gururaj BITS Pilani, Hyderabad Campus


Views in SQL

A view in SQL is a single table that is derived from other tables.

These other tables are known as base tables.

A view does not necessarily exist in physical form, it can be considered


as a virtual table.

The tuples of base tables are actually stored in database.

This limits the updates on views.

In fact when a view is updated, the corresponding base tables are the
structures which are to be updated.

This makes update operations on views complex.

CSF 212 Database Systems Prof.R.Gururaj BITS Pilani, Hyderabad Campus


Creating View
CREATE VIEW EMP_DETAILS
AS SELECT eid, ename, dname,
FROM EMP, DEPT
WHERE dno = dnum;

Whenever the view definition is executed, the new temporary table is


generated with specified attributes from specified base tables.

View definitions are stored in database, not the result of the view.
From then onwards view can be seen as a table and queries can be
posed on it.

CSF 212 Database Systems Prof.R.Gururaj BITS Pilani, Hyderabad Campus


Ex. SELECT eid, ename FROM EMP_DETAILS
WHERE dname=‘HR’ ;

CSF 212 Database Systems Prof.R.Gururaj BITS Pilani, Hyderabad Campus


Note:

• A view is always up to date.


• Updates are generally not possible on views.
• Meant for querying only.
• Some times it is possible to store views for some
duration.
• Those views are known as materialized views.

CSF 212 Database Systems Prof.R.Gururaj BITS Pilani, Hyderabad Campus


Summary

 What is SQL
 What are the features supported by SQL
 How to create relational schemas using SQL
 How to specify queries in SQL
 How to write nested queries in SQL
 Writing queries using the clauses EXISTS, NOT XISTS,
BETWEEN AND, IN, NOT IN
 How to perform explicit JOIN operations
 How to use GROUP BY and HVING
 The concept of views in SQL

CSF 212 Database Systems Prof.R.Gururaj BITS Pilani, Hyderabad Campus


Database Design & Applications
(SS ZG 518)

BITS Pilani Dr.R.Gururaj


CS&IS Dept.
Hyderabad Campus
Relational Algebra &
Relational Calculus
Content

Query languages & Formal query languages for


Relational data model
Introduction to Relational Algebra
Relational operators
Set operators
 Join operators
 Aggregate functions
 Grouping operator
Relational Calculus concepts

Dr.R.Gururaj Database Systems BITS Pilani, Hyderabad Campus


Query Languages for Relational data model

Querying means extracting data from the database for the purpose of
processing it.

Every data model has some formal query languages to support


specification of data retrieval and manipulate requests.

Formal query languages


1. Relational Algebra
2. Relational Calculus
(a) Tuple Relational Calculus
(b) Domain Relational Calculus
Commercial query languages
1. Structured Query Language (SQL)
2. Query by Example (QBE)

Dr.R.Gururaj Database Systems BITS Pilani, Hyderabad Campus


Introduction to Relational Algebra

Relational Algebra is a formal query language for relational data model.

A basic set of relational model operations constitute the relational


algebra.
These operations enable the user to specify basic data retrieval
requests.
The result of a relational algebra query is also a new relation which may
have been formed from one or more relations.

A sequence of relational algebraic operations forms a relational


algebraic expression, whose result is also a relation.

Dr.R.Gururaj Database Systems BITS Pilani, Hyderabad Campus


Operations in Relational Algebra

A. Set Operations

o Union,
o Intersection,
o Difference,
o Cartesian product.

B. Relational Operations

o Select,
o Project,
o join,
o Division etc.

Dr.R.Gururaj Database Systems BITS Pilani, Hyderabad Campus


Select Operation: is to select subset of tuples that satisfy some
selection condition.
Symbol used is  (sigma)

Ex:  dno4 (EMP)


The above expression selects all tuples from EMP table, where the
value of the column ‘dno’ is 4.

The general form of ‘select’ clause is  <select condition> ( R)


Projection Operation:
Selects certain columns. Symbol is ( pi)
 name, age, dno(EMP)
Selects columns name, age, dno for all tuples from the table EMP
Dr.R.Gururaj Database Systems BITS Pilani, Hyderabad Campus
Note:
We can apply the expressions in sequence or we can nest them in
single expression.
 name, age  dno=5 ( EMP) 
Ex.:

The above expression selects name and age of employees


working with dno 5.

The above query can also be written as

R1   dno=5 ( EMP)

R2   name,age ( R1 )
R1 & R2 are the names given to intermediate results(relations).

Dr.R.Gururaj Database Systems BITS Pilani, Hyderabad Campus


Union:
If two relations R1 & R2 are compatible ( i.e., have same type of tuples)
then we can merge them by union operation.

Duplicate tuples are eliminated. Ex: (R1  R2).

Intersection R1  R2

Only equivalent tuples from R1 & R2 are selected.

Difference R1 – R2

Only those tuples seen in R1 and not seen in R2 are selected.

Note: (R1-R2) is not same as (R2-R1)

Dr.R.Gururaj Database Systems BITS Pilani, Hyderabad Campus


 a11 a12  no rows = 3 Rows=3
 b11 b12 
R1  a21 a22  no Columns -2 Column=2
R2 b21 b22 
 a31 a32  b31 b32 

(R1  R2) =  a11 a12 b11 b12 


a a12 b21 b22 
 11
 a11 a12 b31 b32 
 
 a21 a22 b11 b12 
No of rows = 3  3 = 9  a21 a22 b21 b22 
 
No Columns = 2 + 2 = 4  a21 a22 b31 b32 
a a32 b11 b12 
 31 
 a31 a32 b21 b22 
a b32 
 31 a32 b31
Cross product or Cartesian product

Dr.R.Gururaj Database Systems BITS Pilani, Hyderabad Campus


Rename operator

(rho)

Ex:  S ( b , b , b ) ( R)
1 2 3

Renames R to S and new names of attributes are b1, b2,


b3

 S ( R)

Renames R to S with same attribute names

Dr.R.Gururaj Database Systems BITS Pilani, Hyderabad Campus


Dr.R.Gururaj Database Systems BITS Pilani, Hyderabad Campus
Division ()
Used when we want to check the meeting of all the criteria

Let R(A, B) and S(A) TRS

Selects all values for B column in R which contains all values under A
in S.
Hence the no. column in T is only B.

Join: ( θ ) Used to join tuples from different tables based on same


condition. Result is new tuple with different arity.

D  DEPT Mgrssn = ssn EMP

Joins tuples from DEPT & EMP where Mgrssn in DEPT is equal to ssn
in EMP and stores the new tuples in relation D.

Dr.R.Gururaj Database Systems BITS Pilani, Hyderabad Campus


Division operator
R S T
A B B A
a1 b1 b1
T=R÷S a1
a1 b2 b2 a4
a1 b3 b3
a2 b2
a2 b3
a3 b1
a3 b2
a3 b3
a4 b3

Dr.R.Gururaj Database Systems BITS Pilani, Hyderabad Campus


Theta Join: θ
Joining tables on some condition.

Natural Join: is joining of tables on attributes in R and S having the


same label.

In the resulting relation only one column is listed.

Ex. D  DEPT EMP.

The joining is on common attribute with same name (Dept Name).

Dr.R.Gururaj Database Systems BITS Pilani, Hyderabad Campus


Employee Dept Employee * Dept

Name EmpID Dept Name Dept Name Manager Name EmpID Dept Name Manager

Harry 3415 Finance Finance George Harry 3415 Finance George

Sally 2241 Sales Sales Harriet Sally 2241 Sales Harriet

George 3401 Finance George 3401 Finance George

Harriet 2202 Sales Production Charles Hariet 2202 Sales Harriet

Dr.R.Gururaj Database Systems BITS Pilani, Hyderabad Campus


Inner Join (R S) An inner join only combines tuples from R and S if
they meet the conditions. Tuples that do not meet the conditions are not
showed in the final result. (This is the usual type of join).
Outer join: An outer join displays the tuples of one of the relations even if
there is no match for the tuple in the other relation.
Left outer join: (R S) In the result relations, in addition to all the
matching tuples from R and S, all the remaining tuples from left side
relation (R) are also showed. For these tuple from R, columns under S will
have null values(padding).
Right Outer Join: (R S) In the result relation, matching tuples will
occur from R & S. In addition all the tuples form S will also appear with
null values for the R attributes.
Full Outer join (R S) In the result, all tuples from R & S will appear
with null values for the other relations attributes.

Dr.R.Gururaj Database Systems BITS Pilani, Hyderabad Campus


Additional Relational Operations
Aggregate functions: Sum Average Max Min Count

Grouping:

The tuples of a relation are first grouped by the value of some attribute and
then aggregate functions are applied on individual groups.
Symbol used is – £

Ex. Dno £Count (ssn) (EMP)

The above expression first group the tuples in EMP table based on Dno, and
then applies count function on individual groups this will output no. of
employees in each department.
Result relation  Dno Count (SSn)

Dr.R.Gururaj Database Systems BITS Pilani, Hyderabad Campus


Examples

Look at the following relational schemas.

Vendor (vid, vname, city, category)


Part (pid, pname, price)
Supply (pid, vid, qty)

Dr.R.Gururaj Database Systems BITS Pilani, Hyderabad Campus


Vendor Supply
vid vname city cat pid vid qty
v1 Goel Delhi A p1 v1 2
v3 Hameed Kolkata C p1 v3 7
v6 Khanna Delhi C p5 v1 4
p5 v3 1

Part p5 v6 6

pid pname price


p1 Wheel 500
p2 Shaft 200
p5 Injector 600
p9 bolt 100

Dr.R.Gururaj Database Systems BITS Pilani, Hyderabad Campus


Get the partID and part name for those parts supplied by all
vendors from ‘KOLKATA’.

Dr.R.Gururaj Database Systems BITS Pilani, Hyderabad Campus


For each ‘A’ category vendor, give vendor ID, vendor name and
number parts that vendor has supplied.

Dr.R.Gururaj Database Systems BITS Pilani, Hyderabad Campus


Examples for data retrieval
using RA
1. Get the partID and part name for those parts not supplied
by any vendors from ‘Delhi’.
2. Give vendorID and name who are not supplying any part.
3. Give partID and name which are supplied by at least 5
vendors.
4. Give vendorID and name who supply all parts.
5. For each part give part ID name and total quantity
supplied by all vendors together.
6. Give vendorId and name for those who supply at least
one part with cost more than 400.
7. Get PartId and name for those parts not supplied by any
vendor from ‘Mumbai’

Dr.R.Gururaj Database Systems BITS Pilani, Hyderabad Campus


Tuple Relational Calculus

Relational Calculus is a formal query language for relational model


where we write one declarative expression to specify a retrieval
request and hence there is no description of how to evaluate the query.

A calculus expression specifies what is to be retrieved rather than how


to do it.

Hence, relational calculus is non–procedural language where as


relational algebra discussed in the previous section is procedural,
where we write sequence of operations to retrieve data.

Any expression for data retrieval written in relational algebra can also
be written in relational calculus and vice-versa.

Hence expression power of relational algebra and relational calculus is


same.
BITS Pilani, Hyderabad Campus
Tuple Rational Calculus(TRC) is based on specifying a number of tuple
variables.

Each tuple variable usually ranges over a particular database relation.


Variables can take values of individual tuples from the relation.
A simple relational calculus query is in the form-

{t | condition (t)}

t – tuple variable

condition (t) – is a conditional expression involving t.

Result is a set of all tuples that satisfy the conditions specified in


condition (t).

Dr.R.Gururaj Database Systems BITS Pilani, Hyderabad Campus


Ex. Find all employees whose salary is above 50,000

{t | EMP (t) and t. salary > 50,000}

Selects all tuples from EMP such that for each tuple selected, the salary
value is > 50,000.

The expression EMP(t) specifies from where the tuple t must be chosen.

Hence EMP relation in this case is known as a range relation.

Note: The above query retrieves all the attributes of relation EMP.

Dr.R.Gururaj Database Systems BITS Pilani, Hyderabad Campus


The universal (), and existential () quantifiers can be
applied to tuples.
Ex.:
{t.name, t age | EMP (t) and (d) (Dept (d)and d.dname =
‘Research’ and d.dno = t.dno )}

To retrieve the name and age of all employees who work


for ‘Research’ department.

If the tuple variable t occurs with  or  quantifiers the


variable is known as bound variable and otherwise called
as free variable.

Dr.R.Gururaj Database Systems BITS Pilani, Hyderabad Campus


Relational Completeness:

This notion is used to compare high level query


languages.

Any relational query language L is considered to be


relationally complete if we can express in L any query that
is expressed in relational algebra (RA) or relational
calculus (RC).

Dr.R.Gururaj Database Systems BITS Pilani, Hyderabad Campus


Summary
 What is a query language
 Formal query languages for Relational data model
 Basic concepts of Relational Algebra
 Operations in Relational Algebra
 Relational Calculus
 Examples

Dr.R.Gururaj Database Systems BITS Pilani, Hyderabad Campus


CS F212 Database Systems

Prof.R.Gururaj
BITS Pilani CS&IS Dept.
Hyderabad Campus
Conceptual Database Design
(ER Modeling) Ch.7
Content

ER Model
 Steps in Database Design Process
 Entities, Attributes, and Associations
 ER Notations
Examples
ER to Relational Mapping rules

Database Systems Prof. R.Gururaj BITS Pilani, Hyderabad Campus


Major Steps in Database
Design Process
Step 1: Requirement analysis
Understanding the domain
Identifying the data to be stored
Identifying the constraints
Step 2: Conceptual Database design
E-R modeling/UML
Step 3: Logical Database Design
Designing tables and relationships
Step 4: Refinement of schema
Step 5: Physical database design
Indexing
Clustering
 Storage formats
Database Systems Prof. R.Gururaj BITS Pilani, Hyderabad Campus
ER Modeling

ER Model is a popular high-level (conceptual) data


model.
It is an approach to designing Semantic Conceptual
schema of a Database.
ER model allows us to describe the data involved in
a real-world environment in terms of objects and
their relationships, which are widely used in design
of database.
ER model provides preliminary concepts or idea
about the data representation which is later modified
to achieve final detailed design.
Database Systems Prof. R.Gururaj BITS Pilani, Hyderabad Campus
ER Modeling

Important concepts/notions used in ER modeling are-

Entity is an object in real-world or some idea or


concept which can be distinguished from other objects.
Ex.: person, school, class, department, weather,
salary, temperature etc.
Entity has independent existence.

Each entity belongs to an Entity type that defines the


structure.

Entity Set is a Collection of similar objects.

Database Systems Prof. R.Gururaj BITS Pilani, Hyderabad Campus


Concepts used in ER
Attribute: reflects a property of an object or entity. We have following types
of attributes.
> Simple attribute
> Composite attribute
> Single valued attribute
> Multi-valued attribute
> Derived attribute
> Stored attribute
Key : Is an Attribute of an entity type whose value can uniquely identify an
entity in a set.

Database Systems Prof. R.Gururaj BITS Pilani, Hyderabad Campus


Concepts used in ER

Relationship: The association between entities is


known as relationship.

Domain of an attribute: The set of possible values is


known as domain of an attribute

Database Systems Prof. R.Gururaj BITS Pilani, Hyderabad Campus


Notations used in ER
Notations used in ER modeling are shown below.
Entity Type

Weak Entity Type

Relationship Type

Identifying Relationship type

Attribute

Database Systems Prof. R.Gururaj BITS Pilani, Hyderabad Campus


Notations used in ER

Key Attribute

Multivalued Attribute

Composite Attribute

Derived Attribute

Database Systems Prof. R.Gururaj BITS Pilani, Hyderabad Campus


Notations used in ER

E1 R E2
Total Participation of E1 in R

1 N Cardinality ratio 1; N for E1; E2 in R


E1 R E2

(min, max) Structural Constraint (min, max) on


R E Participation of E in R

Database Systems Prof. R.Gururaj BITS Pilani, Hyderabad Campus


Relationships in ER
Relationships

Manager Manages Employee

Manages
Manager Employee

Degree of a Relationship
Manages
• If there are two entity types involved it is a binary relationship type Manager Employee

• If there are three entity types involved it is a ternary relationship type


Sales Sells
Product
Assistant

• Unary relationships are also known as a recursive relationship Customer


Manages

Employee

• It is possible to have n-ary relationship (e.g. quaternary or unary)

Database Systems Prof. R.Gururaj BITS Pilani, Hyderabad Campus


Relationships in ER
Cardinality of a relationship
Relationships are rarely one-to-one.
For example, a manager usually manages more than one employee.
This is described by the cardinality of the relationship,
for which there are four possible categories.

1 is married to 1
Man Women
One to one (1:1) relationship
1 Manages m
Manager Employee
One to many (1:M) relationship

m 1
Studies
Student Course
Many to one (M:1) relationship

m n
Teaches
Lecturer Student
Many to many (M:N) relationship

Database Systems Prof. R.Gururaj BITS Pilani, Hyderabad Campus


Relationships in ER
Participation Constraint

If all the entities of an entity type are involved in the relationship then that entity type’s
involvement said to be total in that relationship. In the below relationship if each employee is
associated with at least one dept. Then the participation of EMP is total. Here, EMP works for
DEPT.
If, only few entities of the set are involved the participation is partial.

E1 R E2

EMP DEPT Association Role:


Worker Employer

* 1
EMP DEPT Multiplicity

Association Name & Direction:


Works_for
EMP DEPT

Database Systems Prof. R.Gururaj BITS Pilani, Hyderabad Campus


Assume a scenario of Clubs (like- Dance Club, Music Club, Photography Club etc.)
in an educational Institution, and we need to design a database. The description is
follows.
Each Student has name, roll# (unique), address, contact (more than one contact
possible), and branch.
There exist clubs (for specialized activities like Dance, Music, Photography etc.),
each club has name (unique), start_date, Faculty-Incharge, Funds available.
Clubs conduct events. Each event has start-date, end-date, description, budget.
Different clubs may conduct different events during same dates. But no single club
will conduct more than one event at a given point of time i.e., a club cannot conduct
more than one event with same start and end dates. One event is conducted by one
club only. Note that Events will not have any IDs for.
Students can become cub members. One student can be member of more than one
club. Some may not have any membership.
Students can become club office bearers (even for clubs where they don’t have
membership) in specific role like-secretary, treasures etc. One student can be office
bearer for only one club. We capture info about present office bearers only

Database Systems Prof. R.Gururaj BITS Pilani, Hyderabad Campus


ER to Relational Mapping
(Ch. 8 of T1)
Content
1. Mapping Regular Entity types
2. Mapping Weak Entity types
3. Mapping 1:1 Relationships
4. Mapping 1:N Relationships
5. Mapping N:M Relationships
6. Mapping Multivalued and Complex
attributes

Database Systems Prof. R.Gururaj BITS Pilani, Hyderabad Campus


Mapping entity types
1. Mapping of Regular Entity Types.

For each regular (strong) entity type E in the ER


schema, create a relation R that includes all the
simple attributes of E.

Choose one of the key attributes of E as the


primary key for R.

If the chosen key of E is composite, the set of


simple attributes that form it will together form
the primary key of R.

Database Systems Prof. R.Gururaj BITS Pilani, Hyderabad Campus


2. Mapping of Weak Entity Types

For each weak entity type W in the ER schema


with owner entity type E, create a relation R &
include all simple attributes (or simple
components of composite attributes) of W as
attributes of R.
Also, include as foreign key attributes of R the
primary key attribute(s) of the relation(s) that
correspond to the owner entity type(s).
The primary key of R is the combination of the
primary key(s) of the owner(s) and the partial key
of the weak entity type W, if any.
Database Systems Prof. R.Gururaj BITS Pilani, Hyderabad Campus
Mapping Relationship types
3. Mapping of Binary 1:1 Relation Types

For each binary 1:1 relationship type R in the ER


schema, identify the relations S and T that correspond to
the entity types participating in R.

Database Systems Prof. R.Gururaj BITS Pilani, Hyderabad Campus


There are three possible approaches:
1. Foreign Key approach: Choose one of the relations-say S-
and include a foreign key in S that refers to the primary key
of T. It is better to choose an entity type with total
participation in R in the role of S.
2. Merged relation option: An alternate mapping of a 1:1
relationship type is possible by merging the two entity
types and the relationship into a single relation. This may
be appropriate when both participations are total.
3. Cross-reference or relationship relation option: The third
alternative is to set up a third relation R for the purpose of
cross-referencing the primary keys of the two relations S
and T representing the entity types.

Database Systems Prof. R.Gururaj BITS Pilani, Hyderabad Campus


4. Mapping of Binary 1:N Relationship Types.

 For each regular binary 1:N relationship type R,


identify the relation S that represent the
participating entity type at the N-side of the
relationship type.
 Include as foreign key in S the primary key of
the relation T that represents the other entity
type participating in R.
 Include any simple attributes of the 1:N relation
type as attributes of S.

Database Systems Prof. R.Gururaj BITS Pilani, Hyderabad Campus


5. Mapping of Binary M:N Relationship Types.

For each regular binary M:N relationship type R,


create a new relation S to represent R.

Include as foreign key attributes in S the primary


keys of the relations that represent the participating
entity types; their combination will form the primary
key of S.

Also include any simple attributes of the M:N


relationship type (or simple components of
composite attributes) as attributes of S.
Database Systems Prof. R.Gururaj BITS Pilani, Hyderabad Campus
Mapping Multivalued
attributes
6. Mapping of Multivalued attributes.

For each multivalued attribute A, create a new


relation R.
This relation R will include an attribute
corresponding to A, plus the primary key attribute
K-as a foreign key in R-of the relation that
represents the entity type of relationship type that
has A as an attribute.
The primary key of R is the combination of A and K.
If the multivalued attribute is composite, we include
its simple components.
Database Systems Prof. R.Gururaj BITS Pilani, Hyderabad Campus
Exercise-1
Look at the following description related to Research and Sponsored Projects in an
Educational Institution.
Institute has some sponsored Projects. Projects will have one Faculty as Principal
Investigator (PI), and can have one or more faculty member as Co-PIs. Some
projects will not have any Co-PI. A Project has ProjectID (unique), Project name,
Budget, and Duration as attributes. Faculty are identified by FacultyID (unique)
and have Name, Dept , Designation as other attributes. A Project is funded by only
one Funding agency (like UGC, DIT, DST etc.) which has- Agency name (unique),
Head, Location (with street, city, and state as sub components). A faculty, as a PI
can have zero to any number of projects. Similarly a faculty as a Co-PI can have
zero to any number of projects. A funding agency might have funded one or more
projects.
Draw an ER diagram for the above requirement. Assume necessary data which is
missing in the question. The model should include- Entity types, relationships, min-
max, cardinality, participation, and other relevant constraints.

Database Systems Prof. R.Gururaj BITS Pilani, Hyderabad Campus


Database Systems Prof. R.Gururaj BITS Pilani, Hyderabad Campus
Database Systems Prof. R.Gururaj BITS Pilani, Hyderabad Campus
Exercise-2
Assume that we need to capture the data about Banking system described below.

i) We capture details of banks; like- name (unique) (Ex. SBI, Canara bank etc.) ,
category (private or public sector) , headquarters (city) , start year, and CEO.
ii) A bank (like SBI, Canara Bank, Union bank etc.), will have branches identified by
branch code. Branch codes are unique within a bank, but may repeat for different banks.
(Ex. SBI and Union Bank both may have branches with code ‘1126’. But no bank can
have two branches with same code.
iii) Each branch will have street, city, manager (name, Designation, contact as sub-
components), turnover as other attributes apart from branch code.
iv) Banks have accounts with unique account number (with in the bank) and customer
name, start_date, cust_address, cust_contact (multiple contacts possible), type, balance
as other attributes. Accounts are attached to banks, but not to branches. There is no
concept of joint account. Every Bank will have at least 1000 accounts. Different banks
can have accounts with same account number. But no bank can have two accounts with
same account number. (Ex. Acct# 11267 can be there in SBI and Corporation bank as
well.). One account is associated with only one bank .
Now, draw the ER diagram for the above description. Indicate- cardinality, keys,
attributes, min-max, and participation constraints for entity-types involved in the
relationships. If found missing, assume necessary data.

Database Systems Prof. R.Gururaj BITS Pilani, Hyderabad Campus


Database Systems Prof. R.Gururaj BITS Pilani, Hyderabad Campus
Database Systems Prof. R.Gururaj BITS Pilani, Hyderabad Campus
Summary
 Various steps in database design process
 What is ER modeling
 Concepts and notations used in ER
Guidelines for mapping ER to Relational schemas

Database Systems Prof. R.Gururaj BITS Pilani, Hyderabad Campus


CS F212
Database Systems
(Tut-1)
Prof.R.Gururaj
BITS Pilani CS&IS Dept.
Hyderabad Campus
Exercise
Assuming a situation, where we need to capture data like-
sid, name, age, cgpa, branch; for some students.
Further, we need to query-
1. name for a given sid
2. Cgpa for given sid
3. All students in a branch like- CSE, EEE etc.

If no database system is available, and if you are asked to


implement a system for above needs using Java,
How would you proceed?
You can use- objects/files/methods etc.
But no database facility.
How do you SOLVE this?

Prof.R.Gururaj CSF 212 Database Systems Tutorial BITS Pilani, Hyderabad Campus
What happens if the query needs change?
How to enforce constraints?
What Security is available?

Why it is difficult to implement such data centric systems


without a DBMS.

Prof.R.Gururaj CSF 212 Database Systems Tutorial BITS Pilani, Hyderabad Campus
Traditional file Systems as Databases

If we take the example of savings bank enterprise,


information about customers and savings accounts need to
be stored.

One way to keep the information on computers is to store


in files provided by operating system (OS).

Prof.R.Gururaj CSF 212 Database Systems Tutorial BITS Pilani, Hyderabad Campus
Disadvantages of the above approach
 Data redundancy leading to inconsistency.
 Difficulty in accessing data (possible operations need to
be hard- coded in programs).
 Data is scattered across different files.
 Integrity problems.
 Atomicity problems due to non availability of transaction
management.
 Concurrency control is not there.
 Security provided by the OS is not adequate.
 The above shortcomings prompted the development of
DBMS.

Prof.R.Gururaj CSF 212 Database Systems Tutorial BITS Pilani, Hyderabad Campus
Main characteristics of database approach versus file-
processing approach

 Self-describing nature of database systems


 Insulation between programs and data
 Support multiple views of data
 Sharing of data and multiuser transaction
processing

Prof.R.Gururaj CSF 212 Database Systems Tutorial BITS Pilani, Hyderabad Campus
Advantages of using DBMS
 We can control the degree of redundancy thus avoiding inconsistency.
 Access control privileges to different user categories/groups can be
specified.
(Security and Authorization subsystem)
 Persistent storage for program objects.
 DBMS provides multiuser interface to the underlying database.
> Through SQL commands at SQL prompt.
> Through programming languages like JAVA, C, C++, PHP etc.
> Through form-based interface.
 Integrity constraints like- unique key, foreign key, primary key, NOT
NULL etc. can be specified on the data.
 Supports efficient backup and recovery mechanisms.
 Supports transaction management.
 Provides data independence.

Prof.R.Gururaj CSF 212 Database Systems Tutorial BITS Pilani, Hyderabad Campus
CS F212
Database Systems
(Tut-2)
Prof.R.Gururaj
BITS Pilani CS&IS Dept.
Hyderabad Campus
DBMS Client-Server
Architecture

DBMS and Client-server Architectre:

1. Centralized:

2. Client server:
two-tier
three-tier

(Covered in Section 2.5 of the Textbook)

Prof.R.Gururaj CSF 212 Database Systems Tutorial BITS Pilani, Hyderabad Campus
Prof.R.Gururaj CSF 212 Database Systems Tutorial BITS Pilani, Hyderabad Campus
Prof.R.Gururaj CSF 212 Database Systems Tutorial BITS Pilani, Hyderabad Campus
Prof.R.Gururaj CSF 212 Database Systems Tutorial BITS Pilani, Hyderabad Campus
1. Advantages of Client-server architecture over Centralized architecture.

2. Advantages of Three-tier architecture over two-tier architecture.

Both in the context of DBMS.

Prof.R.Gururaj CSF 212 Database Systems Tutorial BITS Pilani, Hyderabad Campus
Classification of DBMS

1. Based on Data Model:


(i) Relational (RDBMS)
(ii) Network
(iii) Hierarchical
(iv) Object (ODBMS)
(v) Object relational (ORDBMS)

2. Based on number of users:


(i) Single-user (ii) Multiuser

3. Based on number of sites:


(i) Centralized (ii) Distributed

4. XML Data model:

(Covered in Sec.2.6 of the textbook)


Prof.R.Gururaj CSF 212 Database Systems Tutorial BITS Pilani, Hyderabad Campus
CS F212
Database Systems
(Tut-3)
Prof.R.Gururaj
BITS Pilani CS&IS Dept.
Hyderabad Campus
Relational Constraints
Constraints are restrictions on data of a relation.

Domain level Constrains – Format of data Ex.


Character numeric etc.
Semantic – Not
NULL etc.
Entity integrity constraints – Primary key,
unique key

Referential integrity constraints– Foreign key


(this is already explained in lecture session)

Prof.R.Gururaj CSF 212 Database Systems Tutorial BITS Pilani, Hyderabad Campus
Referential integrity

The Referential Integrity constraint is specified


between two relations and is used to maintain
consistency among the tuples of two relations.
FK
PK
R1 R2
a b c p q r

c in R1 refers to p in R2

Prof.R.Gururaj CSF 212 Database Systems Tutorial BITS Pilani, Hyderabad Campus
Actions need to be taken when FK is set ,
on operations like update, insert, and delete.

FK
PK
R1 R2
a b c p q r

c in R1 refers to p in R2

If insert a tuple in R1 where the value for c is not in p of R2, then don’t allow.

What if a tuple in R2 is deleted:


Cascade, don’t allow, set to default, set to null.

What if update on R2’s p happens:


Cascade, don’t allow, set to default, set to null.

Prof.R.Gururaj CSF 212 Database Systems Tutorial BITS Pilani, Hyderabad Campus
Operations on Relations and
constraints
The following table indicates the constraints need to be taken care while
performing certain operations on a relation.

Operation on relations Constraints need to be


taken care
Insert Null, Not Null, PK, unique, FK,
format, Domain

Delete FK

Update Null, Not Null, PK, unique, FK,


domain, and Semantic

Prof.R.Gururaj CSF 212 Database Systems Tutorial BITS Pilani, Hyderabad Campus
Operations on Relations and
constraints
Emp FK Dept
eid ename age dno dnum dname dloc
101 kiran 28 10 10 Mark Che
105 Gopi 32 20 20 Prod Hyd
121 Ahmed 29 20 30 Acct Bgl
136 John 28 20
138 Mike 30 30 Operation Care for constraints
143 Ali 38 10 Insert PK, Unique, null, notnull,
format
Operation Care for constraints Update PK, Unique, null, notnull,
Insert PK, Unique, null, notnull, format, FK
format, FK Delete FK
Update PK, Unique, null, notnull,
format, FK
Delete No care
Prof.R.Gururaj CSF 212 Database Systems Tutorial BITS Pilani, Hyderabad Campus
Defining FKs

Ex.1:Create following tables with PK and FKs set.

EMP(eid int, ename varchar(10), eage int, dno int)


// PK is eid, dno is FK to dnum in DEPT table

DEPT(dnum int, dname varchar(10), dloc varchar(10))


// dnum is PK

Prof.R.Gururaj CSF 212 Database Systems Tutorial BITS Pilani, Hyderabad Campus
Create table DEPT(dnum int primary key, dname
varchar(10), dloc varchar(10));
OR
Create table DEPT(dnum int, dname varchar(10),
dloc varchar(10), primary key(dnum));
=======================
Create table EMP (eid int primary key, ename varchar(10),
eage int, dno int, foreign key(dno) references
DEPT(dnum));

Prof.R.Gururaj CSF 212 Database Systems Tutorial BITS Pilani, Hyderabad Campus
Defining FKs with circular
reference between tables

Ex.2:Create following tables with PK and FKs set.

EMP(eid int, ename varchar(10), eage int, dno int)


// PK is eid, dno is FK pointing to dnum in DEPT table

DEPT(dnum int, dname varchar(10), dloc varchar(10), hod


int )
// dnum is PK, hod is FK pointing to eid in EMP table

Prof.R.Gururaj CSF 212 Database Systems Tutorial BITS Pilani, Hyderabad Campus
Since EMP has a FK pointing to DEPT, and DEPT has a FK pointing to EMP, There
exists circular dependency w.r.t., FKs. Hence it is not possible to create either of
them first, it throws an error.

We take following approach.


First create tables EMP and DEPT only with PK and set FKs later.

SQL>Create table DEPT(dnum int primary key, dname varchar(10), dloc varchar(10),
hod int );
SQL>Create table EMP (eid int primary key, ename varchar(10), eage int, dno int);

SQL> alter table EMP add constraint EMP_FK foreign key (dno) references
DEPT(dnum);
SQL> alter table DEPT add constraint DEPT_FK foreign key (hod) references
EMP(eid);

Prof.R.Gururaj CSF 212 Database Systems Tutorial BITS Pilani, Hyderabad Campus
Defining self referencing FKs

Ex.3:Create following table with PK and FKs set.

EMP(eid int, ename varchar(10), eage int, manager int )

// PK is eid, manager is FK to eid in EMP it self, indicating


that a given employee is managed by which other
department.

Prof.R.Gururaj CSF 212 Database Systems Tutorial BITS Pilani, Hyderabad Campus
SQL>Create table EMP (eid int primary key, ename varchar(10), eage int, manager
int, foreign key(manager) references EMP (eid) );

Prof.R.Gururaj CSF 212 Database Systems Tutorial BITS Pilani, Hyderabad Campus
Designing table structures

Ex.4: Design a relational DB schema (pictorial representation)


for the following need.
Assume that we need to capture data for:
A. Faculty with attributes- facultyID (unique), faculty name ,
faculty designation, and department to which faculty belongs to.
B. Course with fields like – coursed (unique), course name ,
credits, and faculty teaching that course. (we capture only
current sem teaching assignment, not the history).
Note that some courses can have one or more pre-requisite
courses, and same course may be pre-requisite for many
courses.
C. Department with dname (unque), dloc , hod indicating the
faculty heading the department.
Prof.R.Gururaj CSF 212 Database Systems Tutorial BITS Pilani, Hyderabad Campus
Prof.R.Gururaj CSF 212 Database Systems Tutorial BITS Pilani, Hyderabad Campus
CS F212
Database Systems
(Tut-4)
Prof.R.Gururaj
BITS Pilani CS&IS Dept.
Hyderabad Campus
SQL

Assume we have following relations:

DEPT (dnum, dname, dloc)


EMP (eid, ename, esal, dno, city)
//dno FK to dnum of DEPT ;
PROJ(pnum, pname, dep)
//dep is FK to dnum of DEPT indicating the department
that owns the project
EMP_PROJ (eno, pno, hrs)
// eno FK to eid of EMP & pno is FK to pnum of PROJ

Prof.R.Gururaj CSF 212 Database Systems Tutorial BITS Pilani, Hyderabad Campus
Now write SQL queries for the following.

1. Get the eid, ename, esal for those working in


departments located in ‘Chennai’.
(i)using EXISTS clause
(ii) using IN clause
2. Get pnum and pname for those not having
any employee working on them.
(i) Using NOT EXISTS
(ii) Using NOT IN

Prof.R.Gururaj CSF 212 Database Systems Tutorial BITS Pilani, Hyderabad Campus
3.Get eid and ename for those not working on
any project owned by ‘HR’ department.
(i) using NOT IN
(ii) Using NOT EXISTS (Homework)
4. Get eid, ename and esal for those working on
Project with name – ‘Cloud’.
(i) Using EXISTS
(ii) Using IN (Homework)

Prof.R.Gururaj CSF 212 Database Systems Tutorial BITS Pilani, Hyderabad Campus
5. Get for each department dnum, dname which
do not own any project.
(i) Using set opertation MINUS
(ii)Using NOT IN
(iii) (ii) Using NOT EXISTS (Homework)

6. Get pnum and pname for those which do not


have any employee from ‘DELHI’ working on it.
(assume pnames are unique)
Any approach is OK.

Prof.R.Gururaj CSF 212 Database Systems Tutorial BITS Pilani, Hyderabad Campus
7.Get eid and ename for those belong to the
‘HR’ dept and not working on any project.
(i) Using NOT EXISTS (Homework)
(ii) Using MINUS operation

Prof.R.Gururaj CSF 212 Database Systems Tutorial BITS Pilani, Hyderabad Campus
CS F212
Database Systems
(Tut-5)
Prof.R.Gururaj
BITS Pilani CS&IS Dept.
Hyderabad Campus
Look at the following relational schemas.
Vendor (vid, vname, city, category)
Part (pid, pname, price)
Supply (pid, vid, qty)

Prof.R.Gururaj CSF 212 Database Systems Tutorial BITS Pilani, Hyderabad Campus
Now for the following, give both SQL and
Relational Algebraic query statements:

1. Get vid, vname for those not supplying any part.


2. Get pid, pname which are not supplied any vendor.
3. Get for Delhi based vendors vid and name if they supply
at least 3 parts.
4. Get vid, vname for those vendors not supplying
any part with price greater than 3000.
5. For each part get pid, pname and number of
‘MUMBAI’ based vendors supplying it.
6. Get pid, pname for those supplied by all vendors.
7. For each vendor give vid and vname and number of parts
they sulpply(with price > 500).
8. Get vid, and vname for those not supplying part by name
‘bolt’.

Prof.R.Gururaj CSF 212 Database Systems Tutorial BITS Pilani, Hyderabad Campus
CS F212
Database Systems
(Tut-6)
Prof.R.Gururaj
BITS Pilani CS&IS Dept.
Hyderabad Campus
Exercise-1
Look at the following description related to Research and Sponsored Projects in an
Educational Institution.
Institute has some sponsored Projects. Projects will have one Faculty as Principal
Investigator (PI), and can have one or more faculty member as Co-PIs. Some
projects will not have any Co-PI. A Project has ProjectID (unique), Project name,
Budget, and Duration as attributes. Faculty are identified by FacultyID (unique)
and have Name, Dept , Designation as other attributes. A Project is funded by only
one Funding agency (like UGC, DIT, DST etc.) which has- Agency name (unique),
Head, Location (with street, city, and state as sub components). A faculty, as a PI
can have zero to any number of projects. Similarly a faculty as a Co-PI can have
zero to any number of projects. A funding agency might have funded one or more
projects.
Draw an ER diagram for the above requirement. Assume necessary data which is
missing in the question. The model should include- Entity types, relationships, min-
max, cardinality, participation, and other relevant constraints.

Prof.R.Gururaj CSF 212 Database Systems Tutorial BITS Pilani, Hyderabad Campus
Prof.R.Gururaj CSF 212 Database Systems Tutorial BITS Pilani, Hyderabad Campus
Exercise-2
Assume that we need to capture the data about Banking system described below.

i) We capture details of banks; like- name (unique) (Ex. SBI, Canara bank etc.) ,
category (private or public sector) , headquarters (city) , start year, and CEO.
ii) A bank (like SBI, Canara Bank, Union bank etc.), will have branches identified by
branch code. Branch codes are unique within a bank, but may repeat for different banks.
(Ex. SBI and Union Bank both may have branches with code ‘1126’. But no bank can
have two branches with same code.
iii) Each branch will have street, city, manager (name, Designation, contact as sub-
components), turnover as other attributes apart from branch code.
iv) Banks have accounts with unique account number (with in the bank) and customer
name, start_date, cust_address, cust_contact (multiple contacts possible), type, balance
as other attributes. Accounts are attached to banks, but not to branches. There is no
concept of joint account. Every Bank will have at least 1000 accounts. Different banks
can have accounts with same account number. But no bank can have two accounts with
same account number. (Ex. Acct# 11267 can be there in SBI and Corporation bank as
well.). One account is associated with only one bank .
Now, draw the ER diagram for the above description. Indicate- cardinality, keys,
attributes, min-max, and participation constraints for entity-types involved in the
relationships. If found missing, assume necessary data.

Prof.R.Gururaj CSF 212 Database Systems Totorial BITS Pilani, Hyderabad Campus
Prof.R.Gururaj CSF 212 Database Systems Tutorial BITS Pilani, Hyderabad Campus
Exercise:3 (if time permits)
Look at the following Database schema.
Student(sid, sname, sbranch)
Course(cid, cname, credits)
Student_Course(sid, cid, grade)

Now, write Relational Algebra and SQL (both) queries for the following.

1.Get the sid and the sname for those students who have got A grade in
’Networks’ course.
2.Get the cid and cname for those courses registered by all students from
CIVIL branch.
3. Get the sid and sname for those from CSE and also have registered for
at least 4 courses

Note: No need to rename attributes in results. Do not define VIEWS. Do not


use Outer joins.

Prof.R.Gururaj CSF 212 Database Systems Tutorial BITS Pilani, Hyderabad Campus

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy