Unit-I & II DBMS

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 176

DATABASE MANAGEMENT SYSTEM

(DBMS)

SHANKAR THAWKAR
DEPARTMENT OF INFORMATION TECHNOLOGY
Content
 Basic Definitions
 Popular DBMS/RDBMS systems
 Applications of DBMS
 Data abstraction and Three level architecture of DBMS
Basic Terminology
• Data- It is a basic raw facts or set of values
RollNo CT-1 Marks
1 19
2 15
3 20
4 10
5 16

• Information – Process data is called information


Basic Terminology
• Database- collection of interrelated records
• DBMS- It is a software that provides a tools for creation and manipulation of
database.
OR
It is a collection of interrelated data and set of programs to access and
manipulate those data.
Popular DBMS/RDBMS Systems
 DBMS-
 Sybase
 Informix
 Dbase

 RDBMS
 Oracle ------ Oracle 7, Oracle 9i, Oracle 10g, Oracle 12c.
 MySQL
 SQL Server
 Mongo DB
 Bigtable ( developed and use by Google)
 IBM DB2
 SQLite ( for mobiles)
Database Applications
 Database Applications:
– Banking : all transactions
– Airlines : reservations, schedules
– Universities : registration, grades
– Sales : customers, products, purchases
– Manufacturing : production, inventory, orders, supply chain
– Human resources: employee records, salaries, tax deductions
– Healthcare

 Databases touch all aspects of our lives


Data Abstraction / 3-Level Architecture of database
 Data abstraction – hiding essential details.
 There are three types of abstraction as shown below-
 Physical level-
 It is also called as internal level.
 It is the lowest level of data abstraction. It describe how the data is actually stored in the
database.
 Logical Level-
 It is also called as conceptual level
 It is the next higher level of data abstraction. It describes what data is stored in database
and what type of relationships exist among the data.
 View Level-
 It is also called as external level
 It is theStruct
highest level of data abstraction. It describe the part of entire database.
Customer
• Ex- {
String Name;
String street;
String city ;
float salary;
}
Thank You
DATABASE MANAGEMENT SYSTEM

LECTURE-2
Content
 Instances and Schemas
 Data Independence
 Data Models
 E-R Model
 Relational Model
Instances and Schemas

 Instance – The amount of information stored in a database at a particular moment of


time.

 Schema – the logical structure of the database is called schema.

Example-
int a =10;

 There are two types of schemas-


 Physical schema
 Logical schema
Data Independence
 The ability to modify schema at one level without affecting
the schema at another level.

 There are two types of data independence-


– Physical data independence
– Logical data independence
Data Models
• A model is a collection of tools for describing
– data
– data relationships
– data semantics
– data constraints
Data Models
 There are following types of models-
 Entity-Relationship model
 Relational model
 Other models:
 object-oriented model
 semi-structured data models
 Older models: network model and hierarchical model
Entity-Relationship Model
• It consist of objects called entities and relationship among entities.
• An entity is a real world object which is distinguishable from other objects.
– Example- Car, person, customer, bank etc
• A relationship is an association between entities.
• Attribute : Each entity is characterized by set of attributes

Teacher Student

Emp Dept
Relational Model
• It uses tables for the presentation of data and relationship among
the data. Attributes

customer- customer- customer- account-


Customer
name street city number
-id
192-83-7465 Johnson
Alma Palo Alto A-101
019-28-3746 Smith
North Rye A-215
192-83-7465 Johnson
Alma Palo Alto A-201
321-12-3123 Jones
Main Harrison A-217
019-28-3746 Smith
North Rye A-201
Thank You
DATABASE MANAGEMENT SYSTEM

LECTURE
Content
 Entity-Relationship Model
 Entity
 Types of attributes
 Entity and Relationship set
 Mapping constraints
Entity-Relationship (E-R) model
Basic Concept-

 Entity – An entity is a real world object which is distinguishable from other


objects. Ex- person, car, bank etc.
 Entity set- Set of entities of the same type
 Eg. Emp ( Name, age, salary )

– Each entity is described by set of attributes.


 There are following types of attributes-

1. Simple and Composite attribute

2. Single valued and multivalued attributes

3. Derived attributes

4. Null attribute
Relationship set
• A relationship is an association between entities.
• The entities “Professor “ and “ Class” are participants in the relationship
• The relationship degree is indicated by number of participant entities.

Professor Teaches Class

• In Unary relationship association is maintained within a single entity.

Course

Prerequisite
• A binary relationship exist when two entities are associated.

• A ternary relationship exist when three entities are associated.

Contributor CRF Recipient

fund
Mapping Constraints

 Mapping cardinalities
 Existence dependencies
Mapping cardinalities-

• One-to-one

• One-to-many
Mapping cardinalities-

• Many-to-one

• Many-to-Many
Existence Dependencies

• If the existence of entity x depends on the existence of entity y, then x is said to


be existence dependent on y.
• So, y is called dominant entity and x is called sub-ordinal entity.
• If y is deleted x is deleted

Loan L-P Payment


Key Concept
• Keys are used to uniquely identify each entity in an entity set.
• There are following types of keys-
1. Super key- It is a combination of one or more attributes which are used to uniquely identify
each entity in entity set. It contain extraneous attributes.
eg. Student ( Rollno, Name, address, Branch)
• In student entity-
– Rollno- super key , Rollno+Name  super key,
– So by default all the attributes of a relation form a super key.

2. Candidate key - It is a minimal super key. It does not have extraneous attributes.
• In student entity-
– RollNo Candidate key
– RollNo+name  Is not a candidate key because it contain extraneous attribute “name” but it is a super key

