Sie sind auf Seite 1von 95

RDBMS

Chapter 1: DATABASE SYSTEM CONCEPT


What is Data?
 Data is a raw material for data processing.
 Data is a raw material which when processed to produce meaningful output.
 In computer terms, symbols, characters, images or numbers are the data these are Input for system
to give a meaningful interpretation.
 Data by itself is not significance.
What is Information?
 Information is data that has been processed to produce meaningful output.
 Information is the processed outcome of data.
 Collection of data which conveys some meaningful ideas is a information.
 The information is significant by itself.
 Information is a meaningful data.
Examples of data and information:
1. The list of Seven Wonders of the World is a data and detailed explanation about each wonder is
information.
2. The temperature of day is a data and when temperature of each day is monitored and recorded by
person is information.
3. If I take picture of you the photograph is information about what you look like is a data.

Fact Captured data and knowledge


Data Information
Database Management System (DBMS):
Database is a collection of inter related data and a set of programs to access and manipulate those data.
Database:
The collection of data usually referred to as the database.
Applications of DBMS
1. Banking System:
For storing information about customers, accounts, loans and banking transactions.
2. Hospital Management System:
For storing information about doctors, patient wards, nurses, medicines, etc.
3. Railway Reservation System:
For storing information about trains, passengers, employees working in railway, etc.
4. Universities:
For storing information about students, courses, employees working in universities, etc.
5. Sales:
For storing customers, product and purchase information.
6. Telecommunication:
For storing, call records, generating monthly bills, storing customer‟s information, etc.

1
RDBMS

File processing system:


 Before the database management system data was stored in file processing system.
 This typical file system supported by conventional operating system.
 The system stores permanent records in various files and it needs different application programs to
add records in file and to retrieve records from file.
Disadvantages of file processing system:
1. Data Redundancy:
 Data redundancy means duplication of information or repeatation of information.
 Some information may be duplicated in several files.
E.g. the address and telephone numbers of particular customer may appear in file that consist of
saving account records and current account records.
 This redundancy leads to higher storage and access cost.
2. Data Inconsistency:
Data inconsistency means various copies of same data with different values.
E.g. If customer address changed the change is reflected in saving account records but not in
current account records
3. Difficult in accessing data:
In file processing system it‟s difficult to access the needed data.
E.g. suppose the bank manager wants to find names of customers who live in Pune city for that
manager has two choices.
1. Generate the list manually or
2. Write an application program to generate list.
But both alternatives are unsatisfactory.
4. Data Isolation:
Data is stored in various files and files may be in different formats, writing new application a
program to retrieve the appropriate data is difficult.
5. Integrity problem
The data values stored in database must satisfy certain types of consistency constraints (conditions)
It‟s difficult to apply consistency constraints in file processing system.
E.g. In bank, account balance should not be less than 500 Rs. It‟s difficult to apply such
constraints in file processing system.
6. Atomicity problem:
Atomicity means either all operations of transaction are completed property or not at all.
E.g. consider a program to transfer 50 Rs. from account A to account B. If system failure occurs
during the execution of the program it‟s possible that the 50 Rs. was removed from account A but
was not credited to account B. Resulting in an inconsistent database state.
It‟s difficult to ensure the atomicity property in file processing system.
7. Security problem:
Not every user of database system should be able to access all the data.
E.g. In banking system, bank employees can‟t access information about customer accounts. The
employees can access information on about only his/her own account.
It‟s difficult to ensure security property in file processing system.
8. Concurrent access anomalies:
Concurrent access means more than one user can access the same data at the same time.
E.g. Consider bank account A with balance 500 Rs. if two customers wants to withdraw 50 Rs. and
100 Rs. from account A at the same time, the result of concurrent executions may leave the account
in an inconsistent state.
It‟s difficult to ensure concurrent access property in file processing system.

2
RDBMS

Advantages of DBMS;
1. Data redundancy is reduced:
 Data redundancy means duplication of data or repeatation of information.
 In DBMS the data redundancy is reduced by storing information at central place.

2. Data inconsistency is avoided:


 Data inconsistency means various copies of same data with different values.
 In DBMS the data inconsistency is avoided.

3. Easy to access data:


 In DBMS we can access any information easily.

4. Centralized management of data:


 In DBMS all data is stored in central location. So it‟s easy to store data and perform various
operations on the data.
5. Data integrity maintained:
 Data integrity means data stored in database both are accurate and consistent or
Data integrity means data values stored in database must satisfy certain consistency constraints
(conditions).
 In DBMS we can easily apply consistency constraints on a database.
E.g. In banking system, account balance should not be less than 500 Rs. we can easily apply such
constraints in DBMS with check constraint.

6. Atomicity is maintained:
 Atomicity means either all operations of transactions are completed properly or not at all.
 In DBMS atomicity is maintained.

7. Security is provided:
 Security means not every user of database system should be able to access all the data from
database.
 In DBMS it‟s easy to provide security to the database.

8. Concurrent access:
 Concurrent access means more than one user can access same data at the same time.
 In DBMS concurrent access results in a consistent database state.

Disadvantages of DBMS
1. Cost: Cost of DBMS software is more.
2. Space: It requires more space to store the data.
3. Centralized data: Due to centralized data management many problems are arises.
4. Backup and recovery: In DBMS taking data backup and performing data recovery are difficult.

3
RDBMS

Data Abstraction:

View Level

View1 View2 ………….. Viewn Higher level

Logical Level Middle level

Physical Level Lowest level

Fig. Three levels of data abstraction or Three level architecture of database

 Data abstraction means hiding certain details of how the data are stored and maintained in the
database.
 For system to be usable it must retrieve data efficiently.
 This led to the design of complex data structures to represent data in a database.
 Since many database system users are not computer trained. So developers hide the complexity
from users through several levels of abstraction to simplify user‟s interactions with the system.
Levels of data abstraction:
1. Physical Level:
 The lowest level of abstraction describes how the data are actually stored in database.
 The physical level describes complex low level data structures in details.
2. Logical Level:
 The next highest level of abstraction describes what data are stored in database and what
relationship exists among those data.
 The logical level of abstraction is used by database administrators, who must decide what
information is to be kept in database.
3. View Level:
 The highest level of abstraction describes only part of entire database.
 End users of database use view level to access data from database.
 The system may provide many views for the same database.

Instances and Schemas


 Collection of information stored in database at particular moment is called an instance of database.
 The overall design of database is called as database schemas.
 The database schema corresponds to variable declaration in programming language.
 The database instance corresponds to value of variable in programming language.
For example:
int a schema

a = 10; instance

4
RDBMS

 Database system has several schemes partitioned according to levels of abstraction.

Physical Schema Schema at physical level

Database Schemas Logical Schema Schema at logical level

Sub Schema Schema at view level

Fig. Classification of Schemas.

1. Physical Schema: Describes database design at physical level.

2. Logical Schemas: Describes database design at logical level.

3. Sub Schemas: The database may have several schemas at view level called sub schemas that
describe different views of database.

Data Independence:
The ability to modify schema definition in one level without affecting schema definition in the next
higher level is called data independence.

There are two levels of data independence


1. Physical data independence
 It‟s the ability to modify the physical schema without affecting application programs to be
rewritten.
 It means we can change or modify physical storage structure or devices, which are used to store the
data without changing application programs.
 Modifications at the physical level are necessary to improve the system performance.

2. Logical data independence:


 Its ability to modify logical schema without affecting application program to be rewritten.
 Its means logical changes in table (and views) such as adding / deleting columns or changing
column lengths doesn‟t require modifications in programs.
 E.g. adding an attribute to table doesn‟t requires to change any commands that have not uses new
attribute.
 Logical data independence is more difficult to achieve than the physical data independence.

Physical data Means ability to change


independence physical schema
Data Independence

Physical data Means ability to change


independence physical schema

Fig. Classification of data independence.

5
RDBMS

Database languages
There are mainly three database languages
1. Data definition language (DDL)
2. Data manipulation language (DML)
3. Data control language (DCL)

1. Data Definition Language (DDL) :


 We specify database schema by a set of definitions expressed by a special language called DDL.
 DDL allows user to define table schemas and apply some consistency constraints.
DDL commands are:
1. Create table statement used to create structure of table and apply some consistency constraints.
e.g.
Create table customer
(cus_id number (5),
cus _name char (20));
cus _city char (20))
2. Alter Table:
Alter table statement is used to modify structure of table
e.g.
Alter table customer
Add (phoneno number (10));

Alter table customer


Modify (cus_ name varchar 2 (25));

3. Truncate Table:
Truncate table command is used to remove all rows from the table but structure of table remains as
it is.
e.g.
Truncate table customer;

4. Drop Table:

Drop table command is used to remove all rows as well as to remove structure of table from
database e.g.
Drop table customer;

5. Rename:
Rename command is used to change the name of the table.
e.g.
Rename customer to employee;
6. Desc (Describe Table):
Desc command is used to display structure of table
e.g.
Desc customer;
7. Create user:
Create user command is used to create new user in a database.
e.g.
Create user raj identified by raj123;

6
RDBMS

2. Data Manipulation Language (DML) :


 DML allows user to access or manipulate data from database.
 The types of manipulates are
1. Retrieval of information stored in database.
2. Insertion of new information into the database.
3. Deletion of information from the database.
4. Modification of information stored in database

There are two types of DML‟s


1. Procedural DML:
Requires users to specify what data are needed and how to get those data.

2. Non-procedural DML:
Requires users to specify what data are needed without specifying how to get those data

DML commands are:


1. Select:
Select command is used to display the information from the table.
e.g. Find names of all customers who stay in city Pune.

Select cus_name
from customer
where cus_city = „Pune‟;

2. Insert :
Insert command is used to insert a row into the table.
e.g. Insert a one row into customer table

Insert into customer


Values (1, „Raju‟ , „Pune‟) ;

3. Delete :
Delete command is used to delete data from the table or to delete rows from the table
e.g. Delete the all customer records who stay in Pune city.

Delete from customer


Where cus_city = „Pune‟;

4. Update :
Update command is used to modify the data from the table
e.g. Change the name of customer Raju to Sagar.

Update customer
Set cus_name = „Sagar‟
where cus_name = „Raju‟;

7
RDBMS

3. Data Control Language (DCL)


 DCL is used to control the access to data from database.
 DCL provides security to the database.

DCL commands are:


1. Grant command:
Grant command used to assign permissions to users to access the data from database.
e.g.
Grant update on customer to raj;

2. Revoke :
Revoke statement is used to remove the permissions from the user to a access the data from
database
Revoke update on customer from raj;
e.g.

3. Commit :
Commit statement is used to make database changes permanent.
e.g.
Commit;

4. Rollback :
Rollback statement is used to discard the database changes
e.g.
Rollback;
5. Savepoint :
Using rollback you can undo all operations but if you want to undo upto specific point we can use
savepoint command.
e.g.
savepoint S1 ;

8
RDBMS

Components of DBMS and overall structure of DBMS

Fig. shows the structure of DBMS.

The functional components of DBMS can be divided into two categories as follows:

1. Query Processor
2. Storage Manager

9
RDBMS

1. Query Processor:
Query processor is responsible for accepting requests from various users and processes them
accordingly Query processor consists of following components.
1) DDL Interpreter:
DDL interpreter interprets or reads DDL statements and records the definition in data dictionary.

2) DML compiler:
 DML complier translates DML statements in a query language (high level language) into
low level instructions that the query evaluation engine understands
 DML compiler also performs query optimization i.e. it takes low cost query evaluation plan
for a given query
3) Query evaluation engine:
Query evaluation engine executes low level instructions generated by DML compiler.

2. Storage Manager
 Storage manager provides the interface between low level data stored in database and application
programs and queries submitted to the system.
 Storage manager responsible for storing, retrieving and updating of data in the database.

Storage manager consist of following components:


1) Authorization and Integrity Manager:
This component applies some integrity constraints and checks authority of users to access data
2) Transaction Manager:
 Transaction manager is responsible for ensure atomicity property of transaction.
 Transaction manager ensures that database remains in consistent state despite system
failure and concurrent transactions proceeds without conflicting
3) File Manager:
File manager is responsible for allocating space on disk storage and allocating data structures
for storing data
4) Buffer Manager:
 Buffer manager manages temporary storage
 Which manages transfer of data from disk to main memory

The storage manager uses some data structures to store data.


These data structures are as follows:
1) Data file:which stores database itself.
2) Data dictionary: which stores data about data i.e metadata
3) Indices: which provides fast access to data items from database

Database users and user interfaces.


1. Naive User:
 They are interact with the system by using already written application program.
 They give data as input through application program or get output data which is
generated by application program.
 Example: Bank cashier.

10
RDBMS

2. Application programmers:
 Application programmers are the users who write the application programs.
 These programmers use programming tools to develop the program.
 RAD technology is used to write the program.
3. Sophisticated users:
 Sophisticated users interact with the system by making the requests in the form of query
language.
 These queries are then submitted to the query processor.
 Query processor converts the DML statements into lower level interactions which are
understandable by storage manager.
 Some sophisticated users can be analyst.

4. Database Administrator (DBA) :


 The person who manages central control over data is called database administrator.
Functions of Database Administrator (DBA:
The functions of database administrator are as follows
1. Schema definition:
The DBA creates database schema by writing set of definitions in DDL.

2. Storage structure and access method definition:


The DBA creates appropriate storage structures and access methods for data stored in database.

3. Schema and physical organization modification:


The DBA performs the modifications to database schema whenever necessary and DBA also
performs modifications to physical storage of database whenever necessary.

4. Granting of authorization for data access:


The DBA assigns permissions for different users to access data from database with grant
command.
DBA also remove the permissions from different users to access data from database with revoke
command.

5. Integrity constraints specification:


The data values stored in database must satisfy certain consistency constraints.
For e.g. In banking system, account balance should not be less than 500 Rupees.
Such constraints must be specified by DBA.

6. Routine maintenance:
DBA performs the routine maintenance of database examples of routine maintenance activities
are : For Example
1. Periodically taking backup of database into CD‟s to avoid the data loss in case of hardware
failure, S/W failure, system crash etc.
2. DBA performs the recovery of data in case of data loss occurs.
3. Another job of DBA is to make the free disk space for data storage and upgrade the disk
space as needed.

11
RDBMS

Client-Server Architecture:

Request
Client Server
Machine Reply Machine

Fig (a) : Client-Server Interaction

Client Client Client Client

Server

Fig (b) : General Structure of client-server system

 In client server system all data stored on server machine and application programs are stored on
client machine.
 When client wants some information from sever at that time client requests the information from
server, this request is served by server and server will gives reply to client as shown in fig. (a).
 The functionality provided by database system can be divided into two parts.
1. Front end
2. Back end

1. Front end / Client:


 Front end of database system consist of tools such as SQL user interface, form interface, report
generation tools, data mining tools and analysis tools.
 By using such tools client can be effectively interact with server.

2. Back end / Server:


 The back end manages access structures, query evaluation, query optimization, concurrency control
and recovery.
 The interface between the front end and back end is through SQL or through application program
standards such as ODBS (Open Database Connectivity) and JDBC (Java Database Connectivity)

SQL user From Report generation Data mining and Front


Interface Interface tools Analysis tools end

Interface
SQL engine Back End (SQL + API)

Fig. Front end and Back end functionality

12
RDBMS

Types of client-server Architectures:


There are two types of client server architectures.
1. Two-Tier Architecture
2. Three-Tier Architecture

User
Client Client

User

Client Application

Network

Database System Server Application


Server
Server

Fig (a) : Two-Tier Architecture

Fig (b) : Tree-Tier Architecture

1. Two-Tier Architecture:
 In two-tier architecture, the application is stored on client machine and database is stored on server
machine.
 When client wants some information then client request to server through query language
statements.
 The application program interface standards like JDBC and ODBC are used for interaction between
client and server.
 For e.g: Online exam of computer fundamental subject.

2. Three-Tier Architecture:
 In three-tier architecture, the client machine acts as front end. The applications are stored at
application server and database is stored at database server.
 If client wants some information then client first request to application server through form
interface. Then application server in turn request to database server to access data.
 The database server return requesting information to application server and then application server
return requesting information to client.
 The three-tier architecture useful for large applications.
 For eg. :
(1) Applications that run of worldwide web (WWW) uses three tire architecture.
(2) Filling of online exam form on MSBTE web site is an example of three-tire architecture.

13
RDBMS

What is RDBMS?
 RDBMS stands for relational database management system.
 RDBMS is a database management system based on relational model defined by E.F. codd
 RDBMS is a collection of interrelated data and set of programs to access and manipulated those
data. In addition to this data in RDBMS is stored in the form of tables.
 Each table in RDBMS has multiple rows and multiple columns.
 Rows of table correspond to records of table and columns of table correspond to attributes of table.
 RDBMS allows us to insert, update, delete, retrieve data from relational database.
 Most poplar RDBMS softwares are oracle, Microsoft SQL server, IBM DB2, MySQL, Sybase and
So on.

Difference between DBMS and RDBMS


DBMS RDBMS

1. DBMS stands for database management system. 1. RDBMS stands for relational database
management system.

2. DBMS is a collection of interrelated data and set 2. RDBMS is a collection of interrelated data and
of programs to access and manipulate data. sets programs to access and manipulated data. In
addition to that data and relationship between data in
RDBMS is represented in the form of tables.

3. Data storage capacity is less than RDBMS. 3. Data storage capacity is more than DBMS.

4. Data security is low as compared to RDBMS. 4. Data security is more as compared to DBMS.

5. It supports single user only. 5. It supports multiple users.

6. DBMS supports 3 rules of E.F. codd out of 12 6. It supports minimum 6 rules of E.F. codd.
rules.

7. DBMS used for simple business application. 7. RDBMS is used for more complex application.

8. In DBMS, it‟s not easy to maintain data integrity. 8. In RDBMS it‟s easy to maintain data integrity.

9. In DBMS normalization process will not be 9. RDBMS fully supports normalization process.
present.

10. DBMS software examples 10. RDBMS software examples


- MS-access - Oracle
- Fox pro - Microsoft SQL server
- Foxporw - IBM DB2

14
RDBMS

Names of various DBMS and RDBMS software


Database Software‟s are:
1) MS – access
2) Fox pro
3) Foxprow
4) Dbase
5) File Maker pro
RDBMS Software‟s are:
1) Oracle
2) Microsoft SQL server
3) IBM DB2
4) My SQL
5) Sybase
6) Ingress

