DBMS
DBMS
The importance of data models, Basic building blocks, Business rules, The evolution
of data models, Degrees of data abstraction.
SQL: data definition, aggregate function, Null Values, nested sub queries, Joined
relations. Triggers.
A Silberschatz, H Korth, S Sudarshan, “Database System and Concepts”, fifth Edition McGraw-Hill ,
Practicals
1) Design a Database and create required tables. For e.g. Bank, College Database
2) Apply the constraints like Primary Key , Foreign key, NOT NULL to the tables.
3) Write a sql statement for implementing ALTER,UPDATE and DELETE
4) Write the queries to implement the joins
5) Write the query for implementing the following functions: MAX(),MIN(),AVG(),COUNT()
6) Write the query to implement the concept of Intergrity constrains
7) Write the query to create the views
8) Perform the queries for triggers
9) Perform the following operation for demonstrating the insertion , updation and deletion
using the referential integrity constraints
10) Write the query for creating the users and their role.
1
INTRODUCTION TO DATABASE
MANAGEMENT SYSTEM
Unit Structure
1.0 Objectives
1.1 Introduction
1.2 What is Database Management System
1.3 History of Database System
1.4 Purpose of Database System
1.5 Advantages and Disadvantages of Database System
1.6 Summary
1.7 Model Questions
1.0 OBJECTIVES
1.1 INTRODUCTION
Today DBMS not only used to insert, update and delete the data
stored in database.
Thus the growth of DBMS system has not only benefitted only to
the customers or employees in an organisation but it has touched
all the aspects of our lives.
4
With the time passed by, the DBMS system has matured
significantly. As the development of relational DBMS has
reached to larger users and the number of benefits from the
same, it was widely accepted and many corporate houses
started using this system for their day to day activities.
The period between 1980 and 1990s saw many advances in the
field of DBMS system. Several vendors try to build a system
where more stress is given on complex analysis of data within
an enterprise.
It allowed the user to write their queries through Web forms, and
the formatted output is tabulated through mark-up languages
like HTML.
o Also there are several copies of files are stored, if any one of
the file is changed, the different versions of same file may
not be updated which leads to inconsistency of data.
3. Data isolation
o One of the major problems with the file system is that the
data is scattered and stored in multiple locations and in
different formats.
5. Security problems
6. Integrity problems
7. Atomicity problems
2. Elimination of Inconsistency
o If, after getting the hall ticket the student realize that rather
than expecting Embedded system as the choice of elective
10
1. Database Complexity
1.6 SUMMARY
1
2
INTRODUCTION TO RELATIONAL
DATABASE MANAGEMENT SYSTEM
Unit Structure
2.0 Objectives
2.1 Introduction to RDBMS
2.2 The Relational Model
2.3 Introduction to SQL
2.4 Working with relations of RDBMS
2.5 Advantages and Disadvantages of Relational Database
System
2.6 Summary
2.7 Model Questions
1.0 OBJECTIVES
o There are various roles which are played by SQL. Some of them
are discussed below
o When the user is creating the above table, the user now
become the owner of the newly created table, which is given the
name specified in the above statement.
o Note that the table name must be a legal SQL name, and it
must not conflict with any of the existing tables.
o A slightly complex create table is discussed below which allows
to create a new table and also to set up the relationship
between different tables
2. Validity checking
o Every column in a database has a domain, a set of data
values that are legal for that column. The DBMS can be
asked to prevent other data values in these columns.
3. Entity integrity
o The primary key of a table must contain a unique value
in each row, which is different from the values in all other
rows.
4. Referential integrity
o A foreign key in a relational database links each row in
the child table containing the foreign key to the row of
the parent table containing the matching primary key
value.
6. Business rules
o Updates to a database may be constrained by business
rules governing the real-world transactions that are
represented by the updates.
ADVANTAGES
4. Network Access
o RDBMSs provide access to the database through a server
daemon, a specialized software program that listens for
requests on a network, and allows database clients to
connect to and use the database.
o Users do not need to be able to log in to the physical
computer system to use the database, providing
convenience for the users and a layer of security for the
database. Network access allows developers to build
desktop tools and Web applications to interact with
databases.
5. Speed
o The relational database model is not the fastest data
structure. RDBMS advantages, such as simplicity, make the
slower speed a fair trade-off.
o Optimizations built into an RDBMS, and the design of the
databases, enhance performance, allowing RDBMSs to
perform more than fast enough for most applications and
data sets.
o Improvements in technology, increasing processor speeds
and decreasing memory and storage costs allow systems
administrators to build incredibly fast systems that can
overcome any database performance shortcomings.
6. Maintenance
o RDBMS feature maintenance utilities that provide database
administrators with tools to easily maintain, test, repair and
back up the databases housed in the system.
o Many of the functions can be automated using built-in
automation in the RDBMS, or automation tools available on
the operating system.
7. Language
o RDBMSs support a generic language called "Structured
Query Language" (SQL).
o The SQL syntax is simple, and the language uses standard
English language keywords and phrasing, making it fairly
intuitive and easy to learn.
13
2.6 SUMMARY
3. Entity integrity
4. Referential integrity
5. Other data relationships
6. Business rules
1
3
INTRODUCTION TO DATABASE
STRUCTURE
Unit Structure
3.0 Objectives
3.1 Levels of abstraction in DBMS
3.2 View of data
3.3 Role of Database users
3.4 Role of database administrators
3.5 Transaction Management
3.6 Database Structure
3.7 Summary
3.8 Model Questions
3.0 OBJECTIVES
Introduction
o In traditional system, each collection of application programs
had its own independent master file. The duplication of data
over master files could lead to inconsistent data.
o In early days, efforts were discovered to use a common master
file for a number of application programs resulted in problems of
integrity and security.
2
1. External Level
2. Conceptual Level
Data Independence
1. Naive user:
2. Application programmers
3. Sophisticated users
4. Specialized users
What is a Transaction?
o A transaction is an event which occurs on the database.
Generally a transaction reads a value from the database or
writes a value to the database.
o Although a transaction can both read and write on the
database, there are some fundamental differences between
these two classes of operations.
o A read operation does not change the image of the database
in any way.
o But a write operation, whether performed with the intention
of inserting, updating or deleting data from the database,
10
Read A;
A = A – 100;
Write A;
Read B;
B = B + 100;
Write B;
There are several ways to achieve this and the most popular
one is using some kind of locking mechanism.
o Again, if you have the concept of Operating Systems, then
you should remember the semaphores, how it is used by a
process to make a resource busy before starting to use it,
and how it is used to release the resource after the usage is
over.
o Other processes intending to access that same resource
must wait during this time. Locking is almost similar. It states
that a transaction must first lock the data item that it wishes
to access, and release the lock when the accessing is no
longer required.
12
1. DDL Compiler
Data Description Language compiler processes schema
definitions specified in the DDL. It includes metadata information
such as the name of the files, data items, storage details of
each file, mapping information and constraints etc.
3. Data Manager
The Data Manager is the central software component of the
DBMS also knows as Database Control System.
4. Data Dictionary
Data Dictionary is a repository of description of data in the
database. It contains information about
• Data - names of the tables, names of attributes of each table,
length of attributes, and number of rows in each table.
• Relationships between database transactions and data items
referenced by them which are useful in determining which
transactions are affected when certain data definitions are
changed.
• Constraints on data i.e. range of values permitted.
• Detailed information on physical database design such as
storage structure, access paths, files and record sizes.
• Access Authorization which is the description of database
users their responsibilities and their access rights.
• Usage statistics such as frequency of query and transactions.
7. End Users – They are the users of the system who is going to
use the system for their day to day activities.
3.7 SUMMARY
1
4.0 Objectives
4.1 Introduction
4.2 Evolution of Data models
4.3 Types of Data Models
4.4 Merits and Demerits of Each Model
4.5 Business Rules
4.6 Summary
4.7 Review Questions
5.0 OBJECTIVES
4.1 INTRODUCTION
4.3.2Network databases
4.3.3Relational databases
o Pre-relational models depended upon being able to determine
explicitly where and how individual records were stored.
o The set of minimal keys includes one "primary key"; the rest are
"candidate keys". Within a tuple, references to other tuples are
expressed as a "foreign key," which should contain the values of
the referenced tuple's primary key.
(1) object and object identifier: Any real world entity is uniformly
modeled as an object (associated with a unique id: used to
pinpoint an object to retrieve).
(2) attributes and methods: Here every object has a state (the set
of values for the attributes of the object) and a behavior (the
set of methods - program code - which operate on the state
of the object). The state and behavior encapsulated in an
object are accessed or invoked from outside the object only
through explicit message passing.
(3) class: a means of grouping all the objects which share the
same set of attributes and methods. An object must belong
to only one class as an instance of that class (instance-of
relationship). A class is similar to an abstract data type. A
class may also be primitive (no attributes), e.g., integer,
string, Boolean.
Advantages
1. Simplicity: Since the database is based on the hierarchical
structure, the relationship between the various layers is logically
simple.
Disadvantages
Advantages
Disadvantages
Advantages
1. Conceptual Simplicity: We have seen that both the hierarchical
and network models are conceptually simple, but relational model is
simpler than both of those two.
Disadvantages
1. Hardware overheads: The relational database systems hide the
implementation complexities and the physical data storage details
from the user. For doing this, the relational database system need
more powerful hardware computers and data storage devices.
o Business rules are the rules that are created to affect the way
your business works. Usually, these are rules that involve
employees or staff and are rules that specify what they can and
cannot do.
o A great example of a business rule involves marriages. For
many companies, a boss is not allowed to marry an employee
or an accountant at a company is usually not allowed to marry
another accountant.
11
Departments------offers---------Course
Course----------generates---------Class
Professor --------teaches----------Class
o This shares the business rules with all employees faster and
easier. In relation to how business rules are shred, it is very
important that business rules are written in plain language.
4.6 SUMMARY
a. Hierarchical Model
b. Network Model
c. Object Oriented Model
d. Relational Model
1
Unit Structure
5.0 Objectives
5.1 Database design
5.2 ER-Model
5.3ER Diagram
5.4 Constraints on relationship
5.5 Relational Schemas
5.0 OBJECTIVES
ER Model
ER Diagram
A collection of entities
An Entity set is a set of an entities of all same type that share the
same properties.
ER Diagram
Example
In the Case of Client entity Client_no is the primary key of Client
entity which is used to uniquely identified among the Client ‘s entity
set
Identify relationship
Attributes
Attribute domains
1) Simple Attributes
Simple attributes is an attributes which can further divided in
to two parts
Or
An Attribute composed of single compoenent with an
independent existence
Simple Attributes
Composite Attribute
Or
Example
Composite Attributes
7
Or
Multivalued Attributes
8
Derived attributes
The value from the derived attribute is derived from the
stored attribute for an example Date_of_Birth is a stored attribute
for an each staff member . The value for an Age can be derived
from the Date_of_ Birth attributes I.e by subtracting the Date_of
_Birth from the Current date, therefore the Stored attributes is used
supplied a value to the related attributes
Null attribute
The attribute which take NULL value when entity does not
have the value to it.
Key Attributes
This attribute has the unique value for an entity which is used
to identified given row in the table is called as key attribute of an
entity
Relationships
Degree of relationship
Example
Relationship set
Constraints on relationship
Example
E.g. each member of staff oversees zero or more prosperity for rent
Every row in the Staff table can have relationship with many rows in
the properityforRent Table
One To Many
Many to Many
Many Vendors Has Clients and Many Clients has may Vendors
Participation Constraints
Eg
Type Inheritance
The type of an entity is defined by the attributes it possesses,
and the relationship types it participates in.
Specialization
The process of defining a set of subclasses of super class
The specia;ization is a top down approach of super class and
subclasses
The set of sub classes is based on some distinguishing
characteristic of the super class.
Generalization
Attribute Inheritance
• An entity in a Subclass may possess subclass specific attributes,
as well as those associated with the Superclass
Students Table
Roll_no Firstname Lastname date_of_birth
101 Sachin Godbole 17/07/1981
102 Mahavir Jain 04/12/1985
103 Dinesh Maheshwari 09/10/1987
104 Yogesh Lad 06/11/1985
105 Mahesh Thorat 07/06/1989
II) User Tables: The user table contains the data about the table
which is created by any users in the database systems
III)System tables: The system table contains the data about the
structure of the database and database object
IV) Metadata: The data which hold the description of table in the
database, the table structure, database structure , the
relationship among the tables, the queries and on , This data
id often called as metadata , in short term, Metadata is data
about the data
V) The collection of the system tables is known as the system
catalogs or data dictionary
IV) If that view doesn’t include the primary key columns in the
view, then each record in the table cannot be updated, thereby
violating this rule.
10 ) Integrity independence:
Data integrity constraints should be considered as separated
from application program, the structured query language which
defines data integrity constraint must be stored in the
database in term of data in table that is, in the catalog and not
in the application.
This rule also state that even if the table moves from one
location to another location the user should aware of it, it
should be transparent to the user, changing in the location
mean that the application should not be rewriiten.
12 Nonsubversion rule
The system must not have features that allow you to subvert
database structure integrity. Basically, the system must not
include back doors that let you cheat the system for features
such as administrative privileges or data constraints.
26
6
RELATIONAL DATABASE MODEL
Unit Structure
6.0 Objectives
1 introduction
Table Column
Ro
ws
Table is an abstract entity which does not say how the data
is stored in the physical memory of the computer system
Each table in the database has its own unique name trough
which we can refer the content of the table by the unique name
2.Characteristics of an table
III) Each column name in the table is called as attribute and each
row in the table is called as record. Each column name in the table
is unique namei.e no duplicate name in the same table cannot be
repeated.
V) All the value in the column must be represent in the same data
format
VI) Each columns has the specific range of values, and also
refer as the domain attribute
28
VII) The order of rows and columns is not limited to the DBMS.
3.Example
There is Customer Table contain all information about the
Customer
Cust_id
Cust_Name
Cust_Age
Cust_Address
Cust_Mobile_No
Cust_Phone_No
Attribute
Each column in the above table represent the data item in the
database
Each column in the table represent the attribute in the table
Atleast one column consist in the table
There must be one unique column in the table , this means that
no two columns has the same name in the same table ,it is
possible to have two column with same colmn name but it in the
different table.
The ANSI/SQL Standard does not specify a maximum numbers
of rows and columns in the table.
Records/Tuples
6.3 KEY
Definition
Example:
Types of key
1 Super Key
Customer Table
Example
2. candidate key
Defination:
Example
3 Secondary key
Defination
Example
Customer Table
Account Table
1 ) Entity Integrity
The primary key values should not contain null values, primary
key must be NOT NULL
The uniqueness property ensures that the primary key of
each row uniquely identifies it; there are no duplicates. The second
property ensures that the primary key has meaning, has a value; no
component of the key is missing.
2. Referential Integrity
Referential integrity is a property of data which, when satisfied,
requires every value of one attribute (column) of a relation (table) to
exist as a value of another attribute in a different (or the same)
relation (table).
35
In above example
Definition of Normalization
In the Relational Database Design, the process of
organizing data to minimizing redundancy is known as
Normalization
update anomaly
The same set of information is present in the multiple rows,
now if we applying the updating rule on the table then it lead to
logical inconsistence. Consider an example of customer Table
which contain set of attributes such as Cust_id ,Cust_Name,
Cust_Address,
An insertion anomaly
There are some circumstances in which certain fact cannot
recorded at all
39
Faculty_ID,Faculty_Name,Faculty_Hire_Date,Course_Code
Thus we can add the record the details of any faculty member
who teaches at least one course, but we cannot record the details
of a newly-hired faculty member who has not yet been assigned to
teach any courses except by setting the Course Code to null. This
known as an insertion anomaly.
An deletion anomaly.
There are circumstances in which the deletion of data
representing certain facts necessitates the deletion of some
unrelated data . The "Faculty and Courses" table suffers from this
type of anomaly, for if a faculty member temporarily ceases to be
assigned to any courses, we must delete the last of the records on
which that faculty member appears, effectively also deleting the
faculty member. This is known as a deletion anomaly.
40
Delete
Advantage of Normalization
1) Avoids data modification (INSERT/DELETE/UPDATE) anomalies
as each data item lives in One place
Disadvantage of Normalization
Definition
A relational database table which consist first normal form
(1NF) is to meets certain minimum set of criteria. These criteria are
basically concerned with ensuring that the table is a faithful
representation of a relation and that it is free of repeating groups
42
CR78 Mahesh PG34 Nerul,Navi 1-July-91 30-Oct-95 450 C045 Sanjay More
Lad PG78 Mumbai 1-Nov-95 1-Nov-98 500 C093 Mahavir Jain
Turbhe, Navi
mumbai
CR98 Pramod PG34 Nerul,Navi 1-July-95 30-Oct-98 450 C045 Sanjay More
Patel Mumbai
PG36 Kalyan,Thane 1-Nov-97 1-Nov-99 350 C093 Mahavir Jain
Karjat,Raigad
PG78 1-july-96 1-Nov-97 450 C093 Mahavir Jain
The above table does not contain the atomaic values in the
Property_no, P_Address , Rent_start, Rent_finish,Rent
,Owner_No,Owner_Name Hence it is called un-normalizes
table,we cannot Insert ,update and delete the record from the table
because it is inconsistent state .The above tabe has to be
normimalized
CR78 Mahesh PG34 Nerul,Navi 1-July-91 30-Oct-95 450 C045 Sanjay More
Lad Mumbai
CR78 Mahesh PG78 Nerul,Navi 1-Nov-95 1-Nov-98 500 C093 Mahavir Jain
Lad Mumbai
CR98 Pramod PG34 Nerul,Navi 1-July-95 30-Oct-98 450 C045 Sanjay More
Patel Mumbai
CR98 Pramod PG36 Kalyan,Thane 1-Nov-97 1-Nov-99 350 C093 Mahavir Jain
Patel
CR98 Pramod PG78 Karjat,Raigad 1-july-96 1-Nov-97 450 C093 Mahavir Jain
Patel
43
The above table show the same set of data as the previous
table however we have eliminated the repeated groups.so the table
shown in the above table to be in First Normal form(1NF)
Example
(Customer_No+Property_No)->(Rent-Start, RentFinish)
(Customer_No+Property_No)->Cust_Name
Customer Relation
Customer_NO Cust_Name
CR78 Mahesh Lad
CR98 Pramod Patel
Rental Relation
Property_owner Relation
Property_owner Relation
Transitive Dependency:
(Customer_No+Property_No)->Owner_No
Owner_No ->OName
Property_for_Rent
Owner
Owner_No Owner_Name
C045 Sanjay More
C093 Mahavir Jain
46
Process of Decomposition
Customer_Rental1NF
Property_Owner 2NF
Customer Rental
o For a relation with only one candidate key, 3NF and BCNF are
equivalent.
3NF to BCNF
Client_Interview Relation
1
INTRODUCTION TO UML
Unit Structure
7.0 Objectives
7.1 Introduction
1.0 OBJECTIVES
Class
attributes
Member function
3
7. 2 USECASE DIAGRAM
7. 3 ACTIVITY DIAGRAMS
1
8
RELATIONAL ALGEBRA
Unit Structure
8.0 Objectives
-Navigational (Procedural)
-Non-navigational(non-procedural)
The query only specifies what data is wanted, not how to find
it e.g. relational calculus.
2
8.1 INTRODUCTION
Fundamental operation
o Unary operation
Projection operation(π)
o Select Operation(σ)
o Rename Operation(ρ)
o Binary Operation
SET operation
o Union operation()
o Difference Operation(-)
o Intersection Operation(∩)
Join Operation( )
Cartesian Product Operation(X)
Division Operation(%)
8.1.1Selection operation
The Selection operator select the row from the table that
satify a given predicate. This operation allows to manipulate data in
the single relation. The Selection operation is defined by the symbol
called sigma(σ). The predicate is appear at subscript of Sigma
symbol(σ). The argument relation is present in the parenthesis after
the σ
Synatx
σ
<predicate><Comparsion_operator><Constant_value>(<input_table_name>)
Comparsion_Operator:=,<,<=,>,=>,<>
3
Example
Select all the student from the student table who’s Roll no
is greater than 300
Student
Syntax
Π<attributes>(<Input_Table_Name>)
4
Example
( σ RollNo>300(Student))
8.1.3 Rename Operator(ρ)
Syntax
2) Find
5
8.2.1Union Operator
Union operator is used combine all the result form the first
query to the result from the second query
Syntax
(Relation1) (Relation 2)
Example
1) Employee table
2) Project Table
PROJECTNO DEPTNAME EMPNO
P1 R&D 103
P2 Sales 104
P3 HR 105
Result: The return value would be sales, marketing, R&D and HR.
This operator is find out all the tuples that all the Common tn the
result of Relation 1 and in the Result of Relation 2
Intersect operator doesnot eliminate duplicate record from the
database and they prints the result expression
Syntax
• R1 R2
Example : Get all the employee's full name that are working on a
project.
Syntax R1-R2
Example : Find the employee that are in sales department and are
not on project P2.
7
Result:EMPNO=101
• R1 R2
– The Cartesian product is the table consisting of
all tuples formed by concatenating each tuple in
R1 with a tuple in R2, for all tuples in R2.
• 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.
R1
A B
1 x
2 y
R2
C D
a s
b t
c u
R1XR2
A B C D
1 x a s
1 x b t
1 x c u
2 y a s
2 y b t
2 y c u
8
Example
Employee Table
Department table
Deptno Deptname
100 Sales
200 R &D
Πe.Empno,e.Empname,e.Deptno,d.Deptno,d.Deptname
(ρ e (Employee) X ρ e (Department))
e.E e.Empname e.Deptno d.Deptno d.Deptname
mpno
101 Ramesh 100 100 Sales
101 Ramesh 100 200 R &D
102 Ramesh 200 100 Sales
102 Ramesh 200 200 R &D
103 Rajesh 101 100 Sales
103 Rajesh 101 200 R &D
Syntax
<tablename> <tablename>
Natural Joins
– R1 R2 = ПA’(σC(R1 R2))
– where C is the condition that the values for R1 and R2 are the
same for all attributes in A and A’ is all attributes in R1 and R2
apart from the occurrences of A in R2.
Course Table
Instructor Table
eid ename
123 Rao
345 Allen
456 Mansingh
Course Instructor
CourseId ename
CS51T Rao
CS52S Allen
CS51S Mansingh
10
R ⋈ <R.primary_key = S.foreign_key> S
Inner joins return rows only when there is at least one row
from both tables that matches the join condition.
Inner joins eliminate the rows that do not match with a row from the
other table
Student Table
Course Table
course# name
PH Pharmacy
CM Computing
• R <R.primary_key = S.foreign_key> S
• All rows from R are retained and unmatched rows of S are
padded with NULL
Student Table
Course Table
course# Cname
PH Pharmacy
CM Computing
CH Chemisty
Πe.studid,e.name,e.Course#,c.Course#,c.Cname
(ρ e (Student)= ⋈ ρ c (Course)
All rows from S are retained and unmatched rows of R are padded
with NULL
Right outer Jointakes all the record form the right relation S that
unmatched any record in the S relation
12
Student Table
Course Table
course# Cname
PH Pharmacy
CM Computing
CH Chemisty
Πe.studid,e.name,e.Course#,c.Course#,c.Cname
(ρ e (Student) ⋈= ρ c (Course)
In Full outer join tables on the both sides of operator contains null
values
It will contain record from both relations that do not join with any
record from the other relation. Those tuples will be padded with
NULLs as usual.
R.ColA = S.SColA
A 1 A 1
D 3 D 3
E 5 E 4
B 2 NULL NULL
F 4 NULL NULL
NULL NULL C 2
It is denoted as ÷.
A B
a 1
b 2
a 2
p 3
p 4
Relation or table "s":-
B
2
3
Thefore r%s
A
b
a
p
14
δ (R)= is indicate that relation with one copy of each tuple that
appears one or more times in R
Example
R=
A B
1 2
3 4
1 2
δ (R)=
A B
1 2
3 4
Sorting
R=
A B
1 3
3 4
5 2
. τB (R) =[(5,2),(1,3),(3,4)]
15
Grouping operator
γ L(R) where L is a list of items in the Relation(R) that are either
a) They ate individual attributes or grouping attributes or
b)θ (A), Where θ is an aggregation operator and A the attribute in
the relation(R) to which the aggregation operator is to applied
It is computed by:
2. Within each group, compute θ(A), for each element θ(A) on list L.
3. Result is the relation whose columns consist ofone tuple for each
group. The components of that tuple are the values associated with
each element of L for that group.
Example
Let R =
Jeans Price
Killer 3400
Lee 3100
Live’s 1800
17
RELATIONAL CALCULUS
Unit Structure
9.0 Objectives
To find out the data from the table we have to use the
operator known as selection and projection that used to select
desired data by applying some predicate calculus or formula on
table
σ p (r)= {t | P (t) }
Where as
x y x v y
19
Set of quantifiers:
Select all the Employee whose having the salary more than 30000
σsalary>30000 (Employee)={t|tEmployeet[Salary]>30000}
Query 2 Find the SSN for each Employee whose having salary
more than 30000
SSN
102
103
104
105
20
Sailor Table
Find the all Sailors ID whose rating is greater than 2 ,here we use
the union operator in the relational algebra,In the relational
calculus we used two exists clause and Connected by or
SID
22
31
95
21
SID
31
In the Relational Cartesian Product , The result will return as all the
attributes from both relation R and S.
Syntax
EmployeeID Designation
101 Lecturer
102 Assistant Professor
103 Professor
DepartNumber DepartName
E1 Electrical
C1 Computer
E3 Electronics
In The tuple Relational calculus , requires two exits clause they are
connected by
22
Syntax
Example
DepartNumber DepartName
E1 Electrical
C1 Computer
E3 Electronics
In The tuple Relational calculus , requires two exits clause they are
connected by
uDepartment(u[DepartNumber]=s[DepartNumber]
u[DepartName]=’Computer’))}
EmployeeID
102
Marks
98
quantifier (∃) and the universal quantifier (∀) can be used to bind
the variables.
1) Find the names of all Clerks who earn more than RS 10,000.
{fN, lN | (sN, posn, sex, DOB, sal, bN) (Staff (sN, fN, lN, posn, sex,
DOB, sal, bN)
2) Find all students who have ever taken a course from every
professor who has ever taught a course.
5) Find all loan numbers for loans with an amount greater than
$1200:
10 ) Find the loan numbers of all loans made jointly to Amit and
Ramesh.
11)Find the names of all customers who have a loan from the Kurla
branch, and find the loan amount.
UNIT V: CONSTRAINTS, VIEWS AND SQL
10
CONSTRAINTS
Unit Structure
10.0 Objectives
10.1 Introduction
10.2 Types of Constraints
10.3 Integrity Constraints
10.0 OBJECTIVES:
10.1 INTRODUCTION
Definition:
Constraints are used to limit the type of data that can go into
a table.
s
Constraints can be specified when a table is created (with
the CREATE TABLE statement) or after the table is created (with
the ALTER TABLE statement).
Syntax:
Data Integrity
Constraints are used to enforce the data integrity. This
ensures the accuracy and reliability of the data in the database.
The following categories of the data integrity exist:
Entity Integrity
Domain Integrity
Referential integrity
User-Defined Integrity
NOT NULL
UNIQUE
PRIMARY KEY
FOREIGN KEY
CHECK
For Example:
OR
OR
For Example:
CHECK CONSTRAINTS:
11
VIEWS
Unit Structure
11.0 Objectives
11.1 Introduction
11.0 OBJECTIVES:
Introduction to views
Data Independence
Security
Updates on views
Comparison between tables and views
11.1 INTRODUCTION
Definition:
Syntax:
CREATE VIEW view_name
HORIZONTAL VIEW
A Horizontal view will restrict the user’s access to only a few rows
of the table.
Example:
VERTICAL VIEW
A vertical view restricts a user’s access to only certain columns of a
table.
Ex:
CREATE VIEW EMP_ADDRESS AS
SELECT EMPNO, NAME, ADDR1, ADDR2, CITY
FROM EMPLOYEE
GROUPED VIEW
A grouped view is one in which query includes GROUPBY
CLAUSE.
It is used to group related rows of data and produce only one
result row for each group.
Ex:
Find summary information of Employee Salaries in sales
Department.
Defining View
View Call
Selelct *
From Summary_Empl_Sal
JOINED VIEWS
A Query based on more than one base table is called as
Joined View.
It is also called as Complex View
This gives a way to simplify multi table queries by joining two
or more table query in the view definition that draws its data
from multiple tables and presents the query results as a
single view.
The view once it is ready we can retrieve data from multiple
tables without joining any table simply by accessing a view
created.
Ex:
Company database find out all EMPLOYEES for respective
DEPARTMENTS.
Schema Definition:
View Definition
View Call
Select * from Emp_Details
DROPPING VIEW
When a view is no longer needed, it can be removed by using
DROP VIEW statement.
Syntax:
Query:
DROP view VABC
QUERY:
DROP view VABC RESTRICT
Here, the query will fail because of RESTRICT option tells DBMS to
remove the view only if no other views depend on it. Since VPQR
depends on VABC, will cause an error.
UPDATING VIEWS
Records can be updated, inserted, and deleted though
views.
UPDATAEBLE VIEWS are those in which views are used
against INSERT, DELETE and UPDATE statements.
Physical Level
Logical Level
View Level
This the highest level of abstraction.
It provides different view to different users. At the view level
users see a set of application programs that hide details of
data types.
The details such as data type etc are not available at this
level.
Only view or Access is given to a part of data according to
the users access right
Physical Data Independence
ADVANTAGES OF VIEWS
2. Query simplicity A view can draw data from several different tables and
present it as a single table, turning multi table queries into single-table
queries against the view.
DISADVANTAGES OF VIEWS
While views provide substantial advantages, there are also three
major disadvantages to using a view instead of a real table:
• Performance
Views create the appearance of a table, but the DBMS must still
translate queries against the view into queries against the
underlying source tables.
This is especially true when views are created that reference other
views, which in turn reference even more views.
The more layers between the base tables and the views, the more
difficult it is to resolve problems attributed to the views.
• Update restrictions
When a user tries to update rows of a view, the DBMS must
translate the request into an update on rows of the underlying
source tables.
This is possible for simple views, but more complex views cannot
be updated; they are
read-only.
VIEWS
View comprises of Query in view definition.
Just like table, view contains Rows and columns which is
fully virtual based table.
The fields in a view are fields from one or more real tables in
the database.
When view is called, it does not contain any data. For that, it
goes to memory and fetches data from base table and
displays it.
E-g: - An I.T. Faculty requires only I.T. related data of
students so we can create view called as Stud_IT_View for
Faculty as below which will only depicts I.T. data of students
to I.T. faculty.
A virtual table is like a table containing fields but it does not
contain any data. In run time it contains the data and after
that it gets free. But table stores the data in database occupy
some space.
Stud_IT_View (Student_Id,Student_Name, I.T.)
We can also add functions like WHERE and JOIN
statements to a view and present the data as if the data
were coming from one single table.
9
TABLES
Table stores the data and database occupies some space in
database.
Tables contain rows and columns, columns representing
fields and rows containing data or records.
EX:
Consider a Employee containing following columns,
EMPLOYEE (Emp_ID, EmpName, Designation, Address, Salary)
12
Unit Structure
12.0 Objectives
12.1 Introduction
12.0 OBJECTIVES:
Data Definition
Aggregate Functions
Null Values
Nested Sub queries
Joined relations
Triggers
12.1 INTRODUCTION
SQL stands for Structured Query Language
It lets you access and manipulate databases.
SQL was developed at IBM by Donald D. Chamberlin and
Raymond F. Boyce in the early 1970s.
The first commercial relational database was released by
Relational Software (Later called as Oracle).
SQL is not a case sensitive as it is a keyword based
language and each statement begins with a unique keyword.
FEATURES OF SQL
SQL COMMANDS:
a. CREATE COMMAND
This statement used to create Database.
Syntax:
CREATE TABLE tablename
(
column_name data_type attributes…,
column_name data_type attributes…,
…
)
• Table and column names can’t have spaces or be “reserved
words” like TABLE, CREATE, etc.
3
Example:
b. ALTER COMMAND:
This statement is used to make modifications to the table
structure.
This statement is also used to add, delete, or modify
columns in an existing table
Syntax:
ALTER TABLE table_name
ADD column_name datatype
OR
ALTER TABLE table_name
DROP COLUMN column_name
OR
ALTER TABLE table_name
MODIFY COLUMN column_name
Example:
ALTER TABLE Employee
ADD DateOfBirth date
OUTPUT:
DROP COMMAND:
Syntax:
DROP TABLE table_name
Example:
DROP TABLE Employee
a. INSERT
The INSERT statement is used to insert a new row in a
table.
Syntax:
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
Example:
INSERT INTO Employee VALUES (4,'Nihar)
INSERT INTO Employee VALUES (5,'savita)
INSERT INTO Employee VALUES (6,'Diana)
OUTPUT:
Emp_Id FirstName
4 Nihar
5 Savita
6 Diana
b. DELETE
The DELETE statement is used to delete records in a table.
Syntax:
DELETE FROM table_name
WHERE some_column=some_value
5
Example:
EMP_Id FirstName LastName Designation City
1 Raj Malhotra Manager Mumbai
2 Henna Setpal Executive Delhi
3 Aishwarya Rai Trainee Indore
OUTPUT:
EMP_Id FirstName LastName Designation City
2 Henna Setpal Executive Delhi
3 Aishwarya Rai Trainee Indore
c. UPDATE
The UPDATE statement is used to update records in a table.
Syntax:
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
Example:
EMP_Id FirstName LastName Designation City
2 Henna Setpal Executive Delhi
3 Aishwarya Rai Trainee Indore
4 Nihar Sarkar
UPDATE Employee
SET Designation='CEO, City='Mumbai'
WHERE LastName='Sarkar’ AND FirstName='Nihar'
OUTPUT:
EMP_Id FirstName LastName Designation City
2 Henna Setpal Executive Delhi
3 Aishwarya Rai Trainee Indore
4 Nihar Sarkar CEO Mumbai
6
a. SELECT CLAUSE
This statement is used for various attributes or columns of a table.
SELECT can have 2 options as SELECT ALL OR SELECT
DISTINCT, where SELECT ALL is default select all rows from table
and SELECT DISTINCT searches for distinct rows of outputs.
Syntax:
SELECT * FROM table_name
b. FROM CLAUSE
This clause is used to select a Relation/Table Name in a database.
c. WHERE CLAUSE
This clause is used to put a condition on a query result.
Example:
Ex1: SELECT * FROM Employee
EmpID FirstName LastName Designation City
1 Raj Malhotra Manager Mumbai
2 Henna Setpal Executive Delhi
3 Aishwarya Rai Trainee Indore
Output:
Aliases
Example:
To select the first name of all the students, the query would be like:
7
Output:
Name
Raj
Henna
Aishwarya
Nihar
In the above query, alias 'e' is defined for the table Employee and
the column FirstName is selected from the table.
SQL ORDER BY
Syntax
SELECT column-list
FROM table_name [WHERE condition]
[ORDER BY column1 [, column2, .. columnN] [DESC]];
8
Example:
Output:
Example:
To select all the Employee from the table above, however, we want
to sort the empoyee descending by their last name.
OUTPUT:
AGGREGATE FUNCTIONS
Example
StudID Name Marks
1 Rahul 90
2 Savita 90
3 Diana 80
4 Heena 99
5 Jyotika 89
6 Rubi 88
AVG() Function
The AVG() function returns the average value of a numeric
column.
Syntax:
SELECT AVG(column_name) FROM table_name
Example:
Find average Marks of Students from above table.
AvgMarks
89.3
10
COUNT() Function
The COUNT() function returns the number of rows that matches a
specified criteria.
Syntax:
SELECT COUNT(column_name) FROM table_name
Example
SELECT COUNT(StudID) AS Count FROM Students
Count
6
SUM() Function
The SUM() function returns the total sum of a numeric column.
Syntax
SELECT SUM(column_name) FROM table_name
Example
OutPut:
SUM
536
MIN() Function
Syntax
SELECT MIN(column_name) FROM table_name
Example
Min
80
11
MAX() Function
Syntax
SELECT MAX(column_name) FROM table_name
Example
Max
90
NESTED SUB-QUERIES
SYNTAX:
SELECT select_Item
FROM table_name
WHERE expr_Operator(SELECT select_item
FROM Table_name)
Operator Description
= Equal To
<> Not Equal To
> Greater Than
>= Greater Than Equal To
< Less Than
<= Less Than Equal To
Operator Meaning
IN Equal to any value returned by the subquery
ANY Compare value to each value returned by the subquery
ALL Compare value to every value returned by the subquery
EXISTS CLAUSE
Example:
SELECT *
FROM suppliers
WHERE EXISTS
(select *
from orders
where suppliers.supplier_id = orders.supplier_id);
This select statement will return all records from the suppliers table
where there is at least one record in the orders table with the same
supplier_id.
Example:
SELECT *
FROM suppliers
WHERE not exists (select * from orders Where
suppliers.supplier_id = orders.supplier_id);
This will return all records from the suppliers table where there are
no records in the orders table for the given supplier_id.
NULL VALUES
"Employee" table:
IS NULL VALUES
Output:
FirstName LastName Address
Hussain Lakdhwala
Ranbir Kapoor
Output:
FirstName LastName Address
Elie Sen Juhu Road
JOINS
Example:
If the first table has 20 rows and the second table has 10 rows, the
result will be 20 * 10, or 200 rows.
This query takes a long time to execute.
Let us use the below two tables to explain the sql join conditions.
Joins can be classified into Equi join and Non Equi join.
It is a simple sql join condition which uses the equal sign as the
comparison operator. Two types of equi joins are SQL Outer
join and SQL Inner join.
Example:
We can get Information about a customer who purchased a
product and the quantity of product.
Example:
To display the product information for each order the query will be
as given below.
Since retrieving the data from two tables, you need to identify the
common column between these two tables, which is the product_id.
QUERY:
SELECT order_id, product_name, unit_price, supplier_name,
total_units
FROM product, order_items
WHERE order_items.product_id = product.product_id;
18
Example
Display all the product data along with order items data, with null
values displayed for order items if a product has no order item.
QUERY
Output:
Example
Example:
Find the names of students who are not studying either
Economics, the sql query would be like, (lets use Employee table
defined earlier.)
QUERY:
Output:
TRIGGERS
Creation of Triggers
Syntax:
Triggers Types:
Example:
If an UPDATE statement updates multiple rows of a table, a
row trigger s fired once for each row affected by the update
statement.
A row trigger will not run, if a triggering statement affects no
rows.
If FOR EACH ROW clause is written that means trigger is
row level trigger.
Example:
If a DELETE statement deletes several rows from a table, a
statement level DELETE trigger is fired only once.
Default when FOR EACH ROW clause is not written in
trigger that means trigger is statement level trigger
Rules of Triggers
Advantages of Triggers:-
Disadvantages of Triggers
13
TRANSACTION MANAGEMENT
Unit Structure
13.0 Objectives
13.1 Introduction
TRANSACTION
A transaction is a logical unit of work that contains one or more
SQL statements. A transaction is an atomic unit. The effects of
all the SQL statements in a transaction can be either all
committed (applied to the database) or all rolled back (undone
from the database).
A transaction begins with the first executable SQL statement.
A transaction ends when it is committed or rolled back, either
explicitly with a COMMIT or ROLLBACK statement or implicitly
when a DDL statement is issued.
To illustrate the concept of a transaction, consider a banking
database. When a bank customer transfers money from a
savings account to a checking account, the transaction can
consist of three separate operation:
EXAMPLE:
To illustrate Banking transaction:
2
PROPERTIES OF TRANSACTION:
ATOMICITY
CONSISTENCY
Example:
Transaction T1
Read (A)
A=A-100
Write (A)
Read (B)
B=B+10
Consistency Constraint
ISOLATION
Isolation requires that multiple transactions occurring at the
same time not impact each other’s execution.
DURABILITY
1. Active
This is the initial state. The transaction stay in this state while it
is executing.
2. Partially Committed
This is the state after the final statement of the transaction is
executed.
3. Failed
After the discovery that normal execution can no longer
proceed.
4. Aborted
The state after the transaction has been rolled back and the
database has been restored to its state prior to the start of the
transaction.
5. Committed
The state after successful completion of the transaction.
We cannot abort or rollback a committed transaction.
TRANSACTION SCHEDULE
Non-Serial Schedule
A schedule where the operations from a set of concurrent
transactions are interleaved.
SERIALIZABILITY
What is Serializability?
A given non serial schedule of n transactions is serializable if it is
equivalent to some serial schedule.
i.e. this non serial schedule produce the same result as of the
serial schedule. Then the given non serial schedule is said to be
serializable.
But there are view serializable schedule that are not conflict
serializable.