3. Primary key and Alternate key – If the entity has more than one candidate key then ,
designer will select one of the key has primary key and remaining keys become alternate keys.
Note -> Key is a super key, a candidate key and primary key is also a super key.
E-R diagrams
 It is used to represent the logical design of the database graphically.
 It uses following Notations
DATABASE MANAGEMENT SYSTEM

LECTURE
( E-R DIAGRAMS)
Q1. Construct an E-R diagram for following –
An operator can work on many machines and each machine has many operators. Each machine belongs to one
department but a department can have many machines. Each machine can be manufactured by many companies
and a company can manufactured many machines.
Q2. Construct an E-R diagram for car insurance company that has set of customers, each of whom own one
or more cars. Each car has associated with it zero to any number of recorded accidents.
Q3. Construct an E-R diagram for hospital with a set of patients and a set of medical
doctors. Associated with each patient a log of various test and examinations
conducted.
Q4. Construct an E-R diagram for University application where-
 A University has many departments
 Each department has multiple instructors. One among them is the head of department
 An instructor belongs to only one department
 Each department offers multiple courses, each of which taught by a single instructor.
 A student many enroll for many courses offered by different departments.
Q5. Construct an E-R diagram for Book Club -
 The book club has members. The book club sells books to its members. The member places orders for book, which the book club
fulfills. Each order contain one or more than one book. These books are written by authors. The publisher publishes the book.
An author can write more than one book and a book can have more than one author. A publisher can publish many books. A
member can place more than one order or many not. The book club sells many books.
Q6. Construct an E-R model for a company-
 The company owns several divisions but each division belongs to the same company
 A division can operate several projects but each project belongs to a single division.
 A division has many employees but each employee assign to only one division.
 An employee might be assign to many projects and each project has at least one employee assign to it.
 Each division is mange by one of its employee.
 An employee man or may not have dependent.
 An employee has many skills and each skill is acquired by many employees
Thank You
DATABASE MANAGEMENT SYSTEM

LECTURE
Strong and Weak entity set
 Strong Entity set –
– An entity set which has a sufficient attributes to form a primary key
is called strong entity set

 Weak Entity set – An entity set which has a sufficient attributes to form a
primary key is called strong entity set
Specialization and Generalization
 Specialization -
 The process of defining the sub-classes of an entity is called specialization
 The entity is called Super-class and the relationship is called super-class
sub-class relationship
 Sub-classes inherits the properties of super-class
 The set of sub-classes that form a specialization is defined on the basis of
some distinguishing characteristics.
 It is defined by and labeled as “ ISA”
 Example of Specialization-
 The entity “ employee “ divided into-
sub-classes { Secretory , Engineer, Technician}
– Based on the distinguishing characteristics “ Job-type “
Generalization
 It is the reverse process of specialization
 In this an entities having common attributes are grouped together
to form a super-class
Example-
car { v_id, max_speed, price, licence_no}
truck{ v_id, price, tong_age, licence_no}
• These form super_class as “ Vehicle”
DATABASE MANAGEMENT SYSTEM

LECTURE
Content
 Advantage of DBMS over file system
Advantages of DBMS over File system
1. Data redundancy and inconsistency
 In case of file system, same information is stored in different files this is called data
redundancy. This is not the case in DBMS.

2. Difficulty in accessing data


 In file system , we have to write new program for every new task.

3. Data Isolation
 In file system data is stored in different files having different file formats.
 It means data in scattered form, so writing a new application is a difficult task.
Advantages of DBMS over File system
4. Integrity problem
 Data stored in database must satisfy some constraints. These constraints are
specified in some appropriate codes. So in case of file system, for new
constraints we have change the program to enforce them.
5. Atomicity Problem-
 DBMS ensure atomicity property while file system does not.
 In case of failure's DBMS ensure database remains in consistent state.
Advantages of DBMS over File system

6. Security-
 DBMS ensure user level, table level and column level security but It is
very difficult to implement in file system.

7. Concurrency control-
 When the transactions are executed concurrently, DBMS ensure that
database remain in consistent state but it is very difficult to implement
in file system.
Thank You
DATABASE MANAGEMENT SYSTEM

LECTURE
Content
 Database languages
 Database users
 Database Administrator
 Application Architectures
Database Languages
DBMS support following languages-
1. Data definition language (DDL)
 It is used to specify schema definition
 It provide statements for the creation of an objects –
 tables, users, views etc
Database Languages
2. Data Manipulation Language (DML)
 It provide statements for the manipulation of database.
 Insert, delete and update

 There are two types of DMLs-


a) Procedural DML-
– In this we have to specify what to get and how to get.

b) Declarative DML
– It is a non-procedural DML. SQL support non-procedural DML
Database Users
Users are differentiated by the way they expect to interact with the
system

 Application programmers
 Sophisticated users
 Specialized users
 Naïve users
Database Administrator
 A person who has overall control of the database
 It has following responsibilities-
a) Schema definition
• DBA execute DDL statement for creating schema definition.
b) Storage structure and access method definition
• DBA define data structure for storing data and method for accessing
those data.
c) Granting user authority to access the database
• DBA is responsible for granting privileges to users for accessing data.

d) Backup and recovery


• DBA is responsible for taking backup and restoring system from failure
Application Architectures
Thank You
DATABASE MANAGEMENT SYSTEM

LECTURE
Content
• The overall system architecture is partitioned into three parts-
1. Query Processor
2. Storage Manager
3. Disk Manager
Overall System Structure
The overall system architecture is partitioned into
three parts-
1. Query Processor
2. Storage Manager
3. Disk Manager

Query processor : It consist of –


DDL Interpreter – It interpret the DDL
statement and record the definition in
data dictionary
DML Compiler- It convert DML
statements into low-level statements
that the query evaluation engine
understand.
Query evaluation engine- It execute the
low-level statements.
Overall System Structure
Storage Manager : It consist of-