The 12 rules (Codd‟s laws) for fully functional RDBMS:


The DB is called relational DB if it satisfies codd‟s rules.
Codd provides set of 12 rules which qualify a database product as relational. These rules are as follows
1. Information rule:
 All information in relational DB including table names, column names is represented by values in
table.
2. Guaranteed access rule :
 Every piece of data in relational DB, can be accessed by using combination of table name, a
primary key value that identifies row and column name which identifies cell.
 It also provides data independence.
3. Systematic treatment of null values :
 RDBMS handles records that have unknown values in a predefined function.
 The RDBMS differentiate between zero, blanks and nulls in the records and handle such values in a
consistent manner that produces correct answers for comparisons and calculation.
4. Active online catalog based on relational model :
 The description of database and its contents are DB tables and they can be queries online via DML.
 The changes and additions to catalog can be performed with same commands that are used to
access any other data. This feature improves database administrators productivity.
5. Comprehensive data sub language rule :
 The RDBMS supports multiple languages but at least one of them should allow user to do
following operations :
Define tables and views, query and update data, set integrity constraints, set authorization and
define transactions.
 The user productivity is improved because these is one language used for all DB operations.
 In multiuser environment user need not vary about data integrity because its taken care by system.
 Only users with proper authorization are given access to data.

6. View updating rule :


 Any view that can be updated theoretically can be updated using RDBMS.
 Data consistency is ensured because changes made in view are transmitted to base table and vice
versa.

15
RDBMS

7. High level insert, update & delete :


 RDBMS supports insertion, updation & deletion at table level
8. Physical data independence :
 Its ability to modify physical schema without affecting application program to be rewritten.
 It means database administrator can modify physical storage structure or devices which are used to
store data without changing application program.
 Modifications at physical level are necessary to improve system performance.
9. Logical data independence:
 Its ability to modify logical schema without affecting application program to be rewritten. Its means
logical changes in table (and views) such as adding / deleting columns or changing column lengths
doesn‟t require modifications in programs.
 e.g. adding an attribute to table doesn‟t requires to change any commands that have not uses new
attribute.

10. Integrity Independence:


 Like table and view definitions, integrity constraints are stored in online catalog and they can be
changed without changing application programs.
 The integrity constraints specific to particular relational DB must be defined in relational data sub-
language and stored in the catalog.
11. Distribution Independence:
 The application programs are not affected by changes in distribution of physical data.
 This improves systems reliability because application programs will work even if programs and
data are moved t different sites.
12. Non-subversion rule:
 If the RDBMS has a language that accesses the information of a record at a time, this language
should not be used to bypass security and integrity constraints.

Introduction to distributed database


 Distributed database is a database in which portions of the database are stored on multiple
computers within a network.
 In distributed DB system, DB is stored on multiple computers. The computers in distributed system
communicated with one another through network.
 The computers in distributed system may vary in size, function, ranging from workstation upto
mainframe system.
 Computers in distributed system are refered as sites or nodes.

Fig. General structure of distributed system

16
RDBMS

In distributed system there are two types of transactions:


1. Local transaction:
 They access data only from site where transaction was initiated.
2. Global transaction:
 They access data from different sites where transaction was initiated.
There are several reasons for building distributed DB system, they are as follows

1. Sharing data:
The major advantage of building distributed DB is that users at one site may be able to access data
stored at other sites.
e.g. In distributed banking system ach branch stores data related to that branch only its possible for
users in one branch to access data in another branch with this capability transfer of funds are
achieved.

2. Autonomy:
 The primary advantage of sharing data is that each site is able to control data that are stored locally.
 In centralized system, DBA controls entire DB.
 In distributed system there is global DBA & local DBA
 The global DBA controls entire distributed system and part of these responsibility given to local
DBA for each site (i.e. local DBA controls DB located at that particular site)

3. Availability:
 If one site fails in distributed system then remaining sites may be able to continue operating.
 The data items are replicated in several sites, the transactions needs particular data item may find
data item from any other sites. So that failure of other site does not affects entire system.

Types of Distributed database system


. Distributed database systems can be homogeneous or the heterogeneous.
 In homogeneous distributed database system all sites have same DBMS software.
 In heterogeneous distributed database system, all sites have different DBMS software.
 Heterogeneous DDBMS are more complex and more difficult to manage.

Examples of Distributed database systems are:


 Indian railway
 Search Engine(Google)
 Banking systems
 Airline reservation system

17
RDBMS

Introduction to Data Warehousing and Data Mining

Data Warehousing:-
A data warehouse is a repository of information gathered from multiple sources, stored
under a unified schema, at a single site. Once gathered, data are stored for long time,
permitting access to historical data.
Data warehouses provide the user a single consolidated interface to data, making decision-
support queries easier to write.
Moreover, by accessing information for decision support from a data warehouse, the
decision makers ensures that online transaction-processing systems are not affected by
decision support workload.

Data Mining:-
Data mining is the exploration and analysis of large quantities of data in order to discover
valid, novel, potentially useful and ultimately understandable patterns in data.
Data mining is process of collecting large amount of raw data and transforming that data
into useful information
It is known as “Knowledge Discovery in Databases”. When the data is stored in large
quantities in data warehouse, it is necessary to dig the data from the ware house that is
useful and required for further use.
For data mining, different software tools are used to analyze, filter and transfer the data
from the data warehouses.

18
RDBMS

Chapter 2: RELATIONAL DATA MODEL AND SECURITY AND


INTEGRITY SPECIFICATION
2.1Data Models :
 Underlying structure of database is called data model.
 Data model is a collection of conceptual tools for describing data, data relationship, data semantics
(meaning) and consistency constraint.
There are mainly four data models
1. Entity Relationship (ER) Model
2. Relational Model
3. Network Model
4. Hierarchical Model
1. Entity-Relationship (ER) model:

Fig. (a) : ER Diagram

 The ER model was developed by peter chen in 1976.


 The ER-model consists of collection of objects called entities and relationship among these objects.
 An entity is a “thing” or “object” in the real world that is distinguishable from other objects.
 For e.g. (1) each customer is an entity (2) Bank account can be considered as an entity.
 Each entity is described in database by set of attributes.
e.g. customer entity is described by attributes like cus-id, cus-name, cus-city, cus-street.
 A relationship is an association among several entities.
For e.g. Depositor relationship associates a customer with each account that he/she has or depositor
represents relation between customer and account.
 Entity set: it‟s a set of entities of same type.
 Relationship set : it‟s a set of relationships of same type
 ER-dig. consist of following components
1. Rectangles : which represents entity sets.
2. Ellipses : which represents attributes.
3. Diamods : which represents relationship between entity sets.
4. Lines : which inks attributes to entity sets and entity sets to relationship sets.
ER diagram in fig (a) consist of two entity sets customer and account. The diagram also shows a
relationship depositor between customer and account.

19
RDBMS

2. Relational Model :
 The relational model was developed by E.F. codd in 1969.
 The relational model uses a collection of tables to represent both data and relationship among the
data.
 Each table has multiple columns and each column has a unique name.
 The relational model is more popular in the market and its widely used in database system.

Cus_id Cus_name Cus_city Acc_no Acc_no Balance


1 Anil Pune A-101 A-101 500
2 Sunil Mumbai A-102 A-102 1000
3 Yash Delhi A-102 A-103 2000
4 Anil Pune A-103
Fig. Customer Table Fig. Account Table

Fig. (b) sample relational database


Fig. (a) Shows sample relational database consist of two tables.
1. Shows customers of the bank and
2. Shows accounts that belong to those customers.

 For example : In above table, it shows that customer Anil with cus_id 1, lives in city Pune and has
two accounts : A-101 with balance of 500 rupees and account A-103 with 2000 rupees.
Note : That customers Sunil and Yash shares a single account A-102.
 In relational model many to many relationship maintain.

3. Network Model:

1 Anil Pune ----- A-101 500

2 Sunil Mumbai ----- A-102 1000

3 Yash Delhi ----- A-103 2000

Fig (c) : Network Model


Network model was developed by Charles Bachman in 1969.
 The network model uses a collection of records to represent data and relationship among data is
represented by links.
 The records in database are organized as collection of arbitrary graphs.
 In network model each record has multiple parents records and multiple child records i.e. In n/w
model (one to many and many to one) many to many relationship can be maintained.
 It‟s less popular than relational model and more popular than hierarchical model.
 It‟s used in network systems.
 Fig. (c) Shows sample network database using same information as in figure (b).

20
RDBMS

Author A Author A Author A

Book X Book Y

Fig. network model


 Fig. shows another example of network model, it shows there can be more than one author for
book and one author can write multiple books (i.e. In network model many to many relationship
can be maintained).

4. Hierarchical model

1 Anil Pune ----- 2 Sunil Mumbai ----- 3 Yash Delhi -----

A- A-103 2000 A-102 1000


500 A-102 1000
101

Fig. (d) Hierarchical Model

 The hierarchical model is similar to network model


 Data in hierarchical model is represented by collection of records and relationship among data are
represented by links.
 The records in database are organized as a collection of trees.
 In hierarchical model, each record has multiple child records but only one parent record is present.
 i.e. In hierarchical model one to many relationship can be maintained but not many to one
relationship can be maintained.
 It‟s less popular data model in the market.
 It‟s used in main frame database systems.
 Fig. (d) Shows sample hierarchical database using same information as in figure (b).

21
RDBMS

Comparison between different data models:

Relational Model Network Model Hierarchical Model

1. The Relational Model use a 1. Network Model uses a 1. Hierarchical model uses a
collection of tables to represent collection of records to represents collection of records to represent
both data and relationship among data and relationship among data data and relationship among data
data. are represented by links are represented by links.

2. Records in database are 2. Records in database are 2. Records in database are


organized as collection of tables. organized as collection of organized as collection of trees.
arbitrary graphs.

3. It‟s more popular data model in 3. It‟s less popular than relational 3. Its less popular data model in
the market. model and more popular than the market.
hierarchical model.

4. It‟s widely used in database 4. It‟s widely used in network 4. It‟s widely used in main frame
systems. systems. database system.

5. In relational model many to 5. In network model many to 5. In hierarchical model one to


many relationship is maintained. many to many relationship can be many relationship can be
maintained. maintained but not many to many
relationship is maintained.

6. Relational model was 6. Network model was developed 6.


developed by E.F. codd in 1969. by Charles Bachman in 1969.

7. It uses values to relate data 7. It uses links to relate data. 7. It uses pointer to relate data

22
RDBMS

2.2 Relational Model: Basic concepts Attribute and Domain


 Relational model uses a collection of tables to represents both data and relationship among those
data.
 Each table has multiple columns and each column has a unique name.
 Each table has records of particular type.
 Each record has fixed number of attributes.
 Column of table corresponds to attributes of the table.

Cus_id Cus_name Cus_city


1 Anil Pune
2 Sunil Mumbai
3 Yash Delhi
4 Raj Pune
Fig. Customer table

Cus_id Acc_no Acc_no Balance


1 A-101 A-101 500
2 A-102 A-102 1000
3 A-102 A-103 2000
1 A-103 A-104 3000
4 A-104
Fig. Depositor Table Fig. Account Table
Fig. Sample Relational Database

 The first table is customer table for e.g. that the customer identified by cus-id 1 is named Anil and
lives in pune city.
 The 3rd table, account shows for e.g. account A-101 has balance of 1000 Rs.
 The 2nd table, depositor shows which account belongs to which customer
For e.g. acc-n A-101 belongs to customer whose cus-id is 1 and name is Anil and customer Sunil(2)
and Yash (3) share account number A-102.
 Attribute:-Table headings are called attributes of table
 Consider a customer table, it has three columns headers, namely, cus-id, cus-name, cus-city. These
table headers are called attributes.
 Domain:- For each attribute there is a set of possible values called domain of that attribute
 For e.g.
Attributes

Cus_id Cus_name Cus_city


Domain of 1 Sunil Pune
cus_id attributes
2 Yash Mumbai
3 Raj Delhi
Fig. Customer table

23
RDBMS

Key Concept
 Key is an attribute that allows us to uniquely identifies tuples in a relation (Table)
 The attribute which is considered as key attribute must consist of unique values
 For example : Consider customer table
Cus-id Cus-name Cus-city
1 Sunil Pune
2 Yash Pune
3 Raj Mumbai
4 Sunil Delhi
Fig. Customer table
In above customer table ,we can make cus_id as the key attribute because it contains unique values and
distinguish one customer from another customer.
Types of keys
1. Primary key
2. Super key
3. Candidate key
4. Foreign key
1. Primary Key :
 Primary key is a one and only one attribute is used to uniquely identify tuples in a relation.
 The primary key attribute don‟t contains any null value.
 For Example : Primary Key

Cus_id Cus_name Cus_city


1 Raj Pune
2 Yash Pune
3 Raj Mumbai
Fig. Customer table
In above customer table, cus_id attribute is a primary key, because it contains unique values which
are used to uniquely identify tuples in a customer table
2. Super Key
 Super key is a set of one or more attributes that taken collectively, allow us to uniquely identify
tuples in a relation
 For example : Super Key

Cus_id Cus_name Cus_city Cus_State


1 Raj Pune Maharashtra
2 Yash Delhi Delhi
3 Raj Mumbai Maharashtra
4 Sunil Delhi Delhi
Fig. Customer table
 In above customer table, {cus_id} attribute is the super key. Similarly combination of {Cus_id,
Cus_name} is a super key. Similarly combination of {Cus_name, Cus_city} is a super key but only
{Cus_name} attribute of customer table is not a super key because two or more customer may have
same name.

24
RDBMS

3. Candidate Key
 The candidate key is similar with super key
 The candidate key is a set of one or more attributes that taken collectively allow us to uniquely
identify tuples in a relation.
 The minimal super keys are called candidate key.
 For example :
Candidate Key

Cus_id Cus_name Cus_city Cus_State


1 Raj Pune Maharashtra
2 Yash Delhi Delhi
3 Raj Mumbai Maharashtra
4 Sunil Delhi Delhi
Fig. Customer table

In above customer table, {cus_id} attribute is the candidate key similarly combination of
{cus_name, cus_city} attribute is the candidate key but combination of {cus_id, cus_name}
attribute is not a candidate key because as {cus_id} itself is a candidate key.

4. Foreign Key :
 The foreign key is a attribute whose values are derived from primary key of parent table.
 Foreign key represents parent child relationship between two table.
 Foreign key is a attribute in one relation which is used as a primary key in another relation.
Primary Key
Branch_name Branch_city Assets
Kharghar Mumbai 1,00,000
Vashi Mumbai 2,00,000
Nerul Mumbai 3,00,000
Panvel Mumbai 4,00,000
Fig. Branch Table

Foreign Key
Primary Key
Acc_no Branch_name Balance
A-101 Kharghar 500
A-102 Vashi 1000
A-103 Nerul 2000
A-104 Panvel 3000
Fig. Account Table

For Example: The attribute branch_name in account relation is a foreign key which refers values of
primary key column of parent table.

25
RDBMS

ER-Model(Entity Relationship Model):


 ER Model is used for database design.
 The overall logical structure of DB can be graphically represented by ER diagram.
 ER-Model consists of set of objects called entities and relationship among these objects.
 Entity: An entity is a „thing‟ or „object‟ that different from other objects.
For e.g. (1) each customer is an entity.
(2) each bank account can be considered as an entity.
 Each entity is described in database by set of attributes.
For e.g.: The customer entity is described by attributes like cus_id, cus_name, cus_city, cus_state.

 Entity Set: It‟s a set of entities of same type that share same attributes.
For e.g.: Set of all customers of bank can be considered as entity set customer.

 Relationship: Relationship is association among several entities or relationship represents logical


relations between entities.
For e.g.: Depositor represents relation between customer and account.

 Relationship Set: It‟s a set of relationship of the same type.

The ER-diagram consists of following components


