Beruflich Dokumente
Kultur Dokumente
1
RDBMS
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.
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
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.
a = 10; instance
4
RDBMS
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.
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)
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. Non-procedural DML:
Requires users to specify what data are needed without specifying how to get those data
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
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.
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
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
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.
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.
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
Server
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
Interface
SQL engine Back End (SQL + API)
12
RDBMS
User
Client Client
User
Client Application
Network
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.
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.
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.
14
RDBMS
15
RDBMS
16
RDBMS
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.
17
RDBMS
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
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.
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:
20
RDBMS
Book X Book Y
4. Hierarchical model
21
RDBMS
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.
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.
7. It uses values to relate data 7. It uses links to relate data. 7. It uses pointer to relate data
22
RDBMS
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
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
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
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
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.
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
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
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.
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
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
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
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
31
RDBMS
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.
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.
33
RDBMS
5. Draw ER-dig. of College System. The college maintains the data of students, employees,
books.
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.
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.
Natural join ( )
Fig. Relational Algebra operations
35
RDBMS
For example :
1. Select those tuples of loan relation where the branch is pune
3. Find those tuples of loan relation whose loan amount is greater than 3000 and whose branch is
Pune.
2. Find only those loan numbers whose loan amount is greater than 4000
36
RDBMS
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.
Result :
Cus_name
Sunil
Yash
Raj
Manish names who have either account or loan or both.
Fig. : Customer
37
RDBMS
For e.g. 1 : Find the customer names who have both account and loan at the bank.
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
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)))
For e.g. (2) : Find names of customers who have taken loan from Pune branch.
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)
39
RDBMS
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
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.
42
RDBMS
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.
43
RDBMS
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 :
44
RDBMS
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
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
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.
47
RDBMS
3. The normal forms 2NF, 3NF and BCNF are 3. The normal forms 4NF is based on multivalued
based on functional dependency. dependency.
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.
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
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
In above example check constraint checks balance value it must be greater than or equal to 500
Rupees.
49
RDBMS
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.
In above example acc_no attribute will not allow duplicate values but it allows null values.
50
RDBMS
The above foreign key declaration specifies that for each account tuple, branch name specified in the
tuple must exist in the branch relation.
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.
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.
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.
1. Create table: this command is used to create structure of table in the database
52
RDBMS
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;
53
RDBMS
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
54
RDBMS
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;
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
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
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
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;
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 ;
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‟);
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;
58
RDBMS
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:
59
RDBMS
60
RDBMS
3. To_number : It converts character string containing a number into a number data type.
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;
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;
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.
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
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
63
RDBMS
64
RDBMS
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.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
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:
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
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);
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);
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
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);
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);
70
RDBMS
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
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
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>;
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.
3. Composite Index:
It‟s based two or more columns of table.
Removing Index : To remove index from data dictionary use following statement
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:
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.
Removing Synonym
To remove synonym from data dictionary use following statement
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:
Removing snapshot
To remove snapshot from data dictionary use following statement.
Syntax : Drop snapshot <snapshot_name>;
74
RDBMS
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.
75
RDBMS
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.
Declare
Declaration of variables, constants, etc.
Begin
SQL executable statements;
PL/SQL executable statements
[exception]
Error handling code;
End;
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‟;
77
RDBMS
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
Syntax :
If condition then
Sequence of statement 1;
Else
Sequence of statement 2;
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.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. 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
82
RDBMS
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)
84
RDBMS
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.
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.
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 ;
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.
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
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;
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.
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;
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
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.
Syntax :
Lock table table_name in share/exclusive mode)
Example :
1. To lock entire emp table is share mode use following statement
with above lock, we can read and write data from emp table as
e.g. Update emp.
set sal = 10000
where job = „clerk‟;
95