• Buffer- It fetch the data from disk into


memory
• File manager- It allocate disk storage and
data structure require to store the data
• Transaction manager- Ensure ACID
properties.
• Authorization manager- Ensure database
integrity and permissions to access data

Disk Manager : It consist of-

• Data file – It contain database


• Data Dictionary – Contain meta data. i.e.
Data about data
• Indices- use for fast accessing of data
• Statistical data- used for selection of
efficient query execution plan.
Thank You
DATABASE MANAGEMENT SYSTEM

UNIT-II
RELATIONAL MODEL & RA
Relational Data Model
• In relational database data and relationship is maintained in the form of tables.
• Each table has a unique name.
• Each row of table is called tuple , which represent relationship among set of values.

Student
RollNo Name Address
101 Ravi agra
102 Vijay agra
103 Shan Mathura

Relation r=(101, Ravi, Agra)


Relational Data Model
Mathematical definition,
Let D1, D2, …. Dn be the domain of attributes then a relation r is a subset of D1 x D2 x … x Dn

Thus a relation is a set of n-tuples (a1, a2, …, an) where each ai  Di

• Example: if
RollNo= {101, 102, 103}
Name = {Ravi, Vijay, Shan}
Address = {Agra, Agra, Mathura}

Then r = { (101, Ravi, Agra),


(102, Viajy, Agra),
(103, Shan, Mathura)}

is a relation over RollNo x Name x Address


Attribute Types
• Each attribute of a relation has a name
• The set of allowed values for each attribute is called the domain of
the attribute
• Attribute values are (normally) required to be atomic, that is,
indivisible
– E.g. multivalued attribute values are not atomic
– E.g. composite attribute values are not atomic
• The special value null is a member of every domain
Relational Schema
• Let A1, A2, …, An be the attributes then-
Relational Schema R is defined as-
R = (A1, A2, …, An )
Example-
Student =(RollNo, Name, Address)

• r(R) is a relation on the relation schema R

• Degree of a relation- Number of attributes in a relation

• Cardinality of a relation- number of tuples in a relation.


Relational Algebra (RA)
• It is a Procedural language
• It consist of set of operators that take one or more relations as inputs and give a new
relation as a result.
• RA support Six basic operators ( or operations)
1. select
2. project
3. union
4. set difference
5. Cartesian product
6. Rename
• It also support other operators as-
1. Set intersection
2. Natural join
3. Division
Select Operation – Example
 It select the tuples that satisfy the given predicate (condition)

 Example-2
 Example-1

Q. Find all sailors above age 35

Q. Display all records for which the value of A


and B is same and D must be greater than 5
Sid Sname Rating age
22 dustin 7 45
31 lubber 8 55
Project Operation

• It is denoted by 
• It is used to display specific attributes (columns) of a relation
• Duplicate rows removed from result, since relations are sets
• Syntax-
A1, A2, …, Ak (r)
where A1, A2 are attribute names and r is a relation name.
Project Operation - Example
 Example- Q. Find all values of A and C for B is greater than 20

A B C A C

Q. Display the values of A &C


Q. Find all values of A and C for B is greater than 10
but less than or equal to 40
A B C A C
Project Operation – Example
 Example-3  Example-4

Q. Find sid and sailor name whose rating


between 1 and 8

Q. Find sailor name and age of all sailors


sid sname
31 lubber
Sname age
58 rusty
dustin 45
lubber 55.5
rusty 35
Project Operation – Example
 Example-4  Example-6

Q. Find sid and sailor name whose rating is


above 7

Q. Find sailor name whose rating is above 7 sid sname


and age below 50 yrs
31 lubber
58 rusty
Sname
lubber
rusty
Union Operation ()
• Let r and s be the two relations then r  s display all the tuples that are either
in r or in s or in both.

• It is defined as:
r  s = {t | t  r or t  s}

• The operation r  s must be set compatible-


1. r, s must have the same number of attributes
2. The domain of ith attribute in both relations must be same

• It eliminate duplicate tuples.


Union Example

The result of the operation is-


Set Difference Operation
• Let r and s be the two relations then set difference r – s, display all
the tuples that are in r but not in s

• Defined as:
r – s = {t | t  r and t  s}

• The operation must be set compatible.


Set Difference Example
s-r
The result of the operation is-

A B

The result of the operation is-


Cartesian-Product Operation
• Notation r x s
• Let r and s be the two relations then Cartesian product is
defined as-

r x s = {t q | t  r and q  s}

• The Cartesian Product is also an operator which works on two sets. It is


sometimes called the CROSS PRODUCT or CROSS JOIN.

• It combines the tuples of one relation with all the tuples of the other relation. It
means if r contain (a1, a2……an ) attributes with n tuples and s contain (b1, b2……bm
) attributes with m tuples then rxs contain n+m attributes with nxm tuples.
Cartesian-Product Example

The result of the operation is-

A B C D E
α 1 α 10 a
β 2 β 10 a
The result of the operation is- β 2 β 20 b
Rename Operation
• Allows us to refer to a relation by more than one name.
Defined as:
 x (E)
returns the expression E under the name X
Thank You
DATABASE MANAGEMENT SYSTEM

LECTURE
RELATIONAL ALGEBRA
Banking Example

branch (bname, bcity, assets)

customer (cname, cstreet)

account (acc_no, bname, balance)

loan (l_no, bname, amount)

depositor (cname, acc_no)

borrower (cname, l_no)


Banking Example branch (bname, bcity, assets)

customer (cname, cstreet)

account (acc_no, bname, balance)


1. Find all loans of over 1200
loan (l_no, bname, amount)