1. Rectangles: It represents entity set.
2. Ellipses: It represents attributes of entity set.
3. Diamonds: It represents relationship between entity set.
4. Lines: Which links attributes to entity sets and entity sets to relationship sets.
5. Double Ellipse: It represents multivalued attributes.
6. Dashed Ellipse: It represents derived attribute.
7. Double Rectangle: It represents weak entity set.

Fig(a). ER – Diagram

The ER diagram in fig (a) consists of two entity sets customer and account. The diagram also sows the
relationship depositor between customer and account

26
RDBMS

Symbols used in ER-diagram:

Types of Attributes used in ER Diagram:


The types of attributes used in ER diagram are as follows:
1. Simple attributes
2. Composite attribute
3. Single valued attribute
4. Multivalued attribute
5. Derived attribute
1. Simple Attribute: The attribute which cannot be divided into subparts are called simple attribute.
For e.g.: cus-id attribute in customer entity is a simple attribute.

2. Composite Attribute: The attribute can be divided into sub parts or other attributes are called
composite attributes.
For e.g.: Entity set : Customer
Composite attribute : Cus-name

First-Name Middle-Name Last-Name


The cus-name attribute is a composite attribute; it can be divided into three parts: First Name,
Middle-Name, and Last-Name.
3. Single-Valued Attribute: An attribute have single value for particular entity.
For e.g.: cus-id is a single valued attribute.

4. Multivalued Attribute: An attribute has more than one value for particular entity.
For e.g.: Phone-no is a multivalued attribute

27
RDBMS

5. Derived Attribute: The value for this type of attribute can be derived from the values of other
related attribute.
For e.g.: Age is a derived attribute. The value of age attribute can be derived from date-of-birth
attribute and current date.

Fig. ER diag. with all attributes types


Mapping Cardinalities:
Mapping cardinalities represents number of entities to which another entity can be associated via a
relationship set. The entity sets A & B and R is a relationship set between A & B, then mapping
cardinality must be one of the following:

Fig. (a) One to one Fig (b) : One to Many

Fig (c) Many to one Fig (d) Many to Many

Fig. Mapping Cardinalities


1. One to one
2. One to many
3. Many to one
4. Many to many
1. One to one: An entity in A is associated with at most one entity in B and an entity in B is
associated with at most one entity in A as shown in figure (a).

28
RDBMS

2. One to many: An entity in A is associated with any number of entities in B & an entity in B is
associated with at most one entity in A as shown in figure (b).

3. Many to one: An entity in A is associated with at most one entity in B and an entity in B is
associated with any number of entities in A as shown in figure (c).

4. Many to many: An entity in A is associated with any number of entities in B and an entity in B is
associated with any number of entities in A as shown in figure (d).

Role Indicators:
If an entity plays more than one role, then role indicator describes different roles played by entity set

Fig. : ER-dig. With role indicator

 We indicate roles in ER-diagrams by labelling the lines that connect diamonds to rectangles.
 Fig. shows the role indicators managers and worker between the employee entity set and the works
for relationship set.
Types of Entity Sets:
There are two types of entity sets
1. Weak Entity Set
2. Strong Entity Set
1. Weak Entity Set : An entity set may not have sufficient attributes to form a primary key such
entity set is called Weak Entity Set

Fig. : Weak Entity Set


In above fig. the entity set payment has three attributes payment_no, payment_date and
payment_amount. This entity set does not have primary key,so payment is weak entity set
For a weak entity set to be meaningful, it must be associated with another entity set called
identifying entity set
2. Strong Entity Set: An entity set may have sufficient attributes to form a primary key such entity
set is called Strong Entity Set
In fig(a). customer entity is a strong entity set because it has cus_id as a primary key

29
RDBMS

Enhanced ER Model:
Enhanced ER model includes all concepts of ER model as well as it includes additional concepts such as
specialization or generalization
Specialization :
 The process of designating subgrouping within an entity set is called specialization.
 The specialization of account entity into saving account and checking account.
 The account entity is described by attributes account-no, branch-name, balance.
 The entity set saving-account have all attributes of account and an additional attribute interest-rate
 The entity set checking-account has all attributes of account and an additional attribute overdraft
amount.
 The specialization is a Top-down design process.
 In ER-dig. Specialization is represented by triangle component labelled ISA.
 The label ISA stands for “is A” and represents for e.g. saving-account “is a” account.

Fig. Specialization

Generalization : Its reverse of specialization process


 The generalization is a bottom-up design process, in which multiple entity sets are synthesized into
a higher-level entity set on the basis of common feature.
 The database designer first identifies the customer entity set with attributes cus-id, cus-name, cus-
city, cus-states and credit-rating and an emoloyee entity set with attributes emp-id, emp-name, emp-
city, emp-state and emp-salary.
 The entity set customer and entity set employee have several attributes are common. This
commonality can be expressed by generalization.
 In our example, person is the higher level entity set and customer and employee are lower level
entity sets.
 In this case attributes that are conceptually same had different names in two lower level entity sets.
 To create generalization the attributes must be given common names and represented with higher-
level entity set person.
 We use attribute names person-id, name, city, state with person entity.

30
RDBMS

Fig.Generalization
Examples of ER-Diagrams
1. Draw ER diagram for Banking System
Entity sets Attributes
Customer - Cus-id, Cus-name, Cus-city, Cus-state
Account - Acc-no, branch-name, balance
Loan - Loan no., branch-name, amount
Branch - Branch-name, branch-city, Assets

Fig. : ER-dig. for Banking System

31
RDBMS

2. Draw ER-diagram For Library Management system.


Library maintains data about books, borrowers, issue return details, find collection, suppliers of
book etc. Assume suitable data and display relationship among entities with the help of neat ER-
Diagram.

Fig. : ER-dig. for Library Management System

32
RDBMS

3.Draw ER-dig., for Car insurance company that has a set of customers, each of their own one or
more car. Each car has associated with it zero or any number of recorded accidents.

Fig. ER-dig. for Car Insurance Company

4. Construct ER-dig. for hospital with set of patient and set of medical doctors. Associate with
each patients a log of previous test and examination conducted.

Fig. ER-dig. for Hospital Management System

33
RDBMS

5. Draw ER-dig. of College System. The college maintains the data of students, employees,
books.

Fig. ER-dig. for college system

34
RDBMS

Query Languages :
 Query language is a language in which a user requests information from database.
 Query is a statement for requesting retrival of information.
 There are two types of query languages.
1. Procedural query languages.
2. Non-procedural query languages.

1. Procedural query language


 It requires user to specify what data are needed and how to get those data.
 For example : Relational algebra is a procedural query language.

2. Non-procedural query language


 It requires user to specify what data are needed without specifying how to get those data.
 For example : Tuple relational calculus and domain relational calculus are non-procedural query
languages.
Query Languages

Procedural Non-procedural

Relational Algebra
Tuple relational Domain Relational
Calculus Calculus
Fig. : Query Language

Relational Algebra
Relational algebra consists of set of operations that takes one or two relations as input and produce new
relation as a output.

Relational algebra consist of two types of operations :


1. Unary operations : Operates on one relation
2. Binary operations : operates on two relations
Relational algebra operations

Unary Operations Binary Operations

Select (σ) Sigma Union (U)

Project (π) pi Set difference (-)

Rename (ρ) rho Cartesian product (x)

Set intersection (n)

Natural join ( )
Fig. Relational Algebra operations

35
RDBMS

1. Select Operation (σ) :


 Select operation selects those tuples that satisfy a given condition.
 For giving condition we use =, ≠, <, ≤, >, ≥ comparison operators in select operation.
 Select operation denoted by lowercase Greek latter sigma (σ).
 For combining different conditions into single one we use logical operators like And ( ), OR(v),
NOT ( )
Loan_no Branch_name Amount
L-10 Pune 1000
L-11 Mumbai 2000
L-12 Nashik 3000
L-13 Pune 4000
L-14 Delhi 5000
Fig. Loan relation

For example :
1. Select those tuples of loan relation where the branch is pune

σbranch_name = “pune” (loan)

2. Find tuples of loan relation whose amount is greater than 3000.

σAmount > 3000 (loan)

3. Find those tuples of loan relation whose loan amount is greater than 3000 and whose branch is
Pune.

σamount > 3000 branch-name = “Pune”(loan)

2. Project Operation (π) :


 Project operation display the selected attributes from relation.
 Project operation denoted by uppercase Greek letter pi (π)
For example :
1. Display all loan number and loan amounts from loan relation.

π loan_no, amount (loan)

Combination of Select and Project operation :


 If we want to find only those records who satisfy specific condition then we need to use
combination of select and project operation
For example :
1. Find these customer names who live in pune city

π cus_name (σcus_city = “Pune” (customer))

2. Find only those loan numbers whose loan amount is greater than 4000

π loan_no (σamount > 4000 (loan))

36
RDBMS

3. Rename Operation (ρ) :


 Unlike relations, the results of relational algebra expressions don‟t have a name, so we can give
names to them with rename operation.
 Rename operation is denoted by lowercase Greek letter rho (ρ).
 Given relational algebra expression E, the expression x  E  returns result of expression E under
name x.
 Assume that the relational algebra expression E has n attributes then the expression

x  A1 , A2 , A3 ........ A n  E 

Returns result of expression E under name x and attributes renamed with A, A2, A3, …….. An.
 For Example : Find customer names who live in Pune city and give name employee to result and