depositor (cname, acc_no)

borrower (cname, l_no)


2. Find the loan number for each loan of an amount greater than 1200

3. Find the name of all branches agra

4. Find the name of all branches not in agra


Additional Operations
We define additional operations that do not add any power to the
relational algebra, but that simplify common queries.

• Set intersection
• Natural join
• Division
• Assignment
Set-Intersection Operation
• Notation: r  s
• Let r and s be the two relations then intersection of r and s defined
as-
r  s ={ t | t  r and t  s }

• The operation must be set compatible.


• Note: r  s = r - (r - s)
Natural-Join Operation
 Notation: r s

• Let r and s be the two relations with attributes (A1,A2,…..An) and (B1, B2,
…….Bm) then r s, defined as-

• It join the two relations by forcing equality condition on common attributes in both
the relations.

• Only distinct attributes appear in output.


• If there is no attribute in common then natural join equivalent to Cartesian product.
Natural-Join Operation

The result of the operation is-


The result of the operation is-
Natural-Join Operation
 Theta Join

• It is an extension to the natural join that allow to join the tables using σ
operator and Cartesian product.
• It is defined as -

Sid Bid day sname rating age

22 101 10/10/96 dustin 7 45

58 103 11/12/96 rusty 10 35


Division Operation
• It is denoted by

• It is applied to queries that include the phrase “for all”.

• Let r be the relation with (A1, …, Am) attributes and s be relations with (B1, …, Bn ) attributes then r s contain ((A1, …, Am)

rs={t | t  R-S(r)   u  s ( tu  r ) }
Sno Pno Pno
S1 P1 P2
S1 P2
S1 P3
S1 P4
S2 P1 Pno Pno
S2 P2
P2 P1
S3 P2
S4 P2 p4 P2
S4 P4 p3
Division Example
OUTER JOINs
 Notice that much of the data is lost when applying a join to two relations. In some cases this lost
data might hold useful information.

 An outer join retains the information that would have been lost from the tables, replacing missing
data with nulls.

 There are three forms of the outer join, depending on which data is to be kept.
– LEFT OUTER JOIN - keep data from the left-hand table
– RIGHT OUTER JOIN - keep data from the right-hand table
– FULL OUTER JOIN - keep data from both tables
LEFT-OUTER JOINs
 It is denoted by
 It keep all the tuples in left relation. The mismatch tuples in
right relation are padded with null values.
R LEFT O U TER JO IN R.ColA = S.SColA S
R ColA ColB R LEFT O U TER JO IN R.ColA = S.SColA S
R ColA
A ColB
R1 ColA ColB
R LEF T O U TER JO IN R.ColA = S .S ColA S
A
A 1 A 1
B 21 A 1 DA A31 AD1 1
A 3 1
DB 32 B 2
ED D 35 DE3 D 34 3
FD 43 DF
3
4 BE
E5
2 E-5 E 4- 4
EF 54 E B --2 - -- -
E 5 5 FB F4
2
- 4 -
- -
F 4
S S R RIG H T RO RIG H T OJO
U TER U TER
IN JOR.ColA
IN R.ColA = S .S ColA SS
= S.SColA S
S SColA SColBSColA SColB
R RIG H T O U TER JO IN R.ColA = S.SColA
SColA SColB A 1 A 1 A 1
AA 11 C 2 AA D1 1 A
A3 D 1 1 3
CC 22 D 3 DD E 33 DD5 E 3 3 4
DD 33 E EE - -
4
55 EE C
44 2
EE 44 -- -- CC 22
Right-OUTER JOINs
 It is denoted by
R LEFT O U TER JO IN R.ColA = S.SColA S
 It keep all the
R ColA
A
tuples
ColB
1
in right relation. The mismatch tuples in
A 1 A 1
left relationDare padded
B 2
3
with null
D values.
3 D 3
E 5 E 4
F 4 B 2 - -
E R5 LEFT O U TER JO INF -
4 = S.SColA
R.ColA S-
R ColA ColB R LEFT O U TER JO IN R.ColA S
R ColA ColB = S.SColA
A S 1 A R RIG
1 H T AO U TER 1JO IN R.ColA = S.SColA S
B A 2 1SColA SColB DA 13 A 13
D
DB 32 A 1 ED 35 ADE 134 A 1
FD 43 C 2 BE 52 D-E 4
3- D 3
EF 54 D 3 FB 2
4 E --
5--
E 4
E 5 F 4 - -
E 4 - - C 2
S R RIG H T O U TER JO IN R.ColA = S.SColA S
S SColA SColB R RIG H T O U TER JO IN R.ColA = S.SColA S
SColA SColB
AA 11 AA 11 AA 11
CC 22 DD 33 DD 33
DD 33 EE 55 EE 44
EE 44 -- -- CC 22
FULL-OUTER JOIN
 It is denoted by
 It keep all the tuples in left and right relation. The mismatch
tuples in both relations are padded with null values.
R LEFT O U TER JO IN R.ColA = S.SColA S
R ColA ColB R LEFT O U TER JO IN R.ColA = S.SColA S
R ColA
A ColB
1
A
A R 1FU LL AO U TER JO1 IN S
B R2 1 ColA ColB D A 13 AD 1 3
R.ColA = S.SColA
B 2
D
D
3
3
A 1 ED 35
ADE 134 A 1
F 4 B 2 BE 52 E- 4 -
D- 3- D 3
EF 54 D 3 FB 2
4 E-- 5- - E 4
E 5 F 4
F 4 B 2 - -
S E R RIG
5 H T O U TER JO IN R.ColA = S.SColA- S
S SColA SColB R RIG H T O U TER JO INF R.ColA 4 = S.SColA S-
SColA SColB -A -1
AA 11 A 1 C 2
S A 1 A 1
CC 2 2 SColA SColB D D 33 DD 33
DD 33 A 1 EE 55 EE 44
EE 44 C 2 -- -- CC 22
Banking Example branch (bname, bcity, assets)

customer (cname, cstreet)

account (acc_no, bname, balance)


5. Find all branch whose assets is above 1Cr.
loan (l_no, bname, amount)

depositor (cname, acc_no)

borrower (cname, l_no)


6. Find the account numbers in HDFC branch whose balance is below 5000

7. Find the names of all customers who have a loan, an account, or both, from the
bank

8. Find the names of all customers who have a loan and an account at bank
Banking Example branch (bname, bcity, assets)

customer (cname, cstreet)

account (acc_no, bname, balance)


9. Find the names of all customers who have a loan and an account at bank
loan (l_no, bname, amount)

depositor (cname, acc_no)

borrower (cname, l_no)


10. Find the names of all customers who have a loan at the SBI branch.

11. Find the names of all customers who have an account at the HDFC branch.

12. Find the names of all customers who have taken loan above 5L from SBI branch .
Thank You
DATABASE MANAGEMENT SYSTEM

LECTURE
SQL
Introduction to SQL
• It was developed by IBM in 1970 as a part of project R.
• Initially called as SEQUEL (Structured English Query Language)
• Renamed as Structured Query Language (SQL)
• ANSI and ISO standard SQL in 1979:
– SQL-86 , SQL-89, SQL-92
– SQL:1999 (language name became Y2K compliant!)
– SQL:2003
• Commercial systems offer most, if not all, SQL-92 features, plus varying feature sets from
later standards and special proprietary features.
– Not all examples here may work on your particular system.
SQL is a Declarative language
• An imperative language describes how to perform some task:
– C, C++, java, relational algebra

• A declarative language describes what the results are like not


how to create it
– HTML, latex, SQL, tuple relational calculus
Data Definition Language
Allows the specification of:

• The schema for each relation, including attribute types.


• Integrity constraints
• Authorization information for each relation.
• Non-standard SQL extensions also allow specification of
– The set of indices to be maintained for each relations.
– The physical storage structure of each relation on disk.
SQL has multiple roles
• Data definition language (DDL)
– Eg, define relation schemas
• Data control language (DCL)
– Eg, security and authorization controls
• Data manipulation language (DML)
– Query for tuples
– Insert, delete and modify tuples

• SQL supports constraints, transactions & views


• SQL standard does not support indexes
Domain Types(Data types) in SQL
Syntax-
• char(n). Fixed length character string
Attribute-name data-type(size)
• varchar2(n). Variable length character strings
• int. Integer (machine-dependent).
• smallint. Small integer (a machine-dependent )
• number(p,d). Fixed point number, with user-specified precision of p digits, with n digits to
the right of decimal point.
• real, double precision. Floating point and double-precision floating point numbers, with
machine-dependent precision.
• float(n). Floating point number, with user-specified precision of at least n digits.
• Null values are allowed in all the domain types.
Date/Time Types in SQL (Cont.)

• date. Dates, containing a (4 digit) year, month and date


– E.g. date ‘2001-7-27’
• time. Time of day, in hours, minutes and seconds.
– E.g. time ’09:00:30’ time ’09:00:30.75’
• timestamp: date plus time of day
– E.g. timestamp ‘2001-7-27 09:00:30.75’
Large-Object Types

• Large objects (photos, videos, CAD files, etc.) are stored as a


large object:
– blob: binary large object -- object is a large collection of un-interpreted
binary data (whose interpretation is left to an application outside of the
database system)

– clob: character large object -- object is a large collection of character data

– When a query returns a large object, a pointer is returned rather than the
large object itself.
Create Table Command
• An SQL relation is defined using the create table command:

create table <table-name> ( A1 D1,…………, Ai Di)

– <table-name > user defined name


– each Ai is an attribute name
– Di is the data type of attribute Ai

• Example:

create table branch (branch_name char(15), branch_city char(30), assets integer)


Integrity Constraints on Tables

• not null
• primary key (A1, ..., An )

Example: Declare branch_name as the primary key for branch


.
create table branch
(branch_name char(15) primary key,
branch_city char(30) not null,
assets integer )

• primary key declaration on an attribute automatically ensures not null


• Table can have only one primary key
Thank You
DATABASE MANAGEMENT SYSTEM

LECTURE
SQL
Insert command
• Syntax-
Insert into < table-name> values ( value1, value2,……..)

• Student (rollno, name, address)

Insert into student (123, ‘abc’, ‘agra’)


Select command
• It is used to retrieve records from table
• Syntax-
Select < Attribute list> from <table-name> [ Where
condition]
consider the table -
student (rollno, name, address)

1. Select rollno from student


2. Select rollno, name from student
3. Select * from student
4. Select * from student where address=‘agra’
5. Select name from student where address=‘agra’
Describe and tab command
• It is used to display table structure

• Syntax-
desc <table-name>

Tab command
- Use to display list of objects created by user

- Eg. Select * from tab


111.93.35.149:8081/apex
Distinct clause
• It is used to display unique records

• Syntax-
select [Distinct] A1, A2, ..., An
from < table-name>
where <condition>

Ex-
 select distinct name from student
 select distinct name, address from student
Like operator
• It is used for pattern matching
• It provide two wildcard operators- % and _

• Syntax-
select <attribute list> from < table-name>
where like <condition>

Q. Find all the students whose name start with “A”


Select * from student where name like ‘A%’

Q. Find all the students whose name start with “s” and ends with “r”
Select * from student where name like ‘s%r’

Q. Find all the students whose name contain “a’” at third position
Select * from student where name like ‘__a%’
Thank You
DATABASE MANAGEMENT SYSTEM

LECTURE
SQL
The Rename Operation
• The SQL allows renaming relations and attributes using the as clause:
old-name as new-name

• Find the worker names and hourly rates of all workers


Ordering the Display of Tuples
• We may specify desc for descending order or asc for ascending
order, for each attribute; ascending order is the default.
– E.g. order by customer-name desc
Set Operations
• The set operations union, intersect, and except operate on relations and
correspond to the relational algebra operations 
• Each of the above operations automatically eliminates duplicates; to retain all
duplicates use the corresponding multiset versions union all, intersect all and
except all.

Suppose a tuple occurs m times in r and n times in s, then, it occurs:


– m + n times in r union all s
– min(m,n) times in r intersect all s
– max(0, m – n) times in r except all s
Example

Union all -
Union - Select * from r
Select * from r union all
union select * from s
select * from s
Example

Intersect all -
Intersect - Select * from r
Select * from r intersect all
intersect select * from s
select * from s
Example

except all -
except -
Select * from r
Select * from r except all
except select * from s
select * from s
branch (bname, bcity, assets)
Set Operations Example customer (cname, cstreet)

account (acc_no, bname, balance)


 Find all customers who have a loan, an account, or both: loan (l_no, bname, amount)
(select customer-name from depositor) depositor (cname, acc_no)
union
borrower (cname, l_no)
(select customer-name from borrower)
 Find all customers who have both a loan and an
account.
(select customer-name from depositor)
intersect
(select customer-name from borrower)

nd all customers who have an account but no loan.


(select customer-name from depositor)
except
(select customer-name from borrower)
Aggregate Functions
• These functions operate on the multiset of values of a column of a relation, and
return a value
avg: average value
min: minimum value
max: maximum value
sum: sum of values
count: number of values
Aggregate Functions (Cont.)
Worker(w_id, w_name, skill_type,hrly_rate, supv_id)
Building (bldg_id, bldg_address, type, qlty_level)
Assignment (w_id, bldg_id, start_date, num_days)

p) What are the highest and lowest hourly wages?