give column name as a emp_name instead of cus_name.

 employee(emp_name) (πcus_name (σcus_city=”Pune” (customer))

4. Union Operation (U) :


 Union operation is a binary operation.
 It operates on more than one relation.
 Union operation combines tuples from two relations and form third relation.
 It does not contain duplicate values
 Union operation denoted by U symbol
Cus_name Acc_no Cus_name Acc_no
Sunil A-101 Sunil L-10
Yash A-102 Yash L-11
Raj A-103 Manish L-12
Fig. Depositor relation Fig. borrower relation
 For eg. 1 : Find the names of all customers who have either an account in bank or who have taken
loan from bank or both.

Πcus_name (depositor) U πcus_name (customer)

Result :
Cus_name
Sunil
Yash
Raj
Manish names who have either account or loan or both.
Fig. : Customer

5. Set-intersection operation (∩) :


 It‟s a binary operation, operators on two relations.
 It displays common values from two tables.
 Its denoted by ∩ symbol.
 It does not contain duplicate value.

37
RDBMS

 For e.g. 1 : Find the customer names who have both account and loan at the bank.

πcus_name (depositor) ∩πcus_name (borrower)

Result :
Cus-name
Sunil
Yash
Fig. : Customer names with both account and loan at bank.
6. Set difference(-) :
 It‟s a binary operation, operates on two relations.
 Its used to find those tuples that are in one relation but not in another relation.
 Its denoted by –(minus) symbol.
 It does not contains duplicate values.
 For e.g. (1) : Find all customers who have account at the bank but who have not taken loan from
bank.
πcus_name (depositor) – πcus_name (borrower)

Result
Cus-name
Raj

7. Cartesian-product operation (X) :


 It‟s a binary operation operates on two relations.
 Cartesian product is the operation where one relation would be multiplied by other relation.
 Its denoted by a cross (X) symbol.
 Cartesian product of relation r1 and r2 written as r1  r2 .

Cus_name Acc_no. Loan_no Branch_name Amount


Sunil L-10 L-10 Pune 500
Yash L-11 L-11 Mumbai 1000
Sachin L-12 L-12 Pune 2000
Fig. Borrower relation Fig. Loan relation

Borrower.loan_no Loan.Loan_no Branch_name Amount


Cus_name
Sunil L-10 L-10 Pune 500
Sunil L-10 L-11 Mumbai 1000
Sunil L-10 L-12 Pune 2000
Yash L-11 L-10 Pune 500
Yash L-11 L-11 Mumbai 1000
Yash L-11 L-12 Pune 2000
Sachin L-12 L-10 Pune 500
Sachin L-12 L-11 Mumbai 1000
Sachin L-12 L-12 Pune 2000
Fig. Borrower x loan

38
RDBMS

 For e.g. (1) : Find names of all customers who have loan at the bank and also find their respective
loan amount.
Πcus_name, amount (σborrower.loan_no.=loan.lon_no (borrower x loan))

 For e.g. (2) : Find names of customers who have taken loan from Pune branch.
Πcus_name (σbranch_name=”pune” (σborrower.loan_no.=loan.lon_no (borrower x loan)))

8. Natural Join Operation ( ):


 It‟s a binary operation, operates on two relations.
 It combines certain selection and Cartesian product operations into single operation.
i.e. It combines select and Cartesian product operation into single operation.
 Its denoted by join symbol .
Cus_name Loan_no Loan_no Branch_name Amount
Sunil L-10 L-10 Pune 500
Yash L-11 L-11 Mumbai 1000
Sachin L-12 L-13 Pune 2000
Fig. Borrower table Fig. Loan relation
Loan_no Cus_name Branch_name Amount
L-10 Sunil Pune 500
L-11 Yash Mumbai 1000
Fig. Borrower loan
 For e.g. (1) : Find names of all customers who have loan at the bank and also find their respective
loan amount.
cus_name, amount (borrower loan)

 For e.g. (2) : Find names of customers who have taken loan from Pune branch.

Πcus_name (σbranch_name=”pune” (borrower loan))

Solved Examples:
Example: 1. Consider the structure as
product_master = {prod_id, prod_name, rate}
purchase_details = {prod-id, quantity, dept_no., purchase_rate}
Write relational algebra expression for following:
1. Get product_id, prod_name and quantity for all purchased products.
2. Get the products with rates between 100 and 4500.
Answer: 1. πprod_id, prod_name, quantity (product_master purchase_details)
2. πprod_id, prod_name (σrate > = 100 rate < = 4500 (product_master)

Example :2. Consider following relational database patient_details (patien_id, patient_name,


prescription, doctor) give an expression in relational algebra for following queries:
(1)To get prescription given to Sanjay.
(2)To get patient_id with their name.
Answer : (1) πprescription(σpatient_name = “Sanjay” (patient_details))
(2) πpatient_id, patient_name (patient_details)

39
RDBMS

Example :3.Consider the structure as :


Customer (cust.id, cust.name, cust.add, cust.city, account.no)
Write relational algebra expression for following
(1) Find information of only those customers who live in city Pune.
(2) Find cust.id, cust.name from the customer database.
Answer :(1) σcust.city = “pune” (customer)
(2) πcust.id, cust.name (customer)

Tuple-relational calculus:
 It‟s a non-procedural query language; it describes the desired information without giving a specific
procedure for obtaining that information.
 The query in tuple relational calculus is written as t P t  where t is a set of all tuples such that
predicate P is true for t.
 We use t  A  to denote the value of tuple t on attribute A and we use t  r to denote that tuple t Is
in relation r.
 The complex queries in tuple relational calculus is written as :  t  r  a t   means, there exist a
tuple in relation r such that predicate Q t  is true.
(If you want to particular attributes rather than displaying whole table then we use there exists
construct).
For example:
(1) Find loan_no, branch_name and amount from loan relation whose loan amount is greater than
1000.
t / t  loan  t amount  1000

(2) Find customer tuples who live in city pune.

t / t  customer  t cus-city  "Pune"

Domain Relational Calculus:


 It‟s a non-procedural query language.
 It describes desired information without giving a specific procedure for obtaining that information.
 The query in domain relational calculus is written as :  x1 , x2 ; ........ xn |P  x1 , x2 , .......xn 
where x1 , x2 , .......xn represents domain variables and P represents a predicate or condition.
 x1 , x2 ; ........ xn  r Where ,r is a relation with n attributes and x1 , x2 , .......xn are domain
variables.
For example: 1.Find loan-no, branch-name and amount for loans over 1000.
 1, b, a | l, b, a  loan  a  1000
2. Find customer tuples who live in Pune city
 n, c, s | n,c, s  customer  c  "Pune"

Normalization:
40
RDBMS

Definition: The normalization is process of making database system simple by reducing data redundancy
or Normalization is a scientific method of breaking down complex table structure into simple table
structure by using certain rule.
 Using normalization we can:
1. Reduce data redundancy
2. Avoid data inconsistency
3. Avoid wastage of storage space
 The normalization process is based on concept of normal forms.
 Most widely used normal forms are :
1. First Normal Forms (1NF)
2. Second Normal Form (2NF)
3. Third Normal Form (3NF)
4. Boyce-codd Normal Form (BCNF)

Fig.Normal forms
The First, Second and Third normal forms are developed by Dr. E.F. Codd and the BCNF is developed
by Dr. Boyce and Dr. E. F. Codd.
Objective of Normalization or Need of Normalization or Purpose of Normalization
1. To develop “good” database design
2. To avoid data redundancy
3. To avoid data inconsistency
4. To avoid wastage of storage space.
5. To avoid various types of update anomalies or problems.
Data Redundancy and Updating Anomalies
 The data redundancy means duplication of data or repetition of information in the database.
 The data redundancy wastage the large amount of storage space.
 The main goal of relational database design is to avoid wastage of storage space by reducing data
redundancy.
 Consider following example of loan schema for understanding how data redundancy occurs :
Loan-schema = {branch-name, branch-city, Assets, loan-no, cus-name, amount}
Branch_name Branch_city Assets Loan_no Cus_name Amount
Kharghar Mumbai 100000 L-10 Anil 1000
Shivaji Nagar Pune 200000 L-11 Sachin 2000
Sai Nagar Satara 300000 L-12 Rahul 3000
Fig. Loan Relation
 This relation schema used above have following update Anomalies :
1. Insertion Anomalies:
 if we want to add following new row in above loan relation
(Kharghar, Mumbai, 100000, L-14, Sagar, 500)
 Then the values of attribute branch_name, branch_city and assets are repeated and this will wastage
the large amount of storage space

41
RDBMS

 If we want to insert record of branch then we must have to insert corresponding values of loan-no,
cus-name and amount attributes.

2. Delete Anomalies:
 If we delete information regarding all customer of specific branch then the corresponding
information regarding to that branch also lost.
e.g. If we want to delete the Sachin customer record then the information regarding Shivaji Nagar
Branch is also lost.

3. Modification Anomalies:
 If the value of any attribute is changed then we must have reflect the change in throughout the table
otherwise data inconsistency occurs.
e.g.: The assets value of Kharghar branch is changed from 100000 to 400000 then we need to
update all assets values of Kharghar branch to 400000 otherwise data inconsistency occurs.

Relational database design:


When we are storing data in single table then data redundancy and inconsistency occurs, the goal of
relational database design is to divide the single table two set of tables in such way that it avoids data
redundancy and data inconsistency.
Decomposition:
 Decomposition means dividing the single table into set of tables,
 We decompose the table in such way that we can recover the original table from decomposed tables
by taking natural join of them.
 If we recover the original table from decomposed tables then decomposition is said to be lossless
join decomposition.
 If original table is not recovered from decomposed tables then decomposition is said to be lossy
join decomposition.
 Example of decomposition :
Rollno Name City
1 Sunil Pune Original relation
2 Sunil Mumbai
Fig. Relation S.
We decompose, relation S into two relations S1(Rollno, Name) and S2(Rollno, City)

Rollno Name Rollno City


1st possible
1 Sunil 1 Pune
decomposition
2 Sunil 2 Mumbai
Relation S1 Relation S2
If we take natural join of S1 and S2 (S1 S2) then resultant relation is :
Rollno Name City
1 Sunil Pune
2 Sunil Mumbai
(S1 S2)
The natural join of S1 and S2 forms the original relation so above decomposition is loss less join
decomposition.
We decompose relation S into relation S3 (Roll No, Name) and S4 (Name, City)

42
RDBMS

Rollno Name Name City 2nd


possible
1 Sunil Sunil Pune
decomposition
2 Sunil Sunil Mumbai
Relation S3 Relation S4
If we take natural join of S3 and S4 (S3 S4) then resultant relation is :
Rollno Name City
1 Sunil Pune
1 Sunil Mumbai
2 Sunil Pune
2 Sunil Mumbai
(S3 S4)
The natural join of S3 and S4 don‟t forms the original relation, so above decomposition is lossy join
decomposition. Thus a lossy join decomposition is a “bad database design”.

Functional Dependency :
The normalization is bases on functional dependency. Given relation R, the attribute B is functionally
dependent on attribute A. if and only if, for each value of A there is exactly one value of B. Attribute A is
called determinant or we can say that attribute A functionally determines the attribute B.
The functional dependency denoted by, A  B
For eg. : Consider following student table :
Rollno Name City
1 Sunil Pune
2 Sachin Mumbai
3 Yash Satara
Fig. Student Relation
In above table functional dependencies are
Rollno  Name
Rollno  City
Give a particular value of rollno there is exactly one value of name.
For e.g. For Rollno. 1 there is exactly one value of name, Sunil. Hence name is functionally dependent
on roll no.
Similarly, for each value of rollno there is exactly one value of city.
Hence, the attribute city is functionally dependent on attribute Roll no.
The attribute Rollno. is determinant, you can also say that Rollno. determines the name and city.

Process of Normalization using Normal Forms :


1. 1NF (First Normal Form)
2. 2NF (Second Normal Form)
3. 3NF (Third Normal Form)
4. BCNF (Boyce Codd Normal Form)

1. 1NF (First Normal Form) :


 The table is said to be in 1NF, if and only if each cell of table contains exactly one value or all
values of column are atomic.

43
RDBMS

Supplierno Status City Productid Qty


P1 300

S1 20 Mumbai P2 200
P3 400
P4
200
S2 10 Pune
P2 400
P4
100
S3 20 Mumbai
P3 200
P1
200
S4 10 Pune
P5 500

S5 40 Delhi P1 400
Fig (a) : Supplier table not in 1NF

 The above table is not in 1NF because the cells product-id and quantity contains more than one
value. So we need to convert above relation to 1NF as follows :

Supplierno Status City Productid Qty


S1 20 Mumbai P1 300
S1 20 Mumbai P2 200
S1 20 Mumbai P3 400
S2 10 Pune P4 200
S2 10 Pune P2 400
S3 20 Mumbai P4 100
S3 20 Mumbai P3 200
S4 10 Pune P1 200
S4 10 Pune P5 500
S5 40 Delhi P1 400
Fig. (b) : Supplier table is in 1NF

2. 2NF (Second Normal Form ) :


 The table is said to be 2NF if and only if it‟s in 1NF and every non-key attribute is functionally
dependent on whole key but not on just part of key.
 The table in fig. (b) is in 1NF but not in 2NF, so we need to convert it into 2NF.
 In the table, for each value of supplierno, there is more than one value of qty.
 For e.g. for supplierno S1 there are three values of qty-300, 200, 400, hence qty is not functionally
dependent on supplierno.
 Similarly for each value of productid there is more than one value of qty.
 For e.g. for productid P1, there are three values qty-300, 200, 400, hence qty. is not functionally
dependent on productid.
 But for combination of supplierno and productid there is exactly one value of qty hence quantity is
functionally dependent on the whole key (supplierno + productid)

44
RDBMS

 Now, we check attribute city is functionally dependent on whole key or not.


 For each value of supplierno there is exactly one value of city.
 For e.g. for supplierno S1 there is exactly one value of city, Mumbai. Hence city is functionally
dependent on part of key (supplierno) but for each value of productid there is more than one value
of city. Similarly dependency is true for status attribute. Therefore table supplier is not in 2NF.

Steps for converting a table into 2NF :


1. Find & remove attributes that are functionally dependent on only part of key and place them in
different table along with part of key attribute.
2. Group the remaining attributes in another table.
In above example, city and status attributes are functionally dependent on whole key but they are also
dependent on part of key (supplierno) so we place them into separate table supplier details along with
supplierno attribute.
Supplierno Status City Supplierno Productid Qty
S1 20 Mumbai S1 P1 300
S2 10 Pune S1 P2 200
S3 20 Mumbai S1 P3 400
S4 10 Pun S2 P4 200
S5 40 Delhi S2 P2 400
Fig. (c) Supplier Relation S3 P4 100
S3 P3 200
S4 P1 400
S4 P5 500
S5 P1 400
Fig. (d) Product Relation
Fig. Relations are in 2NF
3. 3NF (Third Normal Form)
 The table is said table in 3NF if and only if its in 2NF and every non-key attribute is functionally
dependent only on primary key.
 The primary key in table supplier relation (in fig. (c)) is supplierno attribute.
 For each value of supplier supplierno there is exactly one value of status and city therefore both
status and city attributes functionally dependent on supplierno (whole key). Hence table is in 2NF.
But attribute status is also dependent on attribute city and attribute city is not a primary key, so
above table (c) is not in 3NF.

Steps for converting table into 3NF


 Find and remove non-key attributes that are functionally dependent on other than primary key
attribute and place them in different table.
 Group the remaining attributes in another table.
In above example status attribute is dependent on primary key but the status is also dependent on non-
primary key attribute city. So we remove status attribute and place them into separate table along with
city attribute.
City Status
Mumbai 20
Pune 10
Delhi 40

45
Supplier-no City
RDBMS
S1 Mumbai
Fig. (e) City_status relation S2 Pune
S3 Mumbai
S4 Pune Fig. (f)
supplier_city relation S5 Delhi
4. BCNF (Boyce-Codd Normal Form) :
The relational R is in BCNF, if and only if it‟s in 3NF and every determinant is a candidate key.
The functional dependency
x y
The Y is functionally dependent on x,
The X is called determinant of the functional dependency.
Candidate Keys

Stud_id Name Course Grade


1 Anil CM A
2 Sunil CO C
3 Sagar ME B+
1 Anil IF B
2 Sunil IF A+
Fig. Student relation is in 3NF but not in BCNF. In above student relation functional dependencies are
Stud_id + Course  Grade
Name + Course  Grade
Stud_id  Name Trivial Functional dependencies
Name  Stud-id

From above functional dependencies, stud_id + course, Name + course determinates are candidate keys
but determinants stud_id and name are not candidate key, so above table is not in BCNF.
Steps for converting table in BCNF
1. Find trivial functional dependency attributes and place them in different table.
2. Group remaining attributes into another table.
Stud_id Name Grade
Stud_id Course
1 Anil A
1 CM
2 Sunil C
2 CO
3 Sagar B+
3 ME
Fig. stud_id_name relation
1 IF B
2 IF A+
Fig. Grade Relation

Multivalued Dependency :
 The given relation R, the attribute B is multi-dependent on attribute A, if for each value of A there
is more than one value of B.

46
RDBMS

 The multivalued dependency is denoted by, A   B we say that attribute B is multidependent


on attribute A.
 The multivalued dependency is generalization of functional dependency.
 The every functional dependency is multivalued dependency but not every multivalued dependency
is a functional dependency.
 The fourth normal form (4NF) is based on multivalued dependency.
For e.g. : Consider following customer table

Cus_name Cus_city Cus_state


Sunil Pune Maharashtra
Sunil Delhi Delhi
Yash Mumbai Maharashtra
Fig. Customer Relation

In above table multivalued dependencies are :


Cus_name  Cus_City
Cus_name  Cus_State
This means the attribute Cus_city and Cus_state multidependent on attribute Cus_name.
For e.g. For Cus_name, Sunil there is more than one value of Cus_city, Pune, Delhi and for Cus_name
Sunil there is more than one value of Cus_state, Maharashtra and delhi.
The attribute cus-name multidetermines cus_city and cus_state attributes.

Write difference between 3NF and BCNF


3NF BCNF

1. 3NF is third formal form developed by Dr. E.F. 1. BCNF is a Boyce Codd normal form developed
Codd by Dr. Boyce and Dr. E. F. Codd.

2. The relation is said to be in 3NF if and only if 2. The relation is said to be in BCNF if and only if
its 2NF and every non-key attribute is functionally its in 3NF and every determinant is a candidate key.
dependent only on primary key.

3. Data redundancy is more as compared with 3. Data redundancy is less as compared with 3NF .
BCNF.

4. Less consistency and accuracy of database is 4. More consistency and accuracy of database is
provided as compared with BCNF. provided with 3NF.

5. 3NF is more advanced than 1NF and 2NF. 4. BCNF is known as the modified version of 3NF.

Write difference between Functional Dependency and Multivalued Dependency


Functional Dependency Multivalued Dependency

47
RDBMS

1. Functional dependency depoted by : A B 1. Multivalued dependency is denoted by


. A  B

2. The attribute B is functionally dependent on 2. The attribute B is multivalued dependent on


attribute A if and only if for each value of A there attribute A, if and only if for each value of a there is
is exactly one value of B. more than one value of B.

3. The normal forms 2NF, 3NF and BCNF are 3. The normal forms 4NF is based on multivalued
based on functional dependency. dependency.

4. Every functional dependency is multivalued 4. Not every multivalued dependency is functional


dependency dependency
5. Example
5. Example
Rollno Name City
Cus_name Cus_city Cus_State
1 Sunil Pune
Sunil Pune Maharashtra
2 Yash Mumbai
Sunil Delhi Delhi
Fig. Student table
Fig. Customer Table
In above table functional dependency are
In above table Multivalued dependencies are
Roll No.  Name cus-name  cus-city
Roll No.  City cus-name  cus-state

Integrity Constraints:
 Integrity constraints means data value stored in database must satisfy certain conditions.
 Integrity constraints are used to avoid invalid data entry into a table.
 Integrity constraints are used to maintain correctness and accuracy of data stored in database.

Examples of integrity constraints:


1. An account balance can‟t be NULL.
2. No two account can have same account number.
3. In bank account balance can‟t be less than 500 Rupees.
Integrity constraints

Domain Integrity Entity Integrity Referential


Constraint Constraint Integrity constraint

NOT NULL Check Primary Key Unique


Constraints Constraint Constraint Constraint

Fig. : Types of Integrity Constraints

1. Domain Integrity Constraints:


 It‟s used to maintained value according to user specification or requirements.

48
RDBMS

 These integrity constraints are apply at column level and hence name given as domain integrity
constraints.
 There are two types of domain integrity constraints
a) NOT NULL constraint
b) Check constraint

a) NOT NULL Constraint:


 By default all columns in a table allow null values when a „NOT NULL‟ constraint is apply on a
column then column will not allow null values.
 Not NULL constraints can be specified at the time of table certain with create table command or
can be specified after table creation with alter table command

 e.g. use of NOT NULL constraint


Create table account
(acc_no char(10) NOT NULL,
balance number (6));

In above example acc_no attribute should not contain null values.


o/p : Desc account

Name NULL? Type


acc_no. NOT NULL char (10)
balance number (6)

b) Check constraint:
 The check constraint defines a condition that each row must satisfy.
 The check constraint can be specified at the time of table creation with create table command or can
be specified after table creation with Alter table command

 e.g. Use of check constraints


Create table account
(acc_no char(10),
balance number(6),
check (balance >= 500));

In above example check constraint checks balance value it must be greater than or equal to 500
Rupees.

2. Entity Integrity Constraint:


 It‟s used to assure that every relation have a primary key and values of primary key are not
repeating and not null.
 There are two types of Entity Integrity constraints
a) Primary key constraint
b) Unique constraint

a) Primary Key Constraint:


The primary key constraint avoids duplication of rows and does not allow null values.

49
RDBMS

 e.g. Use of primary key constraint


Create table account
(acc_no char (10),
balance number (6),
primary key (acc_no.));

In above example acc_no attribute will not allow duplicate values and null values.
b) Unique Constraint :
The unique constraint avoids the duplication of rows but it allows null values.

 e.g. Use of unique constraint


Create table account
(acc_no char (10),
balance number (6)
unique (acc_no.));

In above example acc_no attribute will not allow duplicate values but it allows null values.

3. Referential Integrity Constraint:


 Referential integrity means to ensure that a value that appears in one relation for a given set of
attributes also appears for a certain set of attributes in another relation. This condition is called
referential integrity.
 Referential integrity is used to establish a parent child relationship between two tables baring a
common column.
 Foreign key constraint can be defined at the column level or table level.
 Foreign keys can be specified at the time of table creation with create table command, by using the
foreign key clause.
 For example
Primary Key Primary Key Foreign Key

Branch_name Branch_city Assets Acc_no Branch_name Balance


100000 A-102 Vashi 1000
Vashi Mumbai
200000 A-102 Nerul 2000
Nerul Mumbai
Fig. Branch Table Fig. Account Table
(Parent Table) (Child Table)

For e.g.Use of on foreign key constraint

50
RDBMS

Create table Branch


(Branch_name char (20),
Branch_city char (20),
Assets number (10, 2),
Primary key (Branch_name));

Create table Account


(Acc_no char (10),
Branch_name char (20),
Balance number (8, 2),
Primary key (Acc_no),
Foreign key (Branch_name) references Branch);

Fig. Foreign key declaration using SQL DLL

The above foreign key declaration specifies that for each account tuple, branch name specified in the
tuple must exist in the branch relation.

On delete cascade constraint:


On delete cascade constraint tells RDBMS that when row in parent table is deleted the dependent rows in
child table will also automatically get deleted.
For e.g. Use of on delete cascade constraint

Create table Branch


(Branch_name char (20),
Branch_city char (20),
Assets number (10, 2),
Primary key (Branch_name));

Create table Account


(Acc_no char (10),
Branch_name char (20),
Balance number (8, 2),
Primary key (Acc_no),
Foreign key (Branch_name) references Branch on delete cascade);

Fig. On delete cascade constraint declaration using SQL DLL

In above example when rows of any branch from branch relation is deleted then dependent rows of same
branch from account relation will be automatically gets deleted.

Chapter. 3 – INTERACTIVE SQL


3.1 Introduction to SQL:

51
RDBMS

SQL is a structured query language used to manage and manipulate data stored in database
The SQL is divided into different parts as below:
Data Definition Language (DDL): Used to define how data will be stored in the able and
databases.
Data Manipulation Language (DML): DML is used to manipulate i.e. add, modify or delete data
to tables.
Data control Language (DCL): DCL allows user to keep control on the operations taking place on
data tables.
Data Query Language (DQL): DQL is used mainly to display the results of the query.

3.2 Data Types in SQL :


1. Char (n) :
This data type is used to store characters, symbols and numbers.
This data type stores fixed length character string.
The maximum data stored by this data type is 2000 characters
e.g name char(10)
If user enters 3 character names then 10 bytes are allocated to store name.