r) How many different skill types are there?

s) What is the average weekly wage?


Joins

 Joins are used to retrieve records from more than one tables (relations)
 There are following types of joins-
 Cartesian product
 Self join
 Theta join
 Outer joins
 Left
 Right
 full
Cartesian-Product
 It combines the tuples of one relation with all the tuples of the other relation.
 It means if r contain (a1, a2……an ) attributes with n tuples and s contain
(b1, b2……bm ) attributes with m tuples then Cartesian product contain n+m
attributes with nxm tuples.
 Example-

Select * from r, s
Self Join
 Joining table itself is called self join.
Example- (J) List workers with the names of their supervisors?
W_id W_name Hrly_rate Skill_type Supv_ID W_id W_name Hrly_rate Skill_type Supv_ID
1235 N.Faraday 12.5 Electric 1311 1235 N.Faraday 12.5 Electric 1311
1412 C.Nemo 13.75 Plumbing 1520 1412 C.Nemo 13.75 Plumbing 1520
2920 R.Garret 10.0 Roofing 2920 2920 R.Garret 10.0 Roofing 2920
3231 P.Mason 17.40 Electric 1311 3231 P.Mason 17.40 Electric 1311
1520 H.Recover 11.75 Plumbing 1520 1520 H.Recover 11.75 Plumbing 1520
1311 C.Coulomb 15.50 Electric 1311 1311 C.Coulomb 15.50 Electric 1311
3001 J.Barrister 8.20 Framing 3231 3001 J.Barrister 8.20 Framing 3231
Theta Join
 Use to join two or more tables based on some condition. Tables may be join using
(=, <, >, <=, >= and <> ) condition
Worker(w_id, w_name, skill_type,hrly_rate, supv_id)
Building (bldg_id, bldg_address, type, qlty_level)
Assignment (w_id, bldg_id, start_date, num_days)

i) . What are the skill types of workers assigned to building 435?

k) List the names of workers assigned to office building?


Theta Join
Worker(w_id, w_name, skill_type,hrly_rate, supv_id)
Building (bldg_id, bldg_address, type, qlty_level)
Assignment (w_id, bldg_id, start_date, num_days)

q) What is the average number of days that the workers are assigned to building 435?

r) What is the total number of days allocated for plumbing on building 312?

u) How many buildings have quality level 3?


Thank You
DATABASE MANAGEMENT SYSTEM

LECTURE
SQL
Nested Subqueries
• SQL provides a mechanism for the nesting of subqueries.
• A subquery is a select-from-where expression that is nested within another
query.
• A common use of subqueries is to perform tests for set membership, set
comparisons, and set cardinality.
Nested Subqueries
Worker(w_id, w_name, skill_type,hrly_rate, supv_id)
Building (bldg_id, bldg_address, type, qlty_level)
Assignment (w_id, bldg_id, start_date, num_days)
l) What are the Skill types of workers assigned to building 435?

m) List the workers who have receive a higher hourly wage than their supervisors.
Nested Subqueries
Worker(w_id, w_name, skill_type,hrly_rate, supv_id)
Building (bldg_id, bldg_address, type, qlty_level)
Assignment (w_id, bldg_id, start_date, num_days)

n) List the names of workers assigned to office building?

o) List workers who are assigned to every building.


Group by clause
 The GROUP BY statement groups rows that have the same values into summary
rows, like "find the number of customers in each country".
 The GROUP BY statement is often used with aggregate functions (COUNT, MAX,
MIN, SUM, AVG) to group the result-set by one or more columns.

 Syntax-
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
[HAVING condition]
[ORDER BY column_name(s)]