2. Varchar2 (n):
This data type is used to store characters, symbols and numbers.
This data type stores variable length character string.
The maximum data stored by this data type is 4000 characters
e.g name varchar2(10)
If user enters 3 character names then only 3 bytes are allocated to store name not 10 bytes
Varchar2 data type saves memory space as compared with char data type.

3. Number (p,s) :
This data type is used to store fixed or floating point numbers. P is the precision and S specifies
scale. The maximum precision is 38 digits.
e.g. Percentage number (4, 2)

4. Long:
This data type is used to store the variable length character string containing data up to 2 GB.
The long data type can be assigned to only one column in a table.
e.g doc long

5. Date:
This data type is used to store date and time in a table.
The standard format used to store the date is DD-MON-YY
e.g. dob date.

3.3 DDL(Data Defination Language) Commands

1. Create table: this command is used to create structure of table in the database

52
RDBMS

This command is also used to apply some integrity constraints on table


Syntax: Create table < table name>
( column_name 1 datatype(size),
column_name 2 datatype(size), ………….);
Example:
Create table student ( rollno number(5), name char(10), class char(10));

2. Desc(describe table): : this command is used to display structure of table.


Syntax:desc table_name;
Example:desc student;

3. Alter table: this command is used to modify the structure of table.


With alter table command we can add new column to existing table or to modify the data type of
particular column or to drop any particular column from the table.
Syntax for add option:
alter table <table name>
add ( column_name 1 datatype(size),
column_name 2 datatype(size), ………….);
Example:1
alter table student add (percentage number(4,2));
Syntax for modify option:
alter table <table _name>
modify ( column_name 1 datatype(size),
column_name 2 datatype(size), ………….);
Example:2
alter table student modify (name varchar2(20));
Syntax for drop option:
alter table <table _name> drop column column_name;
Example:3
alter table student drop column class;

4. Truncate table: this command is used to remove all rows from table but structure of table remains
it is.
Syntax: Truncate table <table name>;
Example: Truncate table student;

5. Drop table: this command is used to remove all rows from table as well as structure of table from
database.
Syntax: drop table <table name>;
Example: drop table student;

6. Rename: this command is used give new name to table.


Syntax: rename old_table_name to new_table_name;
Example: rename student to stud;

7. Create user: this command is used to create new user in a database..


Syntax: create user username identified by password;
Example: create user abc identified by abc123;

Difference between drop table and truncate table command


DROP TRUNCATE
1.It is DDL statement which deals with the 1.It is DDL statement which deals only with the

53
RDBMS

structure of the tablealong with data data from table


2. It deletes entire table at once from disk 2. It deletes all records from table at once
3. Column Structure of table does not remain on 3. Empty column structure of the table remains
the disk. on the disk.
4.Syntax : Drop table <tablename>; 4. Syntax : Truncate table <tablename>;
5. Example : Drop table student; 5. Example : Truncate table student;

3.4 DML(Data Manipulation Language) Commands


1. Insert – it‟s used to insert or add new data into table.
1. Syntax1: syntax for insert command without defining attributes
Insert into <Table_name> values (value1,value2,…..);
Example 1: insert into student values(1,‟raj‟,60);

2. Syntax2: syntax for insert command with defining attributes


Insert into <Table_name> (col1,col2,.…) values (value1,value2,…..);
Example 2: insert into student (rollno,name,percentage) values(2,‟rajesh‟,70);

3. Syntax3: To insert values for specific attributes in a table.


Insert into <Table_name> (col1,col2) values (value1,value2);
Example 3: insert into student (rollno,name,) values(3,‟ram‟);

4. Syntax4: To insert more than one row.


Insert into <Table_name>values (&attribute1, &attribute2,&attributen);
Example 4: insert into student values (&rollno,‟&name‟,&percentage);
3. Update: Update command is used to modify the existing data from table

Syntax: update table_name


set column name=new value
where condition;
Example: update student set name=‟sunil‟ where name=‟raj‟;

3. Delete: delete command is used to remove all or specific rows from table
Syntax: delete from table_name where condition;
Example: delete from emp where where name=‟ram‟;

5. Select: select command is used to retrieve all or specific data from table

Syntax 1: select column_name1, column_name2, …. from table_name where condition;


Example 1: select rollno,name from student where percentage >60;

Syntax 2: select * from table_name where condition;


Example 2: select * from student where percentage >60;

3.8 DCL (Data Control Language) Commands


1. Grant command-
This command is used to assign permissions to users to do operations on the other users object.
Syntax:

54
RDBMS

Grant < privilege list> on <relation name> to <users> ;


< privilege list>: is a list of permissions like select, insert, update, delete, all
<relation name>:is a name of table, view on which permissions are assigned
<users>:is a list of users to which permissions are assigned
Example: Grant select, update on student to Sunil;
Above grant statement assigns select and update permissions to sunil user on
student table

2. Revoke command-
Revoke command is mainly used to remove or take out the granted privileges from the specific user.
Syntax:
Revoke < privilege list> on <relation name> from <users> ;
< privilege list>: is a list of permissions like select, insert, update, delete, all
<relation name>:is a name of table, view on which permissions are removed
<users>:is a list of users from which permissions are removed.
Example: revoke update on student from Sunil;
Above revoke statement remove update permission from sunil user on student table
3. Commit:
This command is used to permanently save database changes into hard disk.
Syntax: Commit;
Example: insert into student values(1,‟ram‟,70);
insert into student values(2,‟raj‟,60);
commit;
4. Rollback:
This command is used to undo the database changes up to last commit command.
Syntax: rollback;
Example: insert into student values(3,‟ramesh‟,50);
insert into student values(4,‟rajesh‟,80);
rollback;
5. Savepoint:
This command is used to define breakpoints into transaction to enable partial rollback.
Using rollback you can undo transactions upto last commit command but if you want to undo
transactions upto specific point then you need to first create savepoints into transactions and then you can
rollback transactions upto specific savepoint.
Syntax: savepoint savepoint_name;
Example: insert into student values(3,‟ramesh‟,50);
savepoint s1;
insert into student values(4,‟rajesh‟,80);
savepoint s2;
delete from student;
rollback to s1;

3.5 SQL Operators:


The SQL provides following operators:
1. Arithmetic operators
2. Comparison operators(Relational operators)
3. Logical operators
55
RDBMS

4. Set operators
5. Range searching operators
6. Pattern matching operators
1. Arithmetic Operators:
Arithmetic operators are used to perform arithmetic operations. There are four arithmetic operators.
+ (addition)
- (subtraction)
* (multiplication)
/ (division)
Operator Meaning
+ Adds values or operand on either side of operator
- Subtract right side operand from left side operand
* Multiplies left side operand with right side operand
/ Divides left side operand by right side operand

Example 1. Display salary of all employees by adding 5000 to it


Select sal + 5000 from emp;
Example 2. Display salary of all employees by increasing salary with 5%
Select sal + ( sal * 5/100 ) from emp;

2. Comparison Operators (Relational operators) :


Comparison operators are used to compare two operands or to compare expressions.
The SQL uses comparison operators such as: =, != , >,>=, <, <=, !>, !<

Operator Meaning
Checks if value of two operands are equal or not ,if equal then
=
condition becomes true
Checks if value of two operands are equal or not ,if not equal then
!=
condition becomes true
Checks if value of left operand is greater than value of right operand, if
>
yes then condition becomes true
Checks if value of left operand is greater than equal to value of right
>=
operand, if yes then condition becomes true
Checks if value of left operand is less than value of right operand, if
<
yes then condition becomes true
Checks if value of left operand is less than equal to value of right
<=
operand, if yes then condition becomes true

Example 1. Display details of employees whose job is clerk


Select * from emp where job=‟clerk‟;
Example 2. Display details of employees except job as clerk
Select * from emp where job !=‟clerk‟;
Example 3. Display details of employees whose salary is greater than 20,000
Select * from emp where sal > 20000;

3. Logical Operators:
Logical operators are used to combine multiple conditions in where clause.
The SQL uses logical operators such as : AND, OR, NOT
Operator Meaning

56
RDBMS

AND Returns result when all conditions are true


OR Returns result when any one condition is true
NOT Returns result except specified condition

Example 1. Display details of employees whose job is clerk and whose deptno is 10
Select * from emp where job=‟clerk‟ and deptno=10;
Example 2. Display details of employees whose job is clerk or salesman
Select * from emp where job =‟clerk‟ or job =‟salesman‟;
Example 3. Display details of employees whose job other than clerk
Select * from emp where not job=‟clerk‟;
4. Set Operators:
The set operators operates on two relations
The set operators are used to combines the result of two queries into a single result
The SQL provides following set operators:
1. Union
2. Intersect
3. Minus
Syntax: SQL statement1 set operator SQL statement2;

1. Union: it is used to display all values from both tables.


Example: Display employee names who works in India or USA
Select ename from emp_india
union
Select ename from emp_usa ;

2. Intersect: it is used to display common values from both tables.


Example: Display employee names who works in India and USA
Select ename from emp_india
intersect
Select ename from emp_usa ;

3. Minus: it is used to display values that are present in one table but not present in other table.
Example: Display employee names who works in India but not in USA
Select ename from emp_india
minus
Select ename from emp_usa ;

5. Range searching operators-


Range searching operators are used to find the values that are within specific range
SQL provides following range searching operators:
1. Between
2. Not between
3. In
4. Not In
1. Between: It finds the values that are within specific range
Syntax: select * from table_name
where column_name between value1 and value2;
Example:find employees details whose salary between 10000and 20000
Select * from emp where sal between 10000 and 20000;

2. Not between: It finds the values that are not within specific range
Syntax: select * from table_name
where column_name not between value1 and value2;
Example:find employees details whose salary not between 10000and 20000

57
RDBMS

Select * from emp where sal not between 10000 and 20000;

3. In: It finds the values that are matches with any one value in a list
Syntax: select * from table_name
where column_name In (value1,value2,value3,……..);
Example:find employees details whose job is clerk, salesman or manager
Select * from emp where job in („clerk‟,‟salesman‟,‟manager‟);

4. Not In: It finds the values that are not with matches any value in a list
Syntax: select * from table_name
where column_name Not in (value1,value2,value3,……..);
Example:find employees details whose job is other than clerk, salesman or manager
Select * from emp where job Not in („clerk‟,‟salesman‟,‟manager‟);

6. Patterns matching operators-


Patterns matching operators are used to retrieve data from table with particular pattern
SQl provides following patterns matching operators:
1. Like
2. Not like
3. is null
4. is not null
1. Like: It displays all rows from table where data matches with specified pattern
We describe pattern by two special characters
%( Percent): it represents string of zero or more characters
_ (Underscore): it represents single characters
Syntax: select * from table_name
where column_name like „pattern‟;
Example 1: find employees details whose name starts with „ra‟
select * from emp where ename like „ra%‟;
Example 2: find employees details whose name ends with „sh‟ and name contains maximum of 6
characters
select * from emp where ename like „_ _ _ _sh‟;

2. Not like: It displays all rows from table where data does not matches with specified pattern
Syntax: select * from table_name
where column_name not like „pattern‟;
Example: find employees details whose name does not contain pattern „ra‟
select * from emp where ename not like „%ra%‟;

3. is null: The null values can be retrieved from table using is null keyword in where clause
Syntax: select * from table_name
where column_name is null;
Example: find employees details who do not get commission.
select * from emp where comm is null;

4. is not null: The not null values can be retrieved from table using is not null keyword in where clause
Syntax: select * from table_name
where column_name is not null;
Example: find employees details who does gets some commission.
select * from emp where comm is null;

3.6 Oracle Functions:


 Function is ready to use code written and tested by expert. User just needs to know how to use it by
passing the required value and get the required answer.it may have one or more argument and may
return a value.

58
RDBMS

 SQL provides following functions:


1. String functions or Character functions
2. Arithmetic or Numeric functions
3. Date functions
4. Data conversion functions
5. Aggregate functions

1. String functions :
 String functions accept string values or character values as input and returns string values as
output.
 Only one function length returns the numerical value as output.
SQL provides following string functions:

Sr. No Function Description

Converts first letter of string to capital letter.


Initcap(str) Example:
1. Select initcap(ename) from emp;
Converts a string to all lowercase characters.
Lower(char) Example:
2. Select lower(ename) from emp;
Converts a string to all uppercase characters.
Upper(char) Example:
3. Select upper(ename) from emp;
It returns length of character string.
Length(char) Example:
4. Select length(ename) from emp;

It trim from the left of character string.


Ltrim(char,set) Example:
5.
Select Ltrim(„hello hi‟,‟hello‟) from dual;
It trim from the Right of character string.
Rtrim(char,set) Example:
6. Select Ltrim(„hello hi‟,‟hi‟) from dual;

Concat(string1,string2) It merge or combines two string into single string


7. Example:
Select Concat(„hello ,‟ram‟) from dual;

It returns substring of character string starts from mth character


Substr(char,m,n) and is of length n characters
8. Example:
Select Substr(„Triangle‟,4,5) from dual;

2.Arithmetic or Numeric Functions:


 Numeric functions accept the numeric value as the input and returns the numeric value as output.
SQL provides following numeric functions:
Name Description

59
RDBMS

It returns the absolute value of the number.


Abs(n)
e.g. Select abs(-2.5) from dual;
It returns m raised to the nth power
Power (m,n)
e.g select power(2,3) from dual;
It returns the remainder of m divided by n.
Mod(m,n)
e.g select mod(11,3) from dual;
It returns square root of the number.
Sqrt(n)
e.g. Select sqrt(25) from dual;
It returns e raised to the nth power, where E = 2.71828183....
Exp(n)
e.g. Select exp(14.3) from dual;
It returns the smallest integer greater than or equal to n
Ceil(n)
e.g. Select ceil(14.3) from dual;
It returns the largest integer equal to or less than n
Floor(n)
e.g. Select floor(14.3) from dual;
It returns m rounded to m decimal places
Round(m, [n])
e.g. Select round(54.56,1) from dual;
It returns m truncated to n decimal places.
Trunc(m, [n]) e.g. Select trunc(54.56,1) from dual;

It returns greatest of list of expressions


Greatest (expr1,expr2,…)
e.g. Select greatest(3*2,8/2,5) from dual;
It returns least of list of expressions
Least (expr1, expr2,….)
e.g. Select least(3*2,8/2,5) from dual;

3. Date and Time functions:


 Date functions operate on oracle dates.
 Date functions deals with date datatype column of table
 Date functions generally returns date datatype value
 Only one function months_between returns the numerical value.
 SQL provides following date functions :
Name Description
It returns number of months between two dates.
Months_between(date1,date2) Example:
Select months_between(‟05-may-2016‟, ‟05-jan-2016‟) from dual
It returns date after adding number of months to date
Add_months (date, no. of months)
Example:
Select add_months(‟05-may-2016‟, 3) from dual
It returns date of given week day after specified date
Next_day(date,day of week) Example:
Select next_day (‟05-may-2016‟, „monday‟) from dual
It returns the last day in the month of the specified date.
Last_day(date) Example:
Select last_day (‟05-may-2016‟) from dual
It returns the date rounded by the specified format unit.
format may be year, month or day
Round(date,format) Example:
Select round (sysdate,‟year‟ ) from dual
It returns the date with time portion of date truncated to the unit
specified in format.
Trunc(date,format) format may be year, month or day
Example:
Select trunc(sysdate, ‟year‟ ) from dual

60
RDBMS

It returns systems current date and time


Sysdate Example:
Select sysdate from dual
4. Data conversion Functions:
Conversion functions convert the values of one data type to another.
1. To_char( )
2. To_date ( )
3. To_number( )
1. To char( ) : It converts date or number value into a character string
Syntax: select to_char (expr,format)
e.g .select to_char (sysdate,‟Month DD, YYYY‟) from dual;
e.g .select to_char (sal,‟$99,999‟) from emp;

2. To_date( ) : It converts number or character string into date format

Syntax: select to_date(expr,format)


e.g .select to_date(„January 01 2016‟,‟DD-MON-YYYY‟) from dual;

3. To_number : It converts character string containing a number into a number data type.

Syntax: select to_number(char)


e.g .select to_ number(500) from dual;

5.Aggregate functions:
Aggregate functions are functions that takes set of values as input and return single value as output.
Syntax: Select aggregate function (column_name)
From table_name
Where condition;
SQL provides six aggregate functions:
1. Min: It returns the smallest value in a given column
Example: select min (sal) from emp;
2. Max: It returns the largest value in a given column
Example: select max (sal) from emp;
3. Sum: It returns the sum of the values in a given column
Example: select sum (sal) from emp;
4. Avg: It returns the average value of a given column
Example: select avg (sal) from emp;
5. Count: It returns the total number of values in a given column
Example: select count (sal) from emp;
6. Count (*) : It returns the number of rows in a table
Example: select count (*) from emp;

3.7 Queries using Group by, having and order by clause:

Group by clause:
61
RDBMS

 It‟s used to group the rows based on certain common criteria.so that aggregate functions may be
performed on group with one command. or
 Group by clause used to divide the rows in a table into groups and apply aggregate function on
that group.
Syntax: select column_name, aggregate_function(column_name)
from table_name
where condition
group by column_name;

Example 1: display maximum salary of each department


select dept, max(sal) from emp
group by deptno;
Example 2: display maximum salary of each job type
select job, max(sal) from emp
group by job;

Having clause:
 Having clause is used to give condition after group by clause or
 Having clause is used is used to specify which groups are to be displayed.

Syntax: select column_name, aggregate_function(column_name)


from table_name
where condition
group by column_name
having condition;

Example: display department numbers having maximum salary greater than 40000
select dept, max(sal) from emp
group by deptno
having max(sal)>40000;

Order by clause
 Order by clause is used to display records from table in ascending or descending order of specific
attribute. By default the order is ascending.
Syntax:
Select * from <table name> where <condition> order by <attribute name> [asc/desc];
Example 1: display details of employee in ascending order of salary
Select * from emp order by sal asc;
Example 2: display details of employee in descending order of salary
Select * from emp order by sal desc;

Joins :
 Join is used to retrieve the data from multiple tables either one the basis of common attribute.
 Joins are used to combine data from multiple tables
 SQL Join types are as follows:

62
RDBMS

1) INNER JOIN or EQUI JOIN:


A join which is based on equalities is called equi join. In equi join comparison operator
“=” is used to perform a Join.
Syntax: select table1.column1, table1.column2, ………….
from table 1,table 2
where table 1.column=table 2.column;
Example: display employee names and their respective department name
Select emp.ename,dept.dname
From emp,dept
Where emp.deptno=dept.deptno;

2) NON-EQUI JOIN:
A join which is based on other than „=‟ operator is called non-equi join.
In non-equi join comparison operators such as !=,>,>=,<,<= are used to perform join.
Syntax: select table1.column1, table1.column2, ………….
from table 1,table 2
where table 1.column!=table 2.column;
Example: Select emp.ename,dept.dname
from emp,dept
where emp.deptno!=dept.deptno;

3) SELF JOIN:
The SQL self-join is used to join a table to itself, as if the table were two tables,
temporarily renaming at least one table in the SQL statement.
Syntax: select a.column_name, b.column_name...
from table1 a, table1 b
where a.common_filed = b.common_field;
Example: find manager of each employee
Select a.ename “employee”, b.ename “manager”
from emp a,emp b
where a.mgr= b.empno;
4) CROSS JOIN:
It performs cartesian product operation
Syntax: select *
from table1 cross join table2
Example: Select * from emp cross join dept

5) LEFT OUTER JOIN:


A left outer join retains all of the rows of the “left” table, regardless of whether
there is a row that matches on the “right” table.
Syntax: select *
from table1 left outer join table2 on
table1.columnname= table2.columnname;
Example: select *
from emp left outer join dept on
emp.deptno=dept.deptno
6) RIGHT OUTER JOIN
A right outer join retains all of the rows of the “right” table, regardless of whether
there is a row that matches on the “left” table.
Syntax: select *

63
RDBMS

from table1 right outer join table2 on


table1.columnname= table2.columnname;
Example: select *
from emp right outer join dept on
emp.deptno=dept.deptno
7) FULL OUTER JOIN
A full outer join is a combination of left outer join and right outer join.
Syntax: select *
from table1 full outer join table2 on
table1.columnname= table2.columnname;
Example: select *
from emp full outer join dept on
emp.deptno=dept.deptno
Sub Queries:
 The queries written in queries are called as sub queries. or
 The query written inside another query is called as sub query or
 We can write one select statement inside another select statement is called as sub queries or nested
queries.
Syntax:
Select column1, column 2 ,……….
From table_name
Where column1 operator (select column from table_name where condition);

Type of sub queries:


1. Single row sub queries
2. Multiple row sub queries

1. Single row sub queries:


Sub queries that returns single row are called single row sub queries
Single row sub queries uses single row operators such as =,!=,>,>=,<,<=
Example 1: display details of employees whose job is same as that of employee no 7788
Select * from emp
Where job=(select job from emp where empno=7788)
Example 2: display details of employees whose salary is greater than salary of vijay
Select * from emp
Where sal>(select sal from emp where ename=‟vijay‟)

2. Multiple row sub queries:


Sub queries that returns more than row are called multiple row sub queries
Multiple row sub queries uses multiple row operators such as IN, ANY, ALL
Example 1: display details of employees whose salary is greater than minimum salary of
each department
Select * from emp
Where sal > ALL (select min (sal) from emp group by deptno)
Example 2: display details of employees whose salary is equal to minimum salary
of any department
Select * from emp
Where sal IN (select min (sal) from emp group by deptno)

Examples of SQL queries


Q.1. Consider the following structure for employee. The table EMP (Empno, Ename, Job, Mgr,
Joindates, salary, Comm, Deptno) Write SQL queries for the following :
(i) Display the list of employee excluding job title as „Salesman‟.
(ii) Display the average salaries for each department.

64
RDBMS

(iii) Change the name of employee „Rahul Gosai‟ to „Jigar Dave‟,


(iv) Display employee details whose name start with „A‟
Ans.:
i) select * from emp where job != „Salesman‟;
ii) select avg(salary) from emp group by deptno;
iii) update emp set ename=‟Jiger Dave‟ where ename=„Rahul Gosai‟;
iv) select * from emp where ename like „A%;

Q.2. Consider the following database schema :


Emp (emp_no, ename, job, mgr, joindate, salary, comm., dept_no)
Solve the following queries in SQL :
i) Find the employees who belong to deptno 10 or 30.
ii) Find out number of employees who work as manager.
iii) Change the salary of employee “Prashant Sali” to 40000
iv) List all employees with null values for comm.. (i.e. commission)
Ans.:
i) Select * from emp where depot=10 or deptno=30;
ii) Select count(emp_no) from emp where job= „manager‟;
iii) Update emp set salary=40000 where name =„Prashant Sali‟;
iv) select * from emp where comm IS NULL;

Q.3. Consider the structure of stud record (Name, Mark, Age, Place, Phone, Bith date).
Write SQL queries for following :
i) To list name of student who do not have a phone number.
ii) To list students from Nashik and Pune
iii) To change mark of Monika to 88 instead of 80.
iv) To list the students from Amit‟s Age group.
Ans.:
i) select name from stud where phone IS NULL;
ii) select * from stud where city=‟Nasik‟ or city=‟Pune‟;
iii) update stud set mark=88 where name=‟Monika‟;
iv) select age from stud where age=(select age from stud where name=„Amit‟);

Q.4. Consider following structure for employee


EMP (empno, empname, job, mgr, joindate, salary, comm., dept.no)
Write SQL queries for the following :
1. To display annual salary of all employees.
2. To display name and salary for all employee whose salary is not in rage of Rs. 5000 and Rs.
10000.
Ans.:
1. select salary*12 from emp
2. select name, salary where salary not between 5000 and 10000;

Q.5. Consider the following database: Employee (emp_id, emp_name, emp_city, emp_addr,
emp_dept, join_date)
i) Display the names of employees in capital letters.
ii) Display the emp_id of employee who live in city Pune and Mumbai
iii) Display the details of employees whose joining date is after ‟01-Apr-1997‟.
iv) Display the total number of employees whose dept no. is „10‟.

Ans.:
i) select upper(emp_name) from emp;
ii) select emp_id from emp where city=„Pune‟ or city=„Mumbai‟;
iii) select * from emp where join_date> „01-Apr-1997‟.
iv) Select count (emp_id) from emp where emp_dept=10;

65
RDBMS

Q.6 Given- Employee (EMP_ID, FIRST_NAME, LAST_NAME, SALARY, JOINING_DATE,


DEPARTMENT)
Write SQL queries for-
i) Get FIRST_NAME, LAST_NAME from employee table.
ii) Get unique DEPARTMENT from employee table.
iii) Get FIRST_NAME form employee table using alias name “Employee Name”
iv) Get FIRST_NAME from employee table after removing white spaces from
left side.
Ans :
i) select FIRST_NAME,LAST,NAME from employee;
ii) select distinct DEPARTMENT from employee;
iii) select FIRST_NAME “Employee Name” from employee;
iv) select ltrim(FIRST_NAME) from employee;

Q.7 Consider following schema:


depositor (cust_name, acc_no)
Borrower (cust_name, loan_no) Solve following Qeries:
(i) Find customer name having savings account as well as loan account.
(ii) Find customer names having loan account but not the saving account.
(Each query – 2 Marks)
Ans:
(i) Select cust_name from depositor intersect select cust_name from borrower;
(ii) Select cust_name from borrower minus select cust_name from depositor;

Q.8 Consider following schema:


Employee (emp_no, emp_name, dept, designation, salary, Dept_location)
Solve following queries:
(i) List all Managers in Mumbai location.
(ii) Set salary of all „project leaders‟ to 70000/-.
(iii) List employees with having alphabet „A‟ as second letter in their name.
(iv) Display details of those employees who work in Mumbai or Chennai.
(For each query - 1 Mark)
Ans:
i) Select * from Employee where designation= „Manager‟ and Dept_location= „Mumbai‟
ii) Update Employee set salary=70000 where designation= „project leader‟
iii) Select * from Employee where emp_name like „_A‟
iv) Select * from Employee where Dept_location= „Mumbai‟ or Dept_location= „Chennai‟

Transaction Processing: The concept of Transaction.


A transaction is a collection of operations that forms a single logical unit of work.
The transaction access data using two operations

66
RDBMS

1. Read(x)-which reads data item x from database (hard disk) to local buffer (RAM)
2. Write(x)-which writes data item x from local buffer (RAM) to database (hard disk)
For Example: consider a transaction T1 transfers 100 rupees from account A to account B
This transaction can be defined as:
T1: Read (A);
A: =A-100;
Write (A);
Read (B)
B: =B+100;
Write (B);

ACID Properties:
1. Atomicity: Atomicity means either all operations of transaction performed completely or not at all.
In above transaction operations are Read (A), Write (A), Read (B) and Write (B);
Atomicity property says that either all of four operations of transaction executed at a time or
It should not execute any single operation of transaction.
2. Consistency: Consistency means after execution of transaction database remains in consistent state.
For e.g. suppose before execution of transaction T1 value of account A and account B balances are
1000 and 2000 respectively. The consistency property says that before execution of transaction sum
of A and B is 3000 then after execution of transaction sum of A and B must be 3000
3. Isolation: Even, if two transactions are executed concurrently its result must be same as when these
transactions are executed in some serial order.
4. Durability : Once transaction completes its execution successfully, the changes it has made to the
database remains as its even if there is system failure after the execution of transaction

States of Transaction:

Fig. State diagram of transaction

The Transaction must be in one of following states


1. Active: The active state is initial state. The transaction starts its execution in active state
2. Partially Committed: When transaction completes execution of final statement then it enters into
partially committed state

67
RDBMS

3. Failed: Due to hardware failure or logical error the transaction can‟t proceed its normal execution
then transaction enters into failed state.
4. Aborted: After unsuccessful completion of transaction, the transaction enters into aborted state
5. Committed: When transaction completes its successful execution then it enters into committed
state

Concurrent execution of transaction:


Concurrent Execution means more than one transaction executed at a same time.
Advantages of concurrent execution of transaction are as follows:
 Increased throughput: Throughput means number of transactions executed in given amount of time.
Due to concurrent execution of transactions the throughput is increases.
 Increase resource utilization: Due to concurrent execution of transactions, the utilization (use) of
resources such as processor and disk is increases.
 Reduced waiting time: Due to concurrent execution of transactions, the waiting time required for
short transactions is reduced.
If transactions run serially, then short transactions may have to wait for completion of long
transactions.

Schedules: The Schedule means order in which instructions from transactions are executed.
There are two types of Schedules:
1. Serial schedule
2. Concurrent schedule
1. Serial schedule: In serial schedule sequence of instructions from different transactions are executed
serially.
For Example: consider a transaction T1 transfers 50 rupees from account A to account B
This transaction can be defined as:
T1: Read (A);
A: =A-50;
Write (A);
Read (B)
B: =B+50;
Write (B);
And transaction T2 transfers 10 percent of balance from account A to account B
This transaction can be defined as:
T2: Read (A);
Temp: =A*10/100;
A: =A-Temp;
Write (A);
Read (B)
B: =B+Temp;
Write (B);
Suppose these two transactions T1 and T2 are executed one at a time in serial order of T1 followed by
T2.This execution sequence as shown in fig (a).

68
RDBMS

T1 T2
Read (A);
A: =A-50;
Write (A);
Read (B)
B: =B+50;
Write (B);
Read (A);
Temp: =A*10/100;
A: =A-Temp;
Write (A);
Read (B)
B: =B+Temp;
Write (B);

Fig (a).serial schedule T1 followed by T2.


Consider before execution of serial schedule T1 followed by T2 account A and account B balances are
1000 and 2000 respectively and Sum of A and B is 3000 then after execution of serial schedule T1
followed by T2 account A and account B balances are 855 and 2145 respectively and Sum of A and B
is 3000, so above serial schedule is consistent.
Suppose these two transactions T1 and T2 are executed one at a time in serial order of T2 followed by
T1.This execution sequence as shown in fig( b).

T1 T2
Read (A);
Temp: =A*10/100;
A: =A-Temp;
Write (A);
Read (B)
B: =B+Temp;
Write (B);
Read (A);
A: =A-50;
Write (A);
Read (B)
B: =B+50;
Write (B);

Fig (b).serial schedule T2 followed by T1.

Consider before execution of serial schedule T2 followed by T1 account A and account B balances are
1000 and 2000 respectively and Sum of A and B is 3000 then after execution of serial schedule T2
followed by T1 account A and account B balances are 850 and 2150 respectively and Sum of A and B
is 3000, so above serial schedule is consistent.

69
RDBMS

2. Concurrent schedule: In concurrent schedule sequence of instructions from different transactions


are executed concurrently.
Suppose two transactions T1 and T2 as defined above are executed concurrently.
This execution sequence as shown in fig (c).

T1 T2
Read (A);
A: =A-50;
Write (A);
Read (A);
Temp: =A*10/100;
A: =A-Temp;
Write (A);
Read (B)
B: =B+50;
Write (B);
Read (B)
B: =B+Temp;
Write (B);

Fig (c).Consistent concurrent schedule


Consider before execution of concurrent schedule account A and account B balances are 1000 and
2000 respectively and Sum of A and B is 3000 then after execution of concurrent schedule account A
and account B balances are 855 and 2145 respectively and Sum of A and B is 3000.so above
concurrent schedule is consistent.

Suppose two transactions T1 and T2 as defined above are executed concurrently.


This execution sequence as shown in fig (d).

T1 T2
Read (A);
A: =A-50;
Read (A);
Temp: =A*10/100;
A: =A-Temp;
Write (A);
Read (B)
Write (A);
Read (B)
B: =B+50;
Write (B);
B: =B+Temp;
Write (B);

Fig(d).Inconsistent concurrent schedule


Consider before execution of concurrent schedule account A and account B balances are 1000 and
2000 respectively and Sum of A and B is 3000 then after execution of concurrent schedule account A
and account B balances are 950 and 2100 respectively and Sum of A and B is 3050.so above
concurrent schedule is inconsistent.

70
RDBMS

Chapter 4: ADVANCED SQL: SQL PERFORMANCE TUNING


View :
 View is a virtual table or temporary table used to hide the complexity of database from other uses.
 View is used for security purpose.
 A view is a logical (virtual) table based on another table.
 View logically represents subset of data from one or more tables.
 The table on which a view is based are called base table.
 View takes output of query and treats it as a table.
Syntax to create view
1. Create or replace view <view_name> as select statement;

2. Create or replace view <view_name> [Columns ] as


Select statement
[ With check option [constraint] ]
[ with read only ] ;
Parameters:
Replace: recreates view if it already exists
With check option: it specifies only row accessible to the view can be inserted or updated
With read only: it specifies view is only readable i.e. we cannot perform insert, update or delete
operations on view.
Example :1.Create view emp20 that contains details of employees in deptno 20.
Create view emp20 as
select * from emp where deptno = 20;

Retrieving data from view :


 Data is retrieved from view as similar with data is retrieved from table.
 You can display either the contents of entire view or just specific rows and columns.
e.g. select * from emp20;

Creating complex view :


 Create complex view of employee and department information
Create view emp_dept(empno, ename, job, sal, deptno, dname) as
Select empno, ename, job, sal, dept.depto, dname
from emp, dept
where emp. deptno = dept.deptno;
Removing view :
Use drop view statement to remove the view, this statement removes the view definition from database.
dropping view has no effect on the tables on which the view was based.
Syntax : drop view < view name >;

e.g. drop view emp_dept;

Example:Consider following schema: Depositor (Acc_no, Name, PAN, Balance)


Create a view on depositor having attributes (Acc_no, PAN) where balance is greater than
100000. (For command – 4 Marks)
Ans: Create view v1 as select Acc_no,PAN from depositor where balance>100000;

71
RDBMS

Sequence
 A sequence is a user created database object.
 It can be shared by multiple users.
 It‟s used to generate unique integer numbers.
 It‟s used for multiple tables.
 Sequence is generated and incremented or decremented by oracle routine.