The HAVING clause was added because the WHERE keyword could not be used with group by.
Group by cont…….
Worker(w_id, w_name, skill_type,hrly_rate, supv_id)
Building (bldg_id, bldg_address, type, qlty_level)
Assignment (w_id, bldg_id, start_date, num_days)

u) For each supervisor, what is the highest hourly wage paid to a worker reporting to that
supervisor?

v) For each type of building, what is the average quality level for building of status 1?
Group by cont…….
Worker(w_id, w_name, skill_type,hrly_rate, supv_id)
Building (bldg_id, bldg_address, type, qlty_level)
Assignment (w_id, bldg_id, start_date, num_days)
w) For each supervisor managing more than one worker, what is the highest wage paid to a worker
reporting to that supervisor?

x) For each type of building, what is the average quality level for buildings of status 1? Consider
only those types of buildings having maximum quality level no higher than 3?
Experiment No-1: PREMIER COMPANY DATABASE

TABLE NAME: WORKER

Worker_ID Worker_name Hrly_rate Skill_type Supv_ID

1235 N.Faraday 12.5 Electric 1311

1412 C.Nemo 13.75 Plumbing 1520

2920 R.Garret 10.0 Roofing 2920

3231 P.Mason 17.40 Electric 1311

1520 H.Recover 11.75 Plumbing 1520

1311 C.Coulomb 15.50 Electric 1311

3001 J.Barrister 8.20 Framing 3231


Experiment No-1: PREMIER COMPANY DATABASE

TABLE NAME: Building

Bldg_ID Bldg_address Type Qlty_level Status

312 123 Elm Office 2 2


435 456 Maple Retail 1 1
515 789 Oak Residence 3 1
210 1011 Birch Office 3 1
111 1213 Aspen Office 4 1
460 1415 Beech Warehouse 3 3
W_id Bldg_ID Start_date Num_days
1235 312 10-oct 5
Table : Assignment 1412 312 1-oct 10
1235 515 17-oct 22
2920 460 5-oct 18
1412 460 8-dec 18
2920 435 28-oct 10
2920 210 10-nov 15
3231 111 10-oct 8
1412 435 15-oct 15
1412 515 5-nov 8
3231 312 24-nov 20
1520 515 9-oct 14
1311 435 8-oct 12
1412 210 15-nov 12
1412 111 1-dec 4
3001 111 8-oct 14
1311 460 23-oct 24
1520 312 30-oct 17
3001 210 27-oct 14
Foreign Key
• It is used to link two tables
• It is also called as referential integrity
• A foreign key in one table refers to primary key in another table.
• When we declare any attribute as foreign key-
– It allows duplicate values but the values must be exist in primary key
– A table may have many foreign keys

• Syntax-
create table <table-name> ( attribute-name data-type references <primary-key table> ,……….)
Queries for Premier Construction company database.

Simple Queries
A simple query is one involving only a single database table.
a) List all data about workers?
b) Who are plumbers?
c) List all data about office Buildings?
d) What is the weekly wage rate for each Electrician?
e) Who gets an hourly rate between 10 and12?
f) List the Plumbers, Roofers and Electricians?
g) Find all Workers whose skill type begins with “Elec”?
h) Find all work assignments which will start in the next two weeks?
i) What are the skill types of workers assigned to building 435?
j) List workers with the names of their supervisors?
k) List the names of workers assigned to office building?
Worker(w_id, w_name, skill_type,hrly_rate, supv_id)
Building (bldg_id, bldg_address, type, qlty_level)
Assignment (w_id, bldg_id, start_date, num_days)

Sub-Queries
A sub query or query can be placed within the WHERE clause of the query, resulting in the
expansion of the WHERE clause capability.
l) What are the Skill types of workers assigned to building 435?
m) List the workers who have receive a higher hourly wage than their supervisors.
n) List the names of workers assigned to office building?
o) List workers who are assigned to every building.
Worker(w_id, w_name, skill_type,hrly_rate, supv_id)
Building (bldg_id, bldg_address, type, qlty_level)
Assignment (w_id, bldg_id, start_date, num_days)

Built in Functions
Aggregate functions that operate on a set of values and produce single value as output
(SUM,AVG, COUNT,MAX,MIN).

p) What are the highest and lowest hourly wages?


q) What is the average number of days that the workers are assigned to building 435?
r) What is the total number of days allocated for plumbing on building 312?
r) How many different skill types are there?
s) What is the average weekly wage?
u) How many buildings have quality level 3?
Worker(w_id, w_name, skill_type,hrly_rate, supv_id)
Building (bldg_id, bldg_address, type, qlty_level)
Assignment (w_id, bldg_id, start_date, num_days)

GROUP BY and HAVING


Group By Clause indicates that rows should be grouped on a common value of specified
coloumn(s). Having Clause places condition on groups.
u) For each supervisor, what is the highest hourly wage paid to a worker reporting to that
supervisor?

v) For each type of building, what is the average quality level for building of status 1?

w) For each supervisor managing more than one worker, what is the highest wage paid to
a worker reporting to that supervisor?

x) For each type of building, what is the average quality level for buildings of status 1?
Consider only those types of buildings having maximum quality level no higher than 3?
Thank You
DATABASE MANAGEMENT SYSTEM

LECTURE
TUPLE RELATIONAL CALCULUS
Tuple Relational Calculus (TRC)
 It is a non procedural language
 A query in TRC is expressed as-

{ t | P(t) }

where , P is a formula and t is a tuple variable.


 The result of the query is set of tuples t that satisfy the formula/condition P(t)
Tuple Relational Calculus (TRC)