Syntax to create sequence

Create sequence sequence_name [increment by n] [start with n]


[maxvalue n] [minvalue n]
[ {cycle/nocycle }]

Where, sequence name is the name of sequence generator.


increment by n – it specifies number generated by sequence is incremented by which number,
by default its 1
start with n – it specifies the first sequence number, by default its 1
maxvalue n – it specifies the maximum number generated by sequence (default value is 1027)
minvalue n – it specifies the minimum number generated by sequence (default value is 1)
cycle/nocycle – it specifies, continues to generate values after reaching its maximum or minimum
value ,by default its nocycle.
Example

Create sequence empno_seq increment by 2 start with 10 maxvalue 100


minvalue 5, nocycle;

Above example creates a sequence named empno_seq used for empno column of emp table, the sequence
starts at 10, does not cycle.
Use of sequence
 Insert new record into emp table with empno generated from sequence empno_seq, ename as raj
and salary as 10000.
Insert into emp (empno, ename, sal)
values (empno_seq.nextval, „raj‟, 10000);

 To view or see current value for empno_seq sequence use following statement

Select empno_seq.currval from dual;

 Modifying sequence :
To change increment value, maximum value, minimum value of sequence, cycle option,
use alter sequence statement.
Alter sequence empno_seq increment by 5, maxvalue 200,minvalue 50 cycle;

Removing a sequence
To remove a sequence from database use drop sequence statement.
Syntax : drop sequence <sequence_name>;

Example : drop sequence empno_seq;

72
RDBMS

Index :
 Index is a technique for faster searching of information from huge table.
 Index used by the oracle server to speed up the retrieval of rows by using pointer.
 Indexes are logically and physically independent of the table they index.
 Indexs are used and maintained by oracle serves.
 Create index statement is used to create index on particular column of table.
Types of Index
1. Unique / Primary Index:
 It‟s based on unique column of the table
 Unique index is created automatically when you define primary key or unique constraint in table
definition.

Syntax : Create unique Index Index_name on table_name (coumn_name);

Example : Create unique Index emp_u on emp(emp_id);

2. Non-unique / Secondary Index:


 It‟s based on non-unique column of the table
 User can create non-unique index on column to speed up access to row.

Syntax: Create Index Index_name on table_name (coumn_name);

Example: Create Index emp_s on emp(ename);

3. Composite Index:
 It‟s based two or more columns of table.

Syntax : Create Index index_name on table_name (column1, column2);

Example : Create Index emp_c on emp(ename, job);

Removing Index : To remove index from data dictionary use following statement

Syntax : Drop index <index_name>;

Example : Drop index emp_c;

Synonyms :
 Synonym is a alternative (alias) name given to table, view, sequence, function, procedure or
package
 It shortens lengthy object names
 It simplifies access to object (another name to object)
 Synonyms are easy referring names given to table, view, function, procedure etc.
 Synonyms reduce complexity of SQL statement for database users.
 Synonyms are convenient or easy to use.

73
RDBMS

Creating Synonyms:

Syntax : Create synonym synonym_name for object name;

Example : Create synonym emp for employee;

 To create short name e for emp_vu30 view

Create synonym e for emp_vu30;

 Synonym are used in DML statement in same way that the original relation is used
e.g. You can insert row in synonym emp as you can insert row in employee relation.

Insert into emp(empno, ename) values (1, „raj‟);

Removing Synonym
To remove synonym from data dictionary use following statement

Syntax : Drop synonym <synonym_name>;

Example : Drop synonym e;

Snapshot
 Snapshot is recent copy of table from database.
 Snapshot is a read only copy of table.
 Snapshot is a table that contains result of query of one or more tables.
 These tables may be located on same or remote database.
 Snapshot is also called “materialized view”
Creating Snapshots:

Syntax : Create snapshot snapshot_name as select statement;

Example : Create snapshot emp_data as select * from emp;

Retrieving data from snapshot


 Data is retrieved from snapshot as similar with data is retrieved from table.
 Following statement retrieves data from emp_data snapshot.

select * from emp_data;

Removing snapshot
 To remove snapshot from data dictionary use following statement.
Syntax : Drop snapshot <snapshot_name>;

Example : Drop snapshot emp_data;

74
RDBMS

Chapter 5 : PL/SQL, DATABASE OBJECTS AND SECURITY


Introduction of PL/SQL :
 PL/SQL stands for procedural language/structured query language.
 PL/SQL is a powerful database programming language which allows user to write a programs to do
various operations on database.
 PL/SQL is an extension of SQL which provides features such as data encapsulation exception
handling, information hiding and also brings programming capability to the relational database.
 PL/SQL is a block structured language.

Advantages of PL/SQL :
1. Block Structures :
 PL/SQL consist of block of code.
 Each block forms unit of task
2. Procedural language capability:
 PL/SQL adds capabilities of procedural language like „C‟
 PL/SQL consists procedural language constructs such as conditional statements, looping statements
and sequential statements.
3. Better performance:
 PL/SQL processes multiple SQL statements simultaneously as a single block.
4. Error Handling:
 PL/SQL handles errors or exceptions during program execution.
 If error occurs, PL/SQL display appropriate error message to users.

PL/SQL Data Types :


1. Number : For storing numeric data such as integer or floating point number.
e.g. A number;
2. Char : For storing character data. Char data type also used to store numbers or special symbols.
e.g. Name Char;
3. Varchar2 : For storing variable length character string, varchar2 data type also used to store
numbers or special symbols.
e.g. City Varchar2;
4. Date : For storing date and time.
e.g. Hiredate date;
5. Boolean : For storing Boolean values either true or false.
e.g. Flag Boolean;
6. % type: Declare variable that have same data type as that of a previously defined variable or
column in a table.
e.g. Z emp.sal%type;
Declares variable Z that have same data type as that of sal column of emp table
7. LOB (Large Object) data type :
 It‟s used to store large objects
 Large object can store either a binary or character data values upto 4GB in size.
The types of LOB are :
i.BLOB (Binary LOB) : It stores binary data upto 4GB in size, it stores binary data such as videos
or picture information.

75
RDBMS

ii.CLOB (Character LOB) :


 It stores character data upto 4GB in size.
 It stores character data such as entire documents.
iii.BEILE (Binary File) : This stores a pointer, to read only binary data stored as an external file.

8. % Rowtype : It used to declare a composite a variable having same number of variable inside it as
number of columns present in table.
 % type refers columns data type whereas % rowtype refers the whole record in table. (i.e. it refers
all columns data types in a table).
 % rowtype it declare variable that represents a row in a table.
 e.g. emp_rec emp%rowtype;
 You declare a record named emp_rec, its fields have same names and same data types as the
columns in emp table. You use dot notation to refer fields such as emp_rec.ename.

Display PL/SQL Output :


 The procedure dbms_output.put_line( ) is used to place the results in buffer.
 If we execute set serveroutput on command then SQL*PLUS retrieves and displays the contents of
buffer.

PL/SQL Block Structure :

Declare
Declaration of variables, constants, etc.
Begin
SQL executable statements;
PL/SQL executable statements
[exception]
Error handling code;
End;

Fig. : PL/SQL block structure


Basic unit in any PL/SQL program is a block the PL/SQL block consist of four main sections:
1. Declare Section:
 It consists of declaration of all variables, constants, cursors and etc. that are used in executable
sections.
2. Begin Section:
 It consists of set of SQL and PL/SQL executable statements to manipulate data from database.
 The PL/SQL program logic is written here,constructs like loops, conditional statements and SQL
statements are written here.
3. Exception Section:
 It consists code (set of statements) that is executed when error occurs during the execution of
program.
 or It consists actions to be performed when error or abnormal conditions occurs during the
execution of PL/SQL code.
4. End Section :
 This section is used to make the end of PL/SQL block.

76
RDBMS

Variables :
 Variables are used to store temporary data during PL/SQL program execution.
 Value of variable can be changed during program execution.
 Variables are declared in declare section of PL/SQL block.
Syntax for declaring variable in PL/SQL is as follows:
Variable_name datatype := initial value;
e.g. a number : = 10;
name char : = „Raj‟;
Assigning value to variable :
The value can be assigned to the variable in any one of following two ways.
1. Using assignment operator :=
e.g. a: = 10;
2. Selecting table data values into variable
e.g. select ename into name
from emp
where empno = 7769;
Rules for declaring variable
1. Variable name must being with letter.
2. Variable length can be maximum 30 characters.
3. Space can‟t be used in variable names
4. Case is insignificant while declaring variable.

Constants:
The constants are one whose value can‟t be changed during program execution.
Syntax for declaring constant in PL/SQL is as follows::
Constant_name CONSTANT datatype : = defined value;
e.g. Pi CONSTANT number : = 3.14;
Y CONSTANT char : = „Hello‟;

Fundamental components of PL/SQL :


1. Identifier : are names of PL/SQL objects as constants, variables, exceptions, functions, procedures
and reserved words.
2. Literals : are values of PL/SQL objects
e.g. a number : = 10

Identifier (variable) literal


3. Delimiter : are symbols with special meaning such as
: = (Assignment operator)
|| (concatenation operator)
; (Terminator for statements and declaration)
= (equality operator)
<< and >> Label delimiter
4. Comment : are section of code not execute by complier.
Comments are statements for user understanding purpose.
Single line comment begins with double hyphen (--)
Multiline comment begins with /* and ends with */

77
RDBMS

SQL Statements in PL/SQL :


 In PL/SQL blocks, DML statements such as select, insert, update and delete and TCL commands
such as commit, savepoint and rollback of SQL are used to extract information from or to apply
changes to the database. But DDL statements such as create table, alter table, drop table, truncate
table, rename & DCL statements such as grant, revoke are not supported by PL/SQL.
 Select statement in PL/SQL has following syntax
Select column_name into variable_name
From table_name
where condition
The select statement retrieves the single row value and store into variable using into clause.
e.g. :
declare
X emp.ename%type;
Y emp.job%type;
Z emp.sal%type;
begin
Select ename, job, sal into X, Y, Z from emp
where empno = 7369;
dbms_output_line (X || Y || Z);
end;
The insert, update and delete statements in PL/SQL are used in the same way as they are used in
SQL.
Control Structure :
The number of control statements can be used to change the logical flow of statements within PL/SQL
block.
PL/SQL provides following control structures:
1. Conditional Control:
1. IF - - Then statement
2. IF – Then Else statement
3. IF – Then Elsif statement‟
4. Case statement
2. Iterative control or looping statement:
1. Simple loop statement
2. While loop statement
3. For loop statement
3. Sequential Control:
1. Goto statement
2. NULL statement

1. Conditional Control :
Conditional control executes specific condition given by user in program.
1. IF - - Then Statement:
IF - - then statement executes sequence of statements if condition is true. If condition is false,
then if statement does nothing.
Syntax: If condition then
Sequence of statements;
End if;

78
RDBMS

2. IF – Then Else statement


It‟s used to check condition.if the condition is true then sequence of statements written inside
if part are executed.
If condition is false then sequence of statements written inside else part are executed.

Syntax :
If condition then
Sequence of statement 1;
Else
Sequence of statement 2;
End if;

3. If- then Els if statement :


It‟s used to check condition, if condition is true then sequence of statements written inside if
part are executed.
if condition is false, the elsif clause tests another condition. An if statement can have any
number of elsif clauses. conditions are evaluated one by one from top to bottom. If any
condition is true, its associated sequence of statements are executed and control passes to next
statement. If all conditions are false, the sequence of statements in else clause are executed.
Syntax :
if condition1 then
sequence of statement1,
elsif condition 2 then
sequence of statement2,
else sequence of statementn+1
end if;

4. Case statement :
The case statement selects one sequence of statements to execute.
The case statement begins with keyword case followed by one or more when clauses.
When clauses contains conditions. the conditions are evaluated sequentially. if condition is
true, then it‟s when clause is executed.
If any when clause is executed, control passes to next statement after end case, so subsequent
conditions are not evaluated.

Syntax :
when condition1 then
sequence of statement1;
when condition2 then
sequence of statement2;
: :
when condition n then
sequence of statementn;
else
sequence of statementn+1;
end case;

79
RDBMS

e.g. Write a PL/SQL program to accept 3 numbers and display largest number.
declare
a number : = &a;
b number : = &b;
c number : = &c;
begin
if a > b and a > c then
dbms_output.put_line („A is largest number‟);
elsif b > a and b > c then
dbms_output.put_line („B is largest number‟);
else
dmbs_output.put_line („C is largest number‟)
end if;
end;

2. Iterative control or loop statements :


Loop statements let you execute sequence statements multiple time.
There are three types of loop statements
1.Simple Loop :
 Its used to repeat the sequence of statements multiple times.
 The exit when statement is used to terminate (exit) from loop.
 If exit when condition is true, then it terminates from loop and executes next statements after
end loop statement.
Syntax : loop
sequence of statements;
Exit when condition;
End loop;
e.g. : Display numbers from 1 to 10 using loop statement
declare
n number : = 1;
begin
loop
dbms_output.put_line (n);
n:=n+1;
exit when n > 10;
End loop,
End,

2.While loop :
 The while loop is called conditional loop, it evaluates the condition before each loop
executes,
 if condition written inside while is true then it executes sequence of statement written inside
while,
 if condition is false then it terminates loop and executes next statement after end loop
statement.

80
RDBMS

Syntax :
While condition loop
Sequence of statements;
end loop;

e.g. Display numbers from 1 to 10 using while loop.


Declare
n number : = 1;
begin
While n < = 10 loop
dbms_output.put_line(n);
n : = n+1;
end loop;
end;

e.g. Write PL/SQL to find and display factorial of number 5 using while loop.
Declare
n number : = 5;
i number : = 1;
fact number : = 1;
Begin
While i < n loop
fact : = fact * 1;
i : = i + 1;
end loop;
dbms_outpu.put_line („factorial is‟ ||fact);
end;

3. For loop :
 For loop is used to repeat sequence of statements multiple times.
 The statements written inside for loop executed until given condition is true.
 The counter changes from the lower bound to upper bound.
 If the reverse is specified then loop goes in reverse direction
Syntax :
For counter IN [Reverse] Lower bound..Upper bound loop
Sequence of statements;
end loop;
e.g. Display numbers from 1 to 10 using for loop
Declare
n number : = 1;
begin
for n in 1 .. 10 loop
dbms_outpu.put_put_line (n);
end loop;
end;

81
RDBMS

e.g. Display numbers 1 to 10 in reverse order using for loop


Declare
n number;
begin
for n in reverse 1 .. 10 loop
dbms_output.put_line(n);
end loop;
end;
Examples :
1. Write PL/SQL program to perform addition of two numbers.
Declare
a number : = & a;
b number : = & b;
c number : = 0;
begin
c : = a + b;
dbms_output.put_line(„addition is‟ ||c);
end;
2. Write PL/SQL program to find square of number
Declare
a number : = &a;
b number : = 0;
begin
b : = a * a;
dbms_output.put_line(„square of number‟||b);
end;
3. Write PL/SQL program to find area of circle
Declare
r number : = &r;
pi CONSTANT number : = 3.14;
a number : = 0;
begin
a : = pi * r * r;
dbms_output.put_line („the area of circle is‟ ||a)
end;

4. Write a PL/SQL program to find a raised to b


Declare
i number : = 1;
a number : = &a;
b number : = &b;
c number : = 1;
begin
for i in 1 .. b loop
c : = c * a;
end loop;
dbms_output.put_line(c);
end;

82
RDBMS

3. Sequential control structure :


It transfers flow of control linearly or sequentially up or down in PLSQL program.
1. Goto statement:
Its unconditional branching, when executed Goto statement transfers control to labeled
statement
Syntax :
goto label_name
…………….
……………..
<<label_name>>
Where,label_name is name of label and this goto label defined in program as above.
Example 1:
begin
goto second_output;
dbms_output.put_line („this line will never execute‟);
<<second_output>>
dbms_output.put_line („we are here‟);
End;
Example 2:
Declare
empname char(10);
eno number (10) : = 1;
begin
<<get_name>>
select ename into empname from emp where
empno = eno;
dbms_output.put_line (empname);
eno : = eno + 1;
if eno < = 4 then
goto get_name;
end if;
end;
Restrictions on goto statement :
1. Can branch out of if statement, loop or sub program
2. Can‟t branch into an if statement or loop
3. Can‟t branch from one section of an IF statement to another section
(i.e. branch from IF then section to else section is illegal)

2. NULL Statement :
 Null statement does nothing; it passes control to next statement.
 It performs no action.
 You can use it to increase readability of your code.

83
RDBMS

e.g. Accept number from user, if number if 10 then display it, otherwise does nothing
Declare
n number : = &n;
begin
if n = 10 then
dbms_output.put_line(n);
else
null;
end if;
end;

e.g. Declare
a number : = 1;
begin
if a = 1 then
goto mybranch
else
a : = 1;
end if;
<<mybranch>>
null;
end;

Exception Handling:
 It deals with errors that occur during execution of PL/SQL block.
 Exception is a run time error, when such kind of error occurs during the program execution then the