Existential and Universal Quantifiers-

 Two special symbols called quantifiers appear in the formula. They are-
 Existential quantifier ( )
 Universal quantifier ( )

 The formula is true if the formula P evaluate to true for some tuples.
 The formula is true if the formula P evaluate to true for every tuples.
Tuple Relational Calculus (TRC)

Bind and free variables-

 A tuple variable t is said to be bind variable if it appear quantifiers ( ) otherwise it


is called as free variable.
branch (bname, bcity, assets)
TRC examples- customer (cname, cstreet)

Q. Find loan over 1200. account (acc_no, bname, balance)

loan (l_no, bname, amount)

depositor (cname, acc_no)

borrower (cname, l_no)

Q. Find branch name for loan over 1200

Q find branch name and amount for loan over 1200


branch (bname, bcity, assets)
TRC examples- customer (cname, cstreet)

Q. Find all customers who have a loan or account or both at account (acc_no, bname, balance)

bank. loan (l_no, bname, amount)

depositor (cname, acc_no)

borrower (cname, l_no)

Q. Find all customers who have a loan and account at bank.


branch (bname, bcity, assets)
TRC examples- customer (cname, cstreet)

Q. Find all customers who have an account but not loan at account (acc_no, bname, balance)

bank. loan (l_no, bname, amount)

depositor (cname, acc_no)

borrower (cname, l_no)

Q. Find the name of customers who an account at HDFC bank.


Thank You
DATABASE MANAGEMENT SYSTEM

LECTURE
PROBLEMS
Questions
Q. Suppose we have -
R= (A, B, C)
S= ( D, E, F)
Let r(R) and s(S) be given . Write following queries in TRC
Questions
Q. Suppose we have -
R= (A, B, C)
S= ( D, E, F)
Let r(R) and s(S) be given . Write following queries in SQL
Questions
Q. Suppose we have - R= (A, B, C) and let r1 and r2 be the relations then express following in SQL
Questions
Q. Consider the following relational database-
employee (person-name, street, city )
work ( person-name, company-name, salary )
company ( company-name, city)
manages ( person-name, manager-name)

Give an expression in SQL and RA for each of the following-

1. Find the name of all employees who works for ABC company
2. Find the name and cities of residence of all employees who employee (person-name, street, city )
works for ABC company work ( person-name, company-name, salary )
company ( company-name, city)
manages ( person-name, manager-name)

3) Find the name and cities of residence of all employees who works for ABC company and earn more
than 10,000 per month
employee (person-name, street, city )
4. Find the name of all employees in this database who work ( person-name, company-name, salary )
live in the same city as the company for which they work. company ( company-name, city)
manages ( person-name, manager-name)

5) Find the name all employees in the database who do not work for ABC company
Thank You
DATABASE MANAGEMENT SYSTEM

LECTURE
DOMAIN RELATIONAL CALCULUS
Domain Relational Calculus (DRC)
 This is the 2nd form of relational calculus called DRC.
 This uses domain variables that take on values from an attributes domain rather than
values for an entire database.
 In DRC query is expressed as-

{ <x1, x2, …….. xn} | P(x1, x2, ….., xn) }

where , x1, x2, ….., xn are domain variables and P is a formula or condition.
branch (bname, bcity, assets)
Example Queries customer (cname, cstreet)

account (acc_no, bname, balance)

• Find the loan-number, branch-name, and amount for loans loan (l_no, bname, amount)
of over $1200 depositor (cname, acc_no)

borrower (cname, l_no)

 Find the names of all customers who have a loan of over $1200
branch (bname, bcity, assets)

customer (cname, cstreet)


• Find the names of all customers having a loan, an account, or
both at bank account (acc_no, bname, balance)

loan (l_no, bname, amount)

depositor (cname, acc_no)

borrower (cname, l_no)

 Find the names of all customers who have a loan from the
HDFC branch and the loan amount:
branch (bname, bcity, assets)

customer (cname, cstreet)


Q. Find the names of all customers having a loan and an account
at bank account (acc_no, bname, balance)

loan (l_no, bname, amount)

depositor (cname, acc_no)

borrower (cname, l_no)

Q. Find the names of all customers having a loan b but not an account
at bank
branch (bname, bcity, assets)
SQL Commands ( Some clause) customer (cname, cstreet)

account (acc_no, bname, balance)


Q. Find all branches that have greater assets than some branch loan (l_no, bname, amount)
located in Agra. depositor (cname, acc_no)

borrower (cname, l_no)

 Same query using > some clause


branch (bname, bcity, assets)
SQL Commands ( All clause) customer (cname, cstreet)

account (acc_no, bname, balance)


Q. Find the names of all branches that have greater assets than all loan (l_no, bname, amount)
branches located in Agra depositor (cname, acc_no)

borrower (cname, l_no)


Q. Consider the following relational schema for library
member(mem-no, name, dob)
books (isbn, title, author, publisher)
borrowed (mem-no, isbn, date)

Write the following queries in SQL


1. Find the name of members who have borrowed any book published by “McGraw-Hill”
Q. Consider the following relational schema for library
member(mem-no, name, dob)
books (isbn, title, author, publisher)
borrowed (mem-no, isbn, date)

Write the following queries in RA and SQL

2. Find the name of members who have borrowed all books published by “McGraw-Hill”
Q. Consider the following relational schema for library
member(mem-no, name, dob)
books (isbn, title, author, publisher)
borrowed (mem-no, isbn, date)

3. Find the name and membership numbers of members who have borrowed more than
five different books published by “McGraw-Hill”
Q. Consider the following relational schema for library
member(mem-no, name, dob)
books (isbn, title, author, publisher)
borrowed (mem-no, isbn, date)

4. Find the average number of books borrowed per member

You might also like