exception is raised.
 Exception handler is a set of statements designed to handle particular exception (run time error)

There are two types of exceptions:


1.Predefined exceptions or system defined exceptions :
They are raised automatically whenever corresponding error occurs during program execution.
Following are predefined PL/SQL exceptions:
1.NO_DATA_FOUND: Raised when select into or fetch statement returned no row.
2.TOO_MANY_ROWS: Raised when select statement returns more than one row.
3.ZERO_DIVIDE: Raised when you are trying to divide number by zero.
4.CURSOR_ALREADY_OPEN: Raised when you are trying to open cursor which is already open.
5.INVALID CURSOR: Raised when fetching row from closed cursor or closing cursor that is
not open.
6.CASE_NOT_FOUND: Raised when no when clause of case statement is selected and there is
no else clause.
7. VALUE_ERROR: Raised when size constraint error occurs.
e.g. When your program selects a column value into variable, if value is larger than declared
length of variable then PL/SQL raises value error.

84
RDBMS

e.g. Write PL/SQL code that handles zero-divide exception:


Declare
a number : = 10;
b number : = 0;
c number : = 0;
begin
c : = a/b;
dbms_output.put_line(c)
when Zero_divide then
dbms_output.put_line („you are trying to divide number by zero‟);
end;
2. User defined exception:
They must be declared by user in declare section of PL/SQL block and raised explicitly with raise
statement in executable section of PL/SQL block and exceptions are handled within exception
section of PL/SQL block. Exception section includes different when clauses each with name of
exception, followed by sequence of statements to be executed when that exception is raised.
Structure of user defined exceptions handling :
Declare
exception_name exception;
begin
raise excetion_name;
Exception
when exception_name1 then
sequence of statement1;
when exception_name2 then
sequence of statement2;
when others then
sequence of statement2;
end;
Example: Write PL/SQL code that handles multiple exceptions
Declare
Salary number (10, 2);
Negative_sal exception;
begin
select sal into Salary from emp
where empno = 5;
if Salary < 0 then
raise negative_sal;
else
update emp set sal = 60000 where empno = 5;
end if;
exception
when Negative_sal then
dbms_output.put_line („salary is negative‟);
when No_data_found then
dbms_output.put_line („record not found‟);
when Too_many_rows then
dbms_output.put_line („select statement returns multiple rows‟);
end;

85
RDBMS

Cursor :
 Cursor is a temporary work area used to store data retrieved from database and manipulate those
data or
 Cursor is a temporary work area (temporary memory created in the system memory (RAM) when
SQL statement is executed.
 Cursor can hold more than one row but can process only one row at a time.
 When we want to access more than one row from table, then we need to use cursor.
 Cursors are used to executed SQL statement and store processing information.

There are two types of cursors in PL/SQL


1. Implicit Cursor
2. Explicit Cursor

1. Implicit Cursor:
 Implicit cursor created automatically when we execute DML statements like select, inserts, update,
delete. or
 Implicit cursors are declared by PL/SQL implicit for all DML statements.

There are four attributes associated with implicit cursor to obtain status information of cursor.
These attributes are as follows:
1.% FOUND : Returns true if an insert, update, delete statement affected one or more rows or
select into statement returns one or more rows, otherwise it returns false
e.g. SQL%FOUND

2.% NOT FOUND : Returns true if an insert, update, delete statement affected no rows or select
into statement returned no rows otherwise, it returns false.
e.g. SQL%NOT FOUND

3.% ISOPEN : It always returns false for implicit cursor, because oracle closes the SQL cursor
automatically after executing its associated SQL statement.
e.g. SQL%ISOPEN

4.% ROWCOUNT : Returns the number of rows affected by an insert, update or delete statement
or it returns number of rows returned by select into statement.
e.g. SQL%ROWCOUNT

e.g. Write PL/SQL program to print number of rows delete from emp table
or example of Implicit cursor
Declare
row_del number;
begin
delete from emp;
row_del := SQL%ROWCOUNT;
dbms_output.put_line („number of rows deleted are‟ || row_del);
end;

86
RDBMS

2. Explicit Cursor:
 Explicit cursor is user defined cursor.
 The explicit cursor is a select statement that is declared explicitly in declare section of PL/SQL
block and use open, fetch ,close statements in executable section of PL/SQL block.

Explicit cursor operations:


There are four operations that must be performed for successful working of cursor.
These operations are as follows:
1. Declare: Declare the cursor in declaration section using flowing syntax.
Syntax :
Cursor cursor_name is select statement
Here we give name to cursor and assign select statement to it.

2. Open : Open cursor in execution section


i.e. it executes select statement written in cursor definition.
syntax : Open cursor_name;

3. Fetch : Fetch data from cursor into PL/SQL variable in execution section.
i.e. Fetch statement places contents of current row into local variable.
Syntax : Fetch cursor_name into variable_name.

4. Close : Close the cursor in execution section before you end PL/SQL block. Closing a cursor
releases all resources used by cursor.
Syntax : Close cursor_name ;

Explicit cursor attributes:


There are four attributes associated with explicit cursor to obtain status information of cursor.
These attributes are as follows:
1.% FOUND : True, if fetch statement returns at least one row.
False, if fetch statement doesn‟t return a row.
e.g. cursor_name%FOUND

2.% NOTFOUND : True, if fetch statement doesn‟t return a row.


False, if fetch statement returns at least one row.
e.g. cursor_name%NOTFOUND

3.% ISOPEN : True, if cursor is already open in the program.


False, if the cursor is not opened in program.
e.g. cursor_name% ISOPEN

4.%ROWCOUNT:Return number of rows fetched by fetch statement .if no row is returned, the PL/SQL
statement returns an error.
e.g. cursor_name%ROWCOUNT.

87
RDBMS

e.g. Declare the cursor,that selects all records from emp table, after that inserts these records into emp2
table (create new exmp2 table).
Declare
Cursor C is select * from emp,
X C%rowtype;
begin
Open C;
loop
Fetch C into X;
Exit when C%NOTFOUND;
insert into emp2
values (X.empno, X.ename, X.job, X.mgr, X.hiredate, X.sal, X.comm, X.deptno.);
End loop;
Close C;
End;

e.g. With the help of cursor, increase salary with 20% for only those employees whose job is clerk.
Declare
Cursor C1 is select empno from emp where job = „Clerk
X C1%rowtype;
begin
Open C1;
loop
Fetch C1 into X;
Exist when C1%NOTFOUND;
update emp set sal = sal+ sal*20/100;
where empno = X.empno;
End loop;
Close C1;
End;

e.g. With he help of cursor display department number and names from dept. table.
Declare
Cursor C2 is select deptno, dname, from dept;
X C2%towtype;
begin
Open C2;
loop
fetch C2 into X;
exit when C2%NOTFOUND;
dbms_output.put_line (X.deptno||X.dname);
end loop;
Close C2;
end;

88
RDBMS

Trigger:
 The Trigger is a PL/SQL block that is executed automatically when an insert, update, delete
commands are executed.
 Trigger is PL/SQL block that executed implicitly by a DML statements.
 Trigger is a named database object that defines set of actions that are performed in response to
insert, update, delete operations against a table.
 Trigger are similar to stored procedure, but stored procedures are called explicitly and triggers are
called implicitly by oracle when the concerned even occurs.

Syntax for creating trigger :


Create or replace trigger trigger_name ………… trigger name
[before/after] ………… trigger timing
[insert/update/delete] ………… trigger event
on table_name ………… object name
[for each row/for each statement] ………… trigger type
PL/SQL block ………… trigger body

Components of Trigger :
1. Trigger name : It‟s a unique name assigned to trigger.
2. Trigger timing : It indicates time when trigger fire.
3. Trigger event : It indicates DML operations that causes the trigger to fire.
4. Object name : It indicate the name of table to which trigger is associated.
5. Trigger type : It indicates the trigger type such as for each row or for each statement.
6. Trigger body : It indicate action performed by trigger.

Types of trigger :
1. Statement level trigger
2. Row level trigger
3. Before trigger
4. After trigger

1. Statement level trigger:


Statement level trigger is fired only once for DML statement irrespective of number of rows
affected by the statement. Statement level trigger is default type of trigger.

2. Row level trigger:


Row level trigger fired once for each row that is affected by DML statement.
e.g. If an update command updates 100 rows then row level trigger is fired 100 times whereas a
statement level trigger is fired only once.

3. Before trigger: This trigger is to be fired before DML command is executed.

4. After trigger: This trigger is fired after DML command is executed.


e.g. If after trigger is associated with inserts command then it‟s fired after row is inserted into table.

89
RDBMS

e.g. Create a trigger to store backup entry in backup_emp table, of every employee when the record of
his/her is deleted from the emp table.
Create or replace trigger deleted_emp after delete on emp
for each row
begin
insert into backup_emp(empno, ename, job, mgr, hiredate, sal, comm, deptno, resigndate)
values(:old.empno,:old.ename,:old.job,:old.mgr,:old.hiredate,:old.sal,:old.comm,:old.deptno,
sysdate);
end;
Note that, before using this trigger, we have to create a table called backup_emp having columns similar
to those in emp table with one additional column which stores the date of resignation of employee called
resigndate.
When we compiler this PL/SQL block the trigger named deleted_emp get attached with delete operation
of emp table.
Now, if we execute following statement
delete from emp
where ename = „Raj‟;
Then the information of employee Raj is deleted from emp table and is automatically stored in
backup_emp table.
e.g. Create trigger trg1 that convert enames from lowercase to uppercase before inserting records into
emp table.
Create or replace trigger trg1
before insert on emp
for each row
begin
:new.ename : = upper (:new.ename);
end;
When, we complier this PL/SQL block, trigger trg1 is get attached with insert operation of emp table.
Now, if we execute following statement
insert into emp(ename) values(„jayesh‟);
then ename jayesh is converted into upper case before inserting into emp table.

e.g. Create trigger emp_comm, that calculate commission 20% of their salary for every new employee
belonging to deptn 30 before record for that employee is inserted into emp table.
Create or replace trigger emp_comm
before insert on emp
for each row
begin
if :new.deptno = 30 then
: new.comm: = : new.sal*20/100;
end if;
End;
When, we compile this PL/SQL block, trigger emp_comm is get attached with insert operation of emp
table.Now, if we execute following statement
insert into emp Values (1, „Ajit‟, „Salesman‟, 7369, sysdate, 30000, null, 30);
Then trigger emp_comm is executed and calculates commission value 20% their salary for employee Ajit
befor inserting record into table emp.

90
RDBMS

Deleting Trigger :
To delete trigger from database following command is used.
Syntax : drop trigger trigger_name;
e.g. drop trigger trg1;

Functions:
 Functions are named PL/SQL blocks that can accept parameters, perform an action and returns a
value to calling program (environment).or
 Function is a subprogram that perform specific task
Advantages of Functions :
1. The main advantage of function is that it can return only one value to calling environment.
2. The functions are stored in database for repeated execution.
3. The functions can perform calculations that are too complex for SQL statements and increases
efficiency of queries by performing functions in queries rather than in the applications.
4. Functions improve the performance of database system because functions are compiled into
machine executable version of code. When function is called the database does not have to compile
the function again before executing it.
5. Functions can also be called from another function or procedure or can be used in where or having
clauses.
The functions and procedures have same structure except that functions must have a return clause in the
header and at least one return statement in executable section.
Syntax for creating function :
Create or replace function function_name [(parameter1 [mode1] datatype1, ……)]
return datatype
IS/AS
PL/SQL block;

Modes of parameter
IN : Which passes constant value from calling program into function or procedure
OUT : Which passes value from function or procedure to calling program.
IN OUT : Passes value from calling program function into function and passes different value from
function back to calling program.
e.g. Write a function circle_area to find area of circle use radius as Input parameters
Create or replace function circle_area ( r in number)
return number
is
Pi constant number: = 3.14;
a number : = 0;
begin
a = pi * r * r;
return a;
end;
For calling above function, we write code as :
Declare
a number;
begin
a: = circle_area (5);
dbms_output.put_line („area of circle is‟||a);
end;

91
RDBMS

e.g. Write a function to count number of employees in a department function will accept a department
number & should return number of employees working in that department.
Create or replace function count_emp (dno number)
return number
is
X number;
begin
Select count (empno) into X from emp
where deptno = dno;
return X;
end;
For calling above function, we write code as;
Declare
X number;
begin
X: = count_emp(10);
dbms_output.put_line („number of employee in department are „||X);
end;

e.g. Create function that returns total number of employee in emp table.
Create or replace function total_emp
return number
is
total number;
begin
Select count (empno) into total from emp;
return total;
end;
for calling function, we write code as :
Declare
C number;
begin
c: = totalemp ( );
dbsms_output.put_line („total number of employee‟|| C);
end;

When program calls a function, program control is transferred to called function.


Then called function performs defined task and when it‟s return statement is executed,then it return
program control back to main program.

Deleting Function:
To delete function from database following statement is used.
Syntax :
Drop function function_name;
e.g. Drop function totalemp;

92
RDBMS

Procedures:
 Procedures are named PL/SQL block that can accept parameters, perform an action and can be
invoked.
 Procedure is subprograms that perform a specific task.
 Procedures are stored in database for repeated execution.
 Procedure does not return value to calling environment, but with the help of out parameter it can
return multiple.
 Once procedure is compiled successfully it can be called from any other procedure or function.

Advantages of procedures:
1. Procedures improves the performance of database system because, once procedure is compiled
successfully,they are converted into machine executable versions of code and stored into database
for repeated execution. When next time same procedure is called, then the database system directly
executes the procedure without recompiling it.
2. Procedures are stored in database for repeated executions.
3. Once procedures complied successfully it can be called from another procedure or function.
4. Stored procedures provided high level of security for data.
5. Stored procedures increases productivity by avoiding redundant coding.

Syntax for creating procedure:


Create or replace procedure procedure_name [(parameter1 [mode1] datatype1, ….)
IS/AS
PL/SQL block;

e.g. Write a procedure circle_area to find area of circle. Use radius as input parameter.
Create or replace procedure circle_area(r in number)
is
Pi constant number : = 3.14;
a number : = 0;
begin
a: = pi * r * r;
dbms_output.put_line („area of circle is „||a);
end;
Executing Procedure :
Procedure can be called in two ways :
1. Using execute keyword : execute circle_area (5);
2. Calling name of procedure from PL/SQL block begin.
begin
circle_area (5);
end;

Deleting a procedure :
To delete a procedure from database following statements is used.
Syntax : Drop procedure procedure_name;
e.g. drop procedure circle_area;

93
RDBMS

e.g. Write a procedure to count number of employees in a department. Procedure will accept a
department number and display number of employees working in that department.
Create or replace procedure count_emp(dno in number)
is
X number;
begin
select count (empno) into X from emp where deptno = dno;
dbms_output.put_line („no of employees in department are‟|| X);
end;

Calling procedure :
begin
count_emp (10);
end;

PL/SQL Security – LOCKS


 The lock based protocol is used for controlling concurrent access to data items.
 If two transactions want to access same data item at a same time then concurrency control manager
gives permissions for one transaction to access that data item through lock.
 Definition: LOCK is a mechanism that allows transactions to access data item only if it‟s currently
holding a lock on that data item.

Types of locks:
The data items locked in two modes or
1. Share mode (S):
 In share mode, transaction can read data item but can‟t write data item.
 The multiple transactions can lock data item simultaneously (at the same time) in share mode.
i.e. In share more only select statement is allowed.
2. Exclusive Mode (X) :
 In exclusive mode, the transactions can perform both read and write operations on data item.
 i.e. In exclusive mode select, insert, update and delete operations are allowed.
 Only one transaction can lock data item at a time in exclusive mode.
Lock Mode S X
S True False
X False False
Fig. Lock compatibility Matrix

From above lock capability matrix, we can say that share mode is compatible with share mode,
means at a same time two difference transactions make share lock on same data item. But share
mode is not compatible with exclusive mode, means if data item is already locked in shared mode
by one transaction and at the same time another transaction want to lock same data item in
exclusive mode then another transaction has need to wait until first transaction unlocks data item.
 With the same reason, exclusive mode is not compatible with share mode and exclusive mode is not
compatible with exclusive mode.

94
RDBMS

Locking Strategy (methods):


There are two ways or methods of locking data in table. These methods are as follows:
1. Implicit Locking:
 Implicit locking is automatically performs by oracle engine, when we execute SQL statements.

2. Explicit Locking:
 This is user defined locking strategy which is used to override the default (Implicit locking) locking
strategy used by oracle engine.
 Explicit locking is performed using lock table command.

Lock table command:


 Lock table command allows us to explicitly acquire share or exclusive lock on specific table.or
 Lock table command is used to lock table in either share mode or exclusive mode.

Syntax :
Lock table table_name in share/exclusive mode)

Example :
1. To lock entire emp table is share mode use following statement

lock table emp in share mode;

with above lock we can read data from emp table as :


e.g. Select * from emp

2. To lock entire emp table in exclusive mode use following statement

lock table emp in exclusive mode;

with above lock, we can read and write data from emp table as
e.g. Update emp.
set sal = 10000
where job = „clerk‟;

95

Das könnte Ihnen auch gefallen