Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 89

UNIT-I

Overview of RDBMS

RDBMS is the abbreviation for Relational Database Management System. Proper


management of data is very essential to run any concern successfully. Before the emergence of
RDBMS, People used DBMS to manage data. But most of the concerns felt that DBMS was not
efficient to meet their expectations. As a result, application developers began to move their
attention to other environment like COBOL and C.

Only in late 1970’s a mathematical E.F.T. Codd injected new blood to DBMS. He applied
principles of relationship to data management. Thus the era of RDBMS began in the early 1980’s.

Data Base Management System

A Database Management system is a collection of interrelated data together with a set of


programs to access the data. The collection of interrelated data is called the Database. Any database
system consists of two parts. They are

a. Database Management System


b. Database Application

The Database Management system is required to organise and maintain the data. The Database
Application is a program to retrieve, insert and update the data in the system.

Services of DBMS

A DBMS provides the following services to do the activities mentioned previously. Let us see
some of the services.

i. Data Definition

This is a method of defining data and its storage.

ii. Data Maintenance

This method verifies whether each record has fields containing all information as defined
using data definition.

iii. Data Manipulation


It allows inserting, updating, deleting and sorting data in the database.

iv. Data Display


Data Display allows viewing data in the database.

v. Data Integrity
This method verifies the integrity or accuracy of data stored in the database.

1
Entity

An entity is an object or a thing such as person, place, concept, activity about which an
organisation keeps information. Graphically entity is represented as a rectangle with name.

Example:

In college system Student, Teacher etc, are called entity.

Student

Attributes

An attribute is the characteristic properties of an entity. It describes the entity. Graphically


attributes are represented as an ellipse with name.

Address

Date of Birth Name


Student

Reg_no

Relationship among data

Relationship is an association between the entities. A relationship may associate an entity


with itself.

There are four different types of relationships among the entities. They are

I. One to One
II. One to many
III. Many to One
IV. Many to Many
1. One to One

A relationship between one entity to only one other entity is called one to one relationship.

One to many

Example

Assign
Student Reg_no

2
2. One to many

A relationship between one entity to more entity is called one to many relationship.
Student 1
Example

3.
Teacher Teach Student 2

3. Many to One Student n

A relationship between more entities to one entity is called many to one.

Student 1

Student 2 Enrolled Course

Student n

4. Many to Many

A relationship associated by more entities with more entities is called Many to many.

Student 1 Game 1

Student 2 Play Game 2

Student n Game m

Database Models

Database model is a technique to store the database in a DBMS. Each DBMS follows
different database model. Database models can be classified into two groups. They are:

1. Object based logical model


2. Record based logical model
1. Object based logical model

In this model, the data relationship and contains are defined as a collection of idea tools.

2. Record based logical model

This model describes the data structures and techniques of a DBMS. There are four types of
record based logical model.

3
 File Management System
 Hierarchical Database System
 Network Database System
 Relational Database System
a. File Management System

File Management system is the first method used to store the data in the database. In this model the
data items are stored sequentially in a file. If we want to search an item in a file, the search starts
from the first record and items are checked sequentially till the search item is matched.

Disadvantages

1. Searching and retrieving a record is a very tedious process because it supports only
sequential access.
2. Updating the data items takes more times.
3. It is not supporting directly for altering the file structure.
4. Inserting and deleting process is not easy.
b. Hierarchical Database System

Hierarchical database system keeps the data in the form of Parent-Child relationship. The
data is organised as a Tree Structure. The origin of data is the root of the data tree. The data
occupies with different level of the particular branch of the tree called the node. The last node in
the structure is called leaf. The high level node points to zero or more node(child) in the next
level. Each child has pointers to numerous siblings (Children have same parent) and there is one
pointer to the parent (one to many relationship)

Polytechnic College

CIVIL MECH MOP

II YEAR III YEAR II YEAR III YEAR I YEAR II YEAR III YEAR

A CLASS B CLASS A CLASS B CLASS

4
C Network Database System

In this model data are represented by a collection of records and the relationships among data
are represented by links (pointer) NDS supporting Many to Many relationship.
Amutha
Computer

Kalai
Maths
Anitha

d Relational Database system

A data model in which both data and their relationship are represented by means of table is
called relational model. Each row of a table is called tuple and each column of a table is called an
attribute.

Example

In a college system, the relations students, books and book issue.

Students table

ROLL NAME CLASS


NO
101 Rakesh DCE
102 Ramesh DCE
103 Suresh DCE
.
.
.
151 Rajesh DCE
Books Table

Acc No Title Author


1. Relational Database Management System P.Selva Gopal

2 Programming in c Bala Gurusamy


Book _ issue table

ROLL ACC NO ISSUE DATE


NO
101 1 12/6/12
102 2 12/6/12

5
Codd’s Rule

There are thirteen rules for a DBMS to be relational called codd’s rule. They are

1. Information Rule
2. The rule of Guarantee Access
3. Primary key
4. The systematic treatment of null values
5. The database description rule
6. Comprehensive Data Sub Languages
7. The view updating rule
8. The insert and update rule
9. The physical independent rule
10. The logical data independence rule
11. The integrity independent rule
12. The distribution rule
13. The non sub version rule

1. Information Rule

The information is logically and explicitly represented as a table.

2. The rule of guaranteed Access

Every data in the information can be identified with the help of table name, primary value
and field name.

3. Primary Key

Primary key avoids the duplicate entry and null values in the table.

4. The systematic treatment of null values

The RDBMS supports for null values (zero or space) to represent missing or inapplicable
information.

5.The database description rule

RDBMS keeps the description of database in the data dictionary to maintain database.

6. Comprehensive data sub language

The rule is supporting for data definition, View definition and data manipulation.

7. The view updating rule

All views are theoretically updateable. It can also be updated by the system.

6
8. The insert and update rule

A single operand must be holding good for all retrieval, update, delete and insert activities.

9. The physical independent rule

Application program is not dependent when any change is made in storage representation.

10. The logical data independent rule

The changes should not affect the user’s ability to work with the data. The change can be
splitting the table into many more tables.

11. The integrity independence rule

The integrity constraints should be stored in the database in the table.

12. The distribution rule

The system can be able to manipulate the data that is distributed in other system.

13. The non sub version rule

This rule states that different levels of the languages cannot by no space pass the integrity
rules and constraints.

Relational RDBMS

1. Database Management System

It means working with and managing set of data that attends to 3 specific things.

a. Data structure
b. Data integrity
c. Data Manipulation
a. Data structure
2. Data Definition

Defining the data in RDBMS.

3. Table
The table is a data structure that is used to hold the data in RDBMS. The table consists of
rows. Row stores the data of a table. Row consists of Column. Column in a table represent
one and only one attribute of the entity.

Introduction to Oracle

The oracle corporation was started in 1971 with the name relational software incorporated
(RSI) by Larry Ellison and his associates. During the release of version 3 of Oracle, the company
change its name from RSI to Oracle Corporation. Oracle is a new product supporting Object

7
Relational Database Management System (RDBMS). Oracle products are based on Client/Server
architecture. It means that the processing of application is classified as client side processing and
Server side processing. Client side processing performs all activities that help the user to interact
with the application. Server side processing performs all activities related to the database.

Tools of Oracle

The main tools provided by oracle are

1. SQL * PLUS
2. PL/SQL
3. FORMS
4. REPORTS
1. SQL * PLUS

SQL * PLUS is a structural language supported by Oracle. Though this we can store, edit,
retrieve, enter and run SQL commands. Also we can perform calculations, list out the column,
definitions for any table and can also format query results in the form of a report.

2. PL/SQL

PL/SQL stands for Programming Language was structured Query languages and is a
extension of SQL. A PL/SQL block contains any number of SQL elements.

3. FORMS

It is a graphical tool provided by Oracle. It is used for generating and executing forms based
application. A form consists of block and field. Multiple table can also be accessed over a single form.

4. REPORTS

This tool is used for developing and printing reports. A wide variety of reports can be
developed using this tool.

ORACLE ARCHITECTURE

Oracle manages a lot of interrelated processing and voluminous of data. An oracle database
has a physical structure as well as a logical structure and is separated in the server. Hence
knowledge about the oracle architecture is essential to manage the disk space and for the controlled
availability of data.

Database

A database is a collection of data and can be considered as a separate unit.

The contents of a database are viewed differently at different level.

1. At physical level, a database consists of a group of data files.

Select item_id, stock from item_master where item_id = ‘RKT001’

8
Item_id Stock
RKT 10
001
2. At logical level, a data base consists of a group of table space.

Usually a user in Oracle does not know the architecture of Oracle. Without the knowledge of
the architecture, a user can use all oracle tools. But, if he has a thoroguh knowledge in the
architecture, he can tune the database and can use it effectively.

Data files

The physical storage files where the data are stored are called datafiles. Data can be stored
in a single data file or multiple data files and are kept in a table space.

Table spaces

A table space is a logical storage division of a database. It organises the physical storage of
database information. Every user can set his default table space. When a user creates a database
object such as table view or index without mentioning the table space for the object, then Oracle
stores the object in the user’s default table space. If a user does not his default table space then the
SYSTEM table space acts as the default table space.

Table space names and contents

A table space contains all database objects like tables views, indexes, sequences, procedures and
synonyms. Logically a table space consists of a group of segments for organising the internal
structures.

The system table space

Every database has the system table space. This table space is created automatically when we create
a database.

Temp table space

Oracle requires some temporary space to perform processes. So we can create a temporary table
space to process SQL Statements. Unless a user specifies, the system table space is the temporary
table space.

Example

Create temporary table space named temp_inventory

Create table space temp_inventory data file

D:\inodbf\inu_temp.dbf ‘temporary’;

Tools table space

This table space is used to install all our database tools objects like oracle form, tables and oracle
report tables.

9
User table space

Every user should place his tables in this table space. User table space must have low default
storage.

Data and index table space

This table space is used to store indexes.

Roll back table space

Changed data are recorded in the rollback segments and are kept in rollback table space till they are
committed. This table space must have large default storage.

Data models

A collection of tools for describing data, data relationship consistency constraints are called data
models. Data models are classified into three different groups. They are

I. Object based logical model


II. Record based logical model
III. Physical model

Object based logical model

Object based logical model are used in describing data at the logical and view levels. They
are many different models.

1. The entity relationship model


2. Object oriented model
3. Semantic data model
4. The functional data model
1. The entity relationship model

The entity relationship model is a collection of basic object called entities and relationship
among this objects. An entity is a thing or object that is distinguishable from other objects.

Example

Each person is an entity and bank accounts can be considered to be entities.

 Rectangle which represents entity sets


 Ellipses which represent attributes
 Diamonds which represents relationship among entity sets
 Lines which link attributes to entity sets and entity set relationships

The object oriented model

10
Like the E-R model, the object oriented model is based on a collection of objects. An object contains
values stored in instants variable within the object.

For example

Assume that the bank had been playing 6% interest on all accounts, but now, the banks changes this
policy to pay 5% if the balances less than RS. 45,000 or greater under the object oriented model, the
only change to be made is within pay interest method. The external interface to the objects remains
unchanged.

Semantic data model

Semantic data models are the predecessors are object oriented model. Interdependencies
among the entities can be express in this model.

The function data model

Object, properties and their relationship are viewed uniformly are defined as functions in
this model.

Record based logical model

There are three types of record based logical model.

a) Relational model
b) Network model
c) Hierarchical model

a). Relational model

a data model in which both data and their relationship are represented by means of table is
called relational model. Each row of a table is called tuple and each column of a table is called an
attribute.

Example

In a college system, the relations students, books and book issue.

Student table

ROLL NAME CLASS


NO
101 Anitha DCE
102 Swedha DEEE
103 Kavitha DECE
. . .
. . .
. . .
150 Mala DMOP
BOOKS TABLE

11
ACC TITLE AUTHOR
NO
15531 DATA STRUCTURE Selva Kumar
15532 PROGRAMMING IN Bala Gurusamy
C
15533 VISUAL BASIC 6 Raj kumar
BOOKS ISSUE TABLE

ROLL ACC NO DATE


NO
101 15531 2/6/2012
102 15532 4/6/2012
103 15533 4/6/2012
. . .
. . .
. . .
140 15573 5/6/2012
Physical data model

Physical data models are used to describe data at the lowest level.

Network model

In this model data are represented by a collection of records and the relationship among data are
represented by links (pointer). Net work model is a supporting many to many relationship

Example

Amutha
Computer

Kalai
Maths
Anitha

Hierarchical model

This model keeps the data in the form of parent-child relationship. The data is
organised as a tree structure. The origin of a data is root of the data tree. The data
occupies with different level of the particular branch of the tree called node. The last
node in the structure is called leaf.

Polytechnic College

CIVIL MECH 12 MOP


A CLASS B CLASS A CLASS B CLASS

E-R relationship consists of a set of basic objects called entities and relationship among these
objects.

Basic concepts

There are three basic concepts in E-R Model.

 Entity sets
 Relationship sets
 Attributes

Entity

An entity is an object, place, person are event that the system stores information about.

Example

Employee, Student, Machine etc.

Entity sets

It is a set of entity of the same type that share the same attributes.

Example

The set of all persons who are students at a given department .

Department Department No Student Name


Name
Commerce 1 Kathir
Computer 2 Kala
Physics 3 Kannan
stry 4 Kavitha
History 5 Kesavan
English 6 Kannaki

Attributes

An attributes are the characteristic properties of an entity. It describes the entity.

13
Types of attributes

An attributes can be classified into two types. They are

Simple and Composite Attributes

Single value and Multivalue Attributes

Simple Attributes

The attributes have been simple that is they are not divided into sub parts.

Composite Attributes

Composite Attributes can be divided into subparts.

Example

Entity- Student

Composite Attribute – student name

Student Name

First Name Middle Name Last Name

Single Valued Attributes

All the attributes that we have specified have a single value for a particular entity.

Example

Reg_no

Multi valued Attributes

There may be instances were an attributes has a set of values for a specific entity

Example

Student_Marks

Relationship Sets

The collection of all entity of the same type is an entity set and the collection of all
relationship of the same type is a relationship set.

Keys in entity sets

14
A key is a property of the entity set rather than of the individual entities.

Super key

A super key is a set of one or more attributes than taken collectively, allow us to identify
uniquely and entity in the entity set.

Example

Entity Attributes

Student Name, Address, Status, Roll_no

In this example, roll_no is the super key.

Candidate and super key

If the relation has more than one key and each of the key is called candidate key.

Example

Entity Attributes

Student Name, Address, Status, Roll_no

In this example Name is a candidate key.

Keys in relationship set

The primary key of an entity set is used to distinguish that entity set among the various
entity sets. Similarly a mechanism is needed to distinguish among the various relationship of a
relationship set.

Weak entity set

An entity set may not have sufficient attributes to form a primary or super key. Such an
entity set is called weak entity set.

Example

Student_name , Course_name, Institution name

Normalization

Normalization is associated with relational database model. In general aim of a relational


database design is to generate a set of relational schemas to store and retrieve information easily.

Relational Schemas

A relational schema is a set of attributes in one or more relation to design schema in an


appropriate normal form, the normal forms are defined using functional and data dependancies.

Example

15
Consider the relation sports shown in the table.

Player_no Player Team College Coacher


10001 Amutha Basket Ball American College Kannan
10002 Arun Cricket Madura College Kumar
10003 Vanitha Baket ball American college Kannan
10004 Varathan Cricket Madura College Kumar
10005 France Football Madura College Gopi

Functional Dependency

Let A and B two set of attributes. B is said to be functionally dependent on A if a given value
for each attribute in a uniquely determines the values of attributes in B. The dependency is denoted
by A B

In the schema student (stu-id, name, mark1, mark2, total, rank

Total, Rank Name

Name, Total Rank

Pitfalls in relational database design

The aim of Relational Database design is to generate the relations to store and retrieve
easily. A bad database design leads to the following undesirable properties

 Repetition of information
 Update anomalies
 Insertion anomalies
 Deletion anomalies

Repetition of information

Repeating information waste space. It increase the size of the database. For example, in the
course relation schema, the attributes team, college and coacher are stored several times in the
database.

Update anomalies

Any change made to record affects all the other records in the database.

For example

If we want to change the coacher of cricket in the Madura college, all other records
belonging to the cricket team of Madura college should be changed.

Insertion anomalies

We cannot insert a part of the information in to a relational schema.

16
Example

Suppose if we want to add a new coaher to our database, we cannot insert his details
without any player under team. We must need all attributes of the record.

Deletion anomalies

The deletion of some information leads to deletion anomalies.

For example

If the coacher coaches only one player and if the player discontinues from the course then the
information about the coacher is also lost.

Boyce Code Normal Form (BCNF)

A relational schemas are said to be in (BCNF) with respect to a said as functional


dependencies (FS). A database scheme in BCNF is every relation scheme in the database.

Example

The relational schema student (rollno, name, project) with functional dependencies.

Rollno Name

Rollno Project

sIn each functional dependencies (F+). Rollno is a super key. Hence student
schema in BCNF.

17
UNIT II

Oracle Data Types

Data are stored in a table which is a collection of fields (cells). Hence we must specify
the data type that suits the data we want to store in a column (field). Oracle supports the
following data types.

A. character data types

1. CHAR
Char data type is used when a fixed length character string is required. Upto 2000
bytes can be stored in this data type. The default value is one byte.
Syntax
CHAR (SIZE)

Where
Size- Number of characters. It is varying from 1 to 2000 bytes.
Example
Name Char(20)
2. Varchar2
This data type is used to store variable length character strings. It can also store alpha
numerical values. The size of this data types varies from 1 to 4000 bytes.
Syntax
VARCHAR2 (SIZE)
Where

Size- number of characters (up to 4000 bytes)

Example

Address varchar2(50);

3. Long

Cells of this data type can store variable character strings upto 2GB. Based on the memory
space available in the computer, its length would be restricted. Only one column in a table
can have this data type.

B. Number data types

1. Number

Number data type is used to declare a column to store only numbers. This type
supports the storage of integers, real numbers, floating point numbers etc.

18
Syntax

NUMBER (P,S)

Where

P- Total number of digits (1 to 38)

S- Number of digits to the right of the decimal point (-84 to 127)

Example

Salary number (10, 2)

Syntax

NUMBER (P)

Where

P is the total number of digits

Example

Roll_no number (4)

C. Date Data type

All types of time related information, including data and associated times can be
stored in a column declared with Date Data type.

Syntax

DATE

The standard date format in DD-Mon-YY

DD- The date in number

Mon- The first three letters abbreviation of a month

YY- The last two digits of a year.

Example

Date_of_birth DATE

D. Raw Data Type

This data type is used to store binary data. A maximum of 2000 bytes can be stored
in this data type. Manipulation of data stored in this data type is not possible.

19
Syntax

RAW(size)

Where

Size- size of the data (maximum 2000 bytes)

E. Long raw data type

Binary data up to a maximum size of 2GB can be stored in this data type. Like Raw
data type, manipulation of data is not possible in this data type.

Syntax
RAW(size)

Where

Size- size of the data

F. LOB Data type

LOB is known as Large Object data type. Unstructured information like sound files,
video clips can be stored in this data type. The size of the data type is upto 4GB.

Syntax

LOB(size)

Where

Size- size of the data

I. Data Definition Language

The Data Definition Language is used for the following purposes.

1. To create an object
2. To alter an structure of an object
3. To drop an object

Some of the objects are Table, View, Sequence, Cursor etc.

DDL used for a table

The Data Definition Languages used for table definition are classified as

1. Create table command


2. Alter table command

20
3. Truncate table command
4. Drop table command

1. Creating a table

Syntax

Create table <table name> (column1 datatype1,…, column n datatype n);

Example

SQL> Create table student (roll_no number(4), name varchar2(15), DOB DATE, address
varchar2(100));

If the above command is executed successfully, the message “table created” is


displayed.

Important points to be observed while defining a table

 The first letter should be an alphabet.


 Oracle reserve words cannot be used as table name.
 The length of a table name should not exceed 30 characters.
 Different tables should have different names.
 Underscore, numerals and letters are allowed. Blank space and single quote are not
allowed.
 Double quotes can be used for naming a table. In this case the tables “student”,
“Student” and “STUDENT” are all different tables.

2. Altering a table

The structure of a table can be changed using this command. Using this command
we can do the following.

 Add a new column


 Change the width of a data type
 Change the data type of the column
 Include an integrity constraint
 Drop an integrity constraint

Syntax

Alter table <table name> modify (column datatype,…);

Alter table <table name> add (column datatype,…);

21
Example

SQL> Alter table student modify (name varchar2(25));

SQL> Alter table student add (tel_no number(7));

Truncating a table

Syntax

Truncate table <table name>;

This command is used to delete all records stored in a table. If we use this command,
the structure of the table is retained.

Example

SQL> Truncate table student;

Dropping a table

This command is used to remove a table from the data base.

Syntax

Drop table <table name>;

Example

SQL> Drop table student;

If the statement is executed successfully, “table dropped” will be displayed.

Viewing a table’s structure

Desc command

If the user wants to view a structure of a table, this command can be used.

Syntax

Desc table_name;

22
Example

Desc stuent;

Output:

Name NULL? Type

-----------------------------------------------------------------------------------

Roll no number(4)

Name varchar2(25)

DOB DATE

Address varchar2(100)

-----------------------------------------------------------------------------------

II. Data Manipulation Language (DML)

Data Manipulation languages are used to manipulate the data. Manipulation of data
includes the insertion of the data into the data base, modifications of data stored in the data
base, deletion of data stored in the database, retrieval of data for further manipulation.

Data Manipulation commands all the most frequently used SQL Commands and they
are:

 Insert
 Select
 Update
 Delete

Insert command

Insert into command is used to add one or more rows to a table.

i. Insert a Single Row

Syntax

Insert into table name (column name1, column name2) values (expression1, expression2);

Example

SQL> insert into student (Name, Reg_no, Mark, Course) values (Harish, 001, 90, ‘BE’);

ii. Inserting more than one row

23
Insert command is used to add one or more rows to a table which using this
command. The values must be entered in the same order as they are defined in the table.

Syntax

SQL> insert into student values (‘&Name’, &Roll_no, &Mark, ‘&Course’);

As soon as the statement is executed, Oracle will prompt the user to enter values for all the
columns in the table.

Output

Enter value for Name: Ashok

Enter the Roll_no: 101

Enter the Mark: 85

Enter the course: BE

On successful execution of the command, the message “ 1 row will be created” will be
displayed.

iii. Inserting a Data into a Table From Another Table:

Syntax
INSERT INTO <new table name> SELECT * (columnname1, columnname2 …..) FROM <old
table name>;

Example

A data from Student table Insert into another table Student1.

SQL> INSERT INTO student1 select (name, regno, mark, course) from student;

iv. Inserting Selected Data into a Table From Another Table:

Syntax
INSERT INTO <NEW TABLE NAME> SELECT (columnname1, columnname2….) FROM <old
table name>;

Example
SQL> INSERT INTO Student1 (name, regno, course) FROM student;

v. With Condition Transfer Of Selected Data:

24
Syntax
INSERT INTO <Table New Name> SELECT (columnname1, columnname2…….) FROM <old
table name> where columnname=Expression;

Example
SQL> INSERT INTO Student1 SELECT mark FROM Student WHERE name = ‘harish’;

SELECT COMMAND
After creating and adding data to the table the most important operation to view the
entered data. The SELECT command is used to view the data.

i. Retrieve all records:

The following syntax is used to view or retrieve all the contents or the table.

Syntax
SELECT * FROM table name;

Example
SQL> select * from student;

ii. Retrieve specific columns:

The following syntax is used to view or retrieve specific columns from the table.

Syntax
SELECT column name1, column name2 from table name;

Example
SQL> select name, course from student;

iii. Retrieving data on specific condition using WHERE clause:

To select specific rows from a table we include a “WHERE” clause in the select
command. It can appear only after the ‘FROM’ clause we can retrieve only the rows which
satisfy the ‘WHERE conditions.

Syntax
SELECT *FROM table name WHERE search conditions;

Example

25
Retrieve all student information from the student table where mark field is greater
then 60.

SQL> SELECT * FROM student WHERE mark> 60;

In the search condition, we can use all operators such as logical, arithmetic,
relational etc.

iv. Retrieve specific data set from the table and also to select the columns needed:

Syntax
SELECT column name, column name FROM table name WHERE search condition;

Example

SQL> SELECT name, regno FROM student WHERE course = ‘Bcom’;

The above command will list name and regno of the student from the student table
for the course is equal to Bcom.

v. Elimination of duplicates from the SELECT command:


To prevent the selection of duplicate rows, we include DISTINCT clause in the SELECT
command.

Syntax
SELECT DISTINCT column name, column name from table name;

Example
SQL> select DISTINCT name FROM student;

The above example eliminate the duplicate name entries when retrieving data from
name column of student.

vi. Sorting Data


We can view data in an arrange manner ie., sorted order with the SELECT command
using ORDER BY clause. The order may be either in ascending or descending depending on
the condition specified in the syntax.

Syntax

SELECT *FROM table name ORDER BY column name, column name, (sort order);

Example
SQL> SELECT * FROM student ORDER BY name;

This will list all particulars with ascending order.

For descending order we must mention in the last before semicolon.

26
Example
SQL> SELECT name, regno FROM student ORDER BY name desc;

The ‘ORDER BY’ clause should be the last clause in a SELECT command.

UPDATE COMMAND
Update command is used to changing values in one or two columns of a rows in a
table. Specific rows can also be updated based on some condition. This update command
can be used with or without condition.

Without condition:

In without condition the update command consist of ‘SET’ clause

Syntax
UPDATE table name SET column name =expression, column name =expression;

Example
SQL> UPDATE student SET total=m1+m2+m3;

SQL> UPDATE student SET total=m1+m2+m3, avg=total/3;

With condition:

The UPDATE command consists of ‘SET’ clause and an option ‘WHERE’ clause.

Syntax
Update table name set column name=expression, column name =expression…(WHERE
CONDITION);

Update sets each field with the value that we supply, provided it satisfies the
‘WHERE’ condition.

Example
To change the columns total and average for the particular name of the student.

SQL> UPDATE student SET total=m1+m2+m3, avg=total/3 WHERE name = ‘harish’;

The contents of the row for the student harish will be charged.

SQL> update emp set salary=2000 where designation = ‘accountant’;

27
DELETE
The Delete command is used to delete the unwanted data from a table. This command
is used to delete all the rows or a selected set or rows using with conditions.

Delete all rows:

This command is used to remove rows from a table.

Syntax

DELETE FROM table name;

Example
SQL> DELETE FROM student;

This command will delete all the rows in a student table.

Delete the specific Rows:

This command is used to remove the selected set of rows from a table.

Syntax
DELETE FROM table name WHERE condition;

Example
1. SQL> DELETE FROM student WHERE name= ‘deepak’;

This command will delete the contents from the student table for a name is equal to
Deepak.

2. SQL> DELETE FROM emp WHERE salary<5000;

The above example will delete rows for the salary is less than Rs.5000.

III. Transaction Control Language

All changes made to the database is defined as transaction. It is a logical unit of


work. The transaction can be made permanent to a database only if they are committed.

Transaction control commands included

 COMMIT
 ROLLBACK
 SAVE POINT

28
Commit command

The commit command is used to make all transaction changes permanent to the
data base.

Syntax

COMMIT;

Rollback

Rollback command is used to undo all the changes made in the current transaction.
We can either rollback the entire transaction.

Syntax

ROLLBACK;

This will rollback (undo) the entire transaction.

Save point

Save point is not a command. It is only a marker. Savepoints are used to divide a
lengthy transaction into small ones.

Syntax
The syntax is

SAVE POINT savepoint_id;

Example
INSERT…….

UPDATE……

DELETE…….

SAVE POINT one;

INSERT…..

29
DELETE…..

SAVE POINT two;

RollBack to Savepoint id1;

This will undo all changes made after the creation of the savepoint id1.

IV. Data Control Language

Data Control Language provides users with privilege commands. The database
objects (table, view etc) of a user can’t be accessed by another user without the
permission of the owner user. The owner can allow other user to access his objects as per
his direction. The permission given by a user(owner) to another is called a privilege.

The data control commands are

 Grant Privilege
 Revoke Privilege

Types of Privileges

A permission granted to a user to do some action is called a privilege. There are two
types of privilege.

1. System Privilege
2. Object Privilege

1. System Privilege

The permission granted to execute various data definition commands like create
table, alter table, drop table, view table are called system privilege

Granting System Privilege

GRANT Command is used to give system privileges to an Oracle User.

Syntax

Grant system privilege to user

Example

SQL> Grant create table to Rajan;

30
2. Object Privilege

An object privilege enables a user to execute some command on database objects


like alter, insert, delete, update, select etc.

Revoke Command

Permissions granted to a user can also be taken by a Grantor. This can be done by
the revoke command.

Example

SQL> Revoke select on student from rajan;

DATA CONSTRAINTS

Apart from the cell name, cell length and cell data type there are other
parameters are called data constraints. An integrity constraint is a rule that restricts the
values for one or more columns in a table. The constraints can either be placed at the
column level or at the table level.

Column Level and Table Level Constraints

If the constraints are defined along with the column definition, it is called as column
level constraint. Column level constraint can be applied to any one column at a time. If the
constraint extends across multiple columns, the user will have to use table level constraints.

NULL Value concepts

If a particular column is left blank value while inserting data to a table, that value is
said to be null. Columns of any data type may contain nulls unless the column was defined
as not null when the table was created.

Example:

SQL> Create table client_master (client_no varchar2(6) NOT NULL, name varchar2(20) not
null, address1 varchar2(20));

Primary key concepts

A primary key is one or more columns in a table used to uniquely identify each row
in a table. Primary key values must not be null and must be unique across the column.

Example

SQL> Create table sales_master (item_no number(6) primary key, item_name


varchar2(20),qty_hand number(6));

31
Primary key as a table constraint

Example

SQL> Create table sales_order_details (sorder_no varchar2(6), product_no varchar2(6),


qty_order number(8), product_rate number(8,2), primary key (sorder_no, product_no));

Unique Key concepts

The unique constraint designates a column or combination of a column as a unique


key. To satisfy a UNIQUE constraint, no two rows in the table can have the same value for
the unique key.

Example

SQL> Create table dept (deptno number(2), dname varchar2(10), loc varchar2(10),
constraint unq_dname1 UNIQUE(dname));

Default value concepts

At the time of cell creation a default value can be assigned to it. The data type of the
default value should match the data type of the column.

Example

SQL> Create table passbook (p_no number(6) primary key, amount number(8,2),
trans_type char(1) default ‘D’, balance number(10,2));

Foreign key concepts

A foreign key means that values in one table must also appear in another table. The
referenced table is called the parent table while the table with the foreign key is called the
child table. The foreign key in the child table will generally reference a primary key in the
parent table.

A foreign key can be defined in either a CREATE TABLE statement or an ALTER TABLE
statement.

EXAMPLESQL> CREATE TABLE supplier


( supplier_id numeric(10) not null,
supplier_name varchar2(50) not null,
contact_name varchar2(50),
CONSTRAINT supplier_pk PRIMARY KEY (supplier_id)
);

32
CREATE TABLE products
( product_id numeric(10) not null,
supplier_id numeric(10) not null,
CONSTRAINT fk_supplier
  FOREIGN KEY (supplier_id)
  REFERENCES supplier(supplier_id)
);
Check integrity constraints

The CHECK constraint explicitly defines a condition. To satisfy the constraint, each
row in the table must take the condition either TRUE or unknown.

Example

SQL> Create table student (regno number(6) primary key, name varchar2(20), Mark1
number (3) check (mark1>=0 and mark1<=100), Mark2 number (3) check (mark2>=0 and
mark2<=100), Mark3 number (3) check (mark3>=0 and mark3<=100), Total number(3));

Defining integrity constraints in the ALTER table command

We can define integrity constraints using the constraint clause in the ALTER table
command. The following examples show the definitions of several integrity constraints.

Example

SQL> Alter table supplier_master add primary key (supplier_no);

Dropping integrity constraints in the alter table command

We can drop integrity if the rule it enforces is no longer needed. We can drop the
constraint using the ALTER table command with drop clause.

Example

SQL> Alter table supplier_master drop primary key;

Queries and SQL Functions

Queries

1. Creating a table from an existing table

Using the select statement we can create a table and copy the records into it from an
existing table.

33
Example

SQL> Create table staff (id, name, dob, doap, department) as select roll_no, name, dob,
doad, class from student_master;

Oracle creates a new table STAFF with columns id, name, dob and doap whose
datatypes are same as that of roll_no, name, dob, doad respectively in the student_master
table.

Example

SQL> Create table hosteller as select * from student_master;

Oracle creates a new table hosteller exactly same as the table student_master

2. Inserting rows into a table using select command

If we want to copy the data from one table into another table we can use the SQL
Command.

Syntax

SQL> Insert into employee (id, name, dob, doap) select id, name, dob, doap from staff;

Insertion of selected data into a table from another table

We may want to insert some specific records from the source table

Example

SQL> Insert into employee (id, name, dob, doap) select id, name, dob, doap from
staff where name= ‘s.vasuki’;

Operators in SQL*PLUS

SQL * PLUS Supports the following operators. They are

1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators
1. Arithmetic Operators
We require arithmetic operators to perform calculations in SQL Command.
The arithmetic operators are

Operation Operator
Addition +
Subtraction -
Multiplication *

34
Division /
Example

SQL> Update student SET Total = mark1+mark2+mark3;

2. Comparison Operators
Comparison operators are used to compare two expressions. The comparison
operators are discussed below.

Operation Operator
Equal to =
Not Equal to !=
Less than <
Not Less than or Equal <=
to
Greater than >
Greater than or Equal to >=

There are also some more useful operators. They are


Between – To check between two values
In – To matched with any other values in the list
Like – Pattern Matching

Example1

SQL> Select roll_no, name from student_master where class= civil;

Example2

SQL> Select item_name, cost_price from item_master where cost_price between


500 and 1000;

Logical Operators

Logical operators are used to combine two or more conditions. The value of a
condition is either true or false.

List of Logical Operators

 &
 Or
 Not

Example

35
SQL> Select name, address from student_master where city= virudhunagar and class = mop;

Oracle Function

A function takes one or more arguments and returns a value. Functions are also
capable of accepting user supplied variables or constants and operating on them. Such
variables or constants are called arguments.

Types of sql functions

SQL Functions can be widely classified into two groups. They are:

1. Single row Functions or Scalar Function


2. Group Functions or Aggregate Functions

1. Single row Functions or Scalar Function

Functions that act on only one value at a time are called single row function. The
single row functions are classified as

A. Numeric Functions
B. Date Functions
C. String Values or Character Functions
D. Conversion Function
E. Miscellaneous Function
A. Numeric Functions

Numeric functions accept numeric arguments and return numeric values. The
values returned by a numeric function are accurate up to 38 decimal digits.

i. ABS

SYNTAX :
ABS(n)
Purpose : Returns the absolute value of n

Example: SQL> Select ABS (-129.56) from dual;

Output: ABS (-129.56)

----------------

129.56

ii. CEIL

SYNTAX :
CEIL (n)

36
Purpose : Returns smallest integer greater than or equal to n .

Example: SQL> Select CEIL (134.78) from dual;

Output: CEIL (134.78)

----------------

135

iii. COS
SYNTAX :
COS (n)

Purpose : Returns cosine of n, n being expressed in radians.

Example: SQL> Select COS (45* (22/7/180)) from dual;

Output: COS (45* (22/7/180))

--------------------------

0.70688321

iv. EXP
SYNTAX :
EXP (n)

Purpose : Returns en.

Example: SQL> Select EXP(5) from dual;

Output: EXP (5)

-------------

148.41316

v. FLOOR
SYNTAX :
FLOOR (n)

Purpose : Returns the largest integer less than or equal to n.

Example: SQL> Select FLOOR(149.7) from dual;

Output: FLOOR (149.7)

-------------

37
150

vi. LOG
SYNTAX :
LOG (m,n)

Purpose : Returns the logarithm, base of n(log m,n) where m is any positive number
other than and 1 and n is any positive number.

Example: SQL> Select LOG(10,1000) from dual;

Output: LOG(10,1000)

-------------

vii. MOD
SYNTAX:
MOD(m,n)

Purpose : Returns the remainder when m is divided by n. If n is 0 and returns m.

Example: SQL> Select MOD(13,3) from dual;

Output: MOD(13,3)

-------------

viii. POWER
SYNTAX:
POWER(m,n)

Purpose : Returns mn.

Example: SQL> Select POWER(7,3) from dual;

Output: POWER(7,3)

-------------

343

ix. SQRT
SYNTAX:
SQRT (n)

Purpose : Returns Square root of n, n must be non-negative.

38
Example: SQL> Select SQRT(25) from dual;

Output: EXP (25)

-------------

B. DATE FUNCTION
Date function accept date input and may return a value of date type.

i) ADD_MONTHS
SYNTAX :
ADD_MOMTH (d,n)

Purpose : Returns the date d after n months.

Example: SQL> Select dob, add_months(dob,60) from student_master;

ii) Last_Day
SYNTAX LAST_DAY (d)

Purpose: Returns the date of the last day of the month that contains d.

EXAMPLE: SQL> Select name, doad, last_day(doad) from student_master;

iii) MONTHS_BETWEEN

SYNTAX
MONTHS_BETWEEN (d1, d2)
Purpose: Returns the number of months between d1 and d2.

EXAMPLE: SQL> Select name, month_between (doad,dob) from


student_master;

iv) NEXT_DAY
SYNTAX NEXT_DAY (d,day_name)

Purpose: Returns the first date which is day name that comes after the date d.

EXAMPLE: SQL> Select next_day(’27-FEB-2000’ , TUESDAY) from dual;

v) SYSDATE

SYNTAX SYSDATE

PURPOSE: Returns the current date and time.

39
EXAMPLE

SQL> Select to_char (SYSDATE, ‘DD-MM-YYYY HH24: MI: SS’);

OUTPUT

From Dual

NOW

------

02-06-2012 10:27:11

C. CHARACTER FUNCTION

Character functions accept character input and return either character or number
values. The following are the character functions.

1. INITCAP:

Syntax INITCAP(char)

Purpose: Returns string with first letter in upper case.

Example
SQL> SELECT INITCAP (‘WELCOME’) FROM dual;

OUTPUT: Welcome.

2. LOWER:

Syntax

LOWER(CHAR)

Purpose: Returns char, with all letters in lower case.

Example
SQL> SELECT LOWER (‘HARISH’) FROM dual;

Output: harish

3. UPPER:

40
Syntax
UPPER (CHAR)

Purpose: Returns char with all letters in upper case.

Example
SQL> select UPPER (‘harish’) from dual;

Output: HARISH

4. LTRIM:

This function removes character from the left of char with initial characters removed
upto the first character not in set.

Syntax

LTRIM (CHAR [SET])

Purpose: This function removes character from the left of char with initial characters
removed upto the first character not in set.

Example
SQL> select LTRIM (‘srharish’,sr) from dual;

Output: harish.

5. RTRIM:

This will return char, with final characters removed after the last character not in the
set.

Syntax RTRIM (char, [set]).

Purpose: This will return char, with final characters removed after the last character not in
the set.

Example
SQL> SELECT RTRIM (‘HARISHPRABHU’, ‘PRABHU’) FROM dual;

Output : HARISH.

6. SUBSTR:

Syntax
SUBSTR(char,in,n)

41
Purpose:
This function returns a portion of char, beginning at character ‘in’ exceeding up to ‘n’
characters. If ‘n’ is omitted, result is returned up to the end char. The first position of char
is 1.

Example

SQL>select SUBSTR (‘RAMACHANDRAN’,5,8) from dual;

Output: CHANDRAN.

7. LENGTH:

This will return the length of character.

Syntax
LENGTH(char)

Purpose: This will return the length of character.

Example: SQL>select LENGTH (‘Sekar’) from dual;


Output : 5.

D. CONVERSION FUNCTION
Conversion value convert a value from one data type to another. The conversion
function are classified into three categories. They are
1. To_char
2. To_date
3. To_number

1. To_char, date conversion

Syntax

To_char (d [, fmt]

Purpose

Convert the date d to varchar2 data type, in the format specified by the date format
fmt.

Example

SQL> Select sales_no, to_char (sales_date, ‘dd-month-yyyy’ from sales_master;

Output:

42
Sales_to_char (sales_date)

---------------------------------

S01 02-January- 2012

S02 12-January-2012

S03 31-March-2012

2. To_char number conversion

Syntax

To_char(n[,fmt])

Purpose

Convert the number n to varchar2 data type using the optional number format fmt.

Example

Select item_name, to_char (stock*cost_price, ‘9,99,999.99’) from item_master, item_name;

Output

Item-name cost*price

A4PAPER 40,000.00

A3 PAPER 44,000.00

MOUSE 52,500.00

KEYBOARD 62,500.00

E. MISCELLANEOUS FUNCITONS
The following functions are also supported by Oracle.

1. UID

Syntax

UID
Purpose

Returns an integer that identifies the current user uniquely.

Example

SQL> Select UID from dual;

OUTPUT

43
UID

-----

22

2. USER

SYNTAX

USER
T
Purpose : Returns the current Oracle User.

Example: Select user from dual;

Output

user

SCOTT

GROUP FUNCTIONS

A group function returns one result row based on a group of rows.

The following options are used most of the group functions.

DISTINCT: This option causes a group of function to consider only distinct values of the
argument expression.

ALL: This option causes a group of function to consider all values including duplicates.

AVG

SYNTAX AVG ([DISTINCT │ALL] n)

Purpose Returns average value of n.

Example SQL> Select AVG (cost_price) from item_master;

Output AVG(Cost_Price)

--------------------

2247.6667

COUNT

SYNTAX AVG ({│ [DISTINCT │ALL] expr})

Purpose Returns the number of rows returned by the query.

Example SQL> Select COUNT (Client_name) “No. of clients” from client_master;

44
Output No. of Clients

--------------------

MAX
MAX ([DISTINCT │ALL] expr)
SYNTAX

Purpose Returns maximum value of expr

Example SQL> Select MAX (cost_price) from item_master;

Output MAX(Cost_Price)

--------------------

5500

MIN
MIN ([DISTINCT │ALL] expr)
SYNTAX

Purpose Returns maximum value of expr

Example SQL> Select MAX (cost_price) from item_master;

Output MIN(Cost_Price)

--------------------

195

STDDEV
STDDEV ([DISTINCT │ALL] X)
SYNTAX

Purpose Returns Standard deviation of x.

Example SQL> Select STDDEV(cost_price) from item_master;

Output STDDEV(Cost_Price)

--------------------

1966.9609

SUM

SYNTAX SUM ([DISTINCT │ALL] n)

Purpose Returns sum value of n.

Example SQL> Select SUM (cost_price) from item_master;

45
Output SUM (Cost_Price)

--------------------

33715

UNIT – III

Joins

A join is a query that combines rows from two or more tables and views oracle performs a
joint whenever multiple tables appear in the query from CLAUSE.

Join Conditions

Most join query’s contains where clause conditions that combine two columns, each from a
different table such a condition is called a joint conditions.

Equi Joins

Equi joins is a join with a join conditions containing an equality operator. An equi joins
combines rows that have equivalent values for the specified columns.

Example

Select * from emp;

EMP_No Name Job Dept


1 Ratha Accountant 10
2 Sudha Computer operator 20
3 Manju Sales representative 30
4 Mala Purchase manager 40

Select * from dept;

D_N DNAME
O
10 Accounts dept
20 Computer dept
30 Sales dept
40 Purchase dept

Select name, job, dept, dno , dname from emp, dept where emp.dept= dept.dno

Nam Job D.No DName


e
1 Ratha Accounts 10
2 Sudha Compute 20
r

46
3 Manju Sales 30
4 Mala Purchase 40

Self Joins

A Self join is a join of a table itself. This table appears twice in the from clause and is
followed by table aliases that qualified column name in the join condition. To perform a self join,
oracle combines and returns rows of the table that satisfy the join condition.

Example

Select E1.Name || ‘works for’|| E2.Name “Employees and their Managers” from emp.E1,
emp.E2 where E1.Manager = E2.Emp_name

Output

Employees and their Managers

Babu works for siva

Constructing an English sentence with data from table columns

The concatenation operator (||) is used to construct an English sentence with the table data.

Example

Select Name || ‘is working as a ’|| Job “English Sentence” from emp;

English Sentence

Babu is working as a Clerk.

Siva is working as a clerk.

Sub Query

A sub query is a form of an SQL statement that appears inside another SQL Statement. A sub
query may contain another sub query. The statement containing a sub query is called a parent
statement.

Uses of Sub query

 To create a table from another table including the record.


 To insert records to a table from an existing table.
 To update records in a table.

Example

47
SQL> Create table emp14 (name, job) as select ename, job from emp13;

Output

Name Job

Vasanth clerk

Jayanth Manager

Suba Accountant

Sankari Sales man

Set Operators

Set operators are used to combine the result of two component queries into a single result.
Queries containing set operators are called compound queries.

The following lists are the SQL Set operators.

Operator Returns
s
Union All rows selected by either query without duplicates.
Union All All rows selected by either query, including all duplicates.
Intersect All distinct rows selected by both queries.
Minus All distinct rows selected by the first query but not by the second query.

Example

Select name from emp14;

Vasanth

Jayanth

Suba

Sankari

Select name from emp15;

Suba

Sumathi

Kalees

Vasanth

Union

48
SQL> Select name from emp14 union select name from emp15;

Vasanth

Jayanth

Suba

Sankari

Sumathi

Kalees

Union All

SQL> Select name from emp14 union all select name from emp15;

Vasanth

Jayanth

Suba

Sankari

Vasanth

Jayanth

Suba

Sankari

Sumathi

Kalees

Intersect

SQL> Select name from emp14 intersect select name from emp15;

Vasanth

Suba

Minus

SQL> Select name from emp14 minus select name from emp15;

Jayanth

Sankari

49
Indexes

An index is an ordered list of all values of a column or group of column in a table. It enables
oracle to find data stored within the table quickly. Oracle can use indexes to improve
performance.

 When searching for rows with specified index column values.


 Accessing tables in index column order.

An index created on the single column of a table is called simple index. When multiple columns
are included in the index is called composite index. An index can combine a maximum of 32
columns. The column included in the index can have duplicate values.

Syntax

Create index index file name on table name (column[, column]…]);

Example

SQL> Create index emp_index on emp14 (name);

Creating an unique index

The unique keyword is used to create a unique index which avoides duplicate when the user
defines a primary key or a unique key constraint. Oracle automatically creates unique indexes on
the primary key column or unique key column.

Example

SQL> Create unique index uni_index on mark (reg_no, name);

Dropping indexes

Drop index is used to remove an index from the database.

Example

SQL> Drop index reg_index;

Creating Views

A view is a logical table that allows us to access data from other tables a view itself contains
no data. The table upon which a view is based are called based tables.

Syntax

SQL> Create view view_name as select column, column from table name [ where condition];

Example

Create view emp_view as select emp_no, emp_name from employee

Output

50
Emp_n Emp_name
o
1 Kalai
2 Kannan
3 Murugan
4 Sathya

Renaming the columns of a view

For getting meaning ful column names we can re_name columns of a view during creating
the view.

Example

Create st_view (student_name, VB, Oracle, Networks, total, result) as select (Name, Mark1, Mark2,
Mark3, Total , Result) from student;

Student_name VB Oracle Networks Total Result

Kavitha 85 88 95 178 Pass

Mala 92 93 90 275 Pass

Destroying View

Drop view command is used to destroying view.

Syntax

Drop view view_name;

Example

SQL> Drop view student_view;

Update Views

Views are also used for data manipulation we can perform insert, update, delete operations
in the view. These views are called updatable views.

The modifications maid on the view also affects the base table, to become an updatable
view, it should meet the following conditions.

1. The view must be created on a single table.


2. The primary key of the table should be included in the view.
3. The view should not contain any group functions.

Sequences

51
Most of the application require automatic generation of integer numbers to avoid duplicates
and missing entries. For example A student table requires the automatic generation of registered
number.

In such situations, we can use the sequence command to generate sequence numbers oracle
provides on automatic sequence generator of numeric values which can have a maximum value of
up to 38 digits.

Features of Sequences

1. Sequences are used to generate numbers either in ascending or descending order.


2. They provide regular interval between numbers.
3. They can be restarted after reaching the maximum value specified.

Creating Sequence

Syntax

Create sequence sequence _name [increment by integer_value] start with integer value max value
integer_value [no max value] min value integers_value [ no min value] cycle/ no cycle

Keywords and Parameters

Sequence name It is the name of the sequence to be created.


Increment by Specify the interval between sequence numbers. This integer value default
number is one.
Start with Specify the 1st sequence number to be generated.
Max value Specify the maximum value the sequence can generate.
No Max value Specify the no limit for the maximum value.
Min value Specify the sequences minimum value.
No Min Value Specify no limit for the minimum value. Default is one for ascending
sequence.
Cycle Specifies that sequence continuous to generate values after reaching either
its maximum or minimum value.
No cycle Specifies that the sequence cannot generate more values after reaching its
maximum or minimum value.

Example

Create reg_sequence increment by 1 start with 10901 max value 11000 minimum value 1 cycle

Referencing sequence

Once a sequence is created we can access its value in SQL Statement with the following

CURRVAL – Returns the current value of the sequence.

NEXTVAL – Increments the sequence and returns the value.

52
Example

Select reg.seq nextval from dual;

Altering a sequence

The sequence can be altered using the alter sequence command. The sequence can be
altered by Changing the increment between further sequence valueSetting or eliminating the
minimum or maximum value.

Syntax

Alter sequence reg_sequence name [incrementby integer_value max value integer_value no max
value] min value integer value [no min value] cycle/ no cycle

Dropping a sequence

A sequence can be dropped by using the drop sequence command.

Syntax

Drop sequence sequence_name;

Example

Drop sequence reg_sequence name;

Permissions

Creating an user

The oracle has a user called system with the manager is the password that has all privileges
against the oracle objects. From the system user, we can create our own uses. First logon to the
system user and then give the command to create a new user.

Syntax

Create user username identified by password;

Example

Create user mop identified by III year;

Logon to an user from another user

The connect command is used to logon to a user from another user.

Syntax

Connect user name password;

Example

53
Connect system/manager;

Granting permission for the objects created by the user

Now the user mop has no privileges to logon. So we cannot logon to the user mop though it
was created. To logon to the newly created user, we must give some privileges to the user. The
privilegs are of two types. They are

 System Privileges
 Object Privileges

System Privileges

These privileges are granted to the newly created user to execute DDL Commands such as
create table, create view, create sequence etc. Grant command is used to give system privileges to
the user.

Syntax

Grant system privileges to user name;

Example

Grant system privilege to mop;

Some of the system privileges are

Create session To logon to the user


Create table To create a table
Create sequence To create sequence
Create To create a procedure
procedure
Create Trigger To create a trigger
Create view To create view

Example

Grant create session to mop;

Grant create table to mop;

Grant create sequence to mop;

Grant create view to mop;

Object privileges

Object privileges are granted by one user to another user for accessing the objects available
in the current user.

Syntax

54
Grant object privileges on object name to user name [with grant option]

The object privilege are

Alter Allows the grantee to change by uisng the alter table command
Session
Delete Allows the grantee to delete the rows from the table by using delete command.
Insert Allows the user to add records to the table using insert command.
Select Allows the grantee to query the table using the select command.
update Allows the grantee to update the contents of the table using update.
All Allows the grantee to perform all the above mentioned operations.

With grant option

The with grant options allows the grantee to grant object privileges to other user.

Example

Create an user name computer

Steps:

Logon to the user system with the password manager.

Create the new user by typing the following command.

Create user computer identified by comp;

Now the user computer is created with no privileges. Then give the privileges to the user computer
as given below.

Grant connect, resource to computer;

The resource privileges gives all privileges to the user computer.

Logon to the user computer

Type the following command to logon to the user computer.

Connect computer/comp;

Creating tables in the user computer

Create some table, views in the user computer. Create the tables student and marks in the
user. Creating another user in named Mop, grant system privileges and creating some objects.
Create some tables, views in the user Mop. Create the EMP and Department tables in this user.

 Granting permission to access objects in one user from another user.


 Now we have to user Computer and Mop
 Give permissions to access the objects of computer to user to Mop user.
 Give permissions to access the student table to the user Mop using the following command.

55
 Grant select insert on student to mop;
 Referencing a table belonging to another user
 If the user gives some of the object privileges to another user, then the grantee can refer
thus objects by mentioning the object name preceded by the name of the owner of the
object.

Example

We already gave permissions to access the table student of the user computer to the user
mop now access the table from the user Mop

 First logon to the user Mop


 Then referred the student table as below
 Select * from computer. Student;
 Granting permissions to the users when the Grantor has been given grant permission
 The grantor can give all privileges to another user. If the grantee wants to grant privileges
which are granted to him he must get permissions from the owner of the objects on those
objects with the WITH GRANT OPTION;
 Then only he can grant privileges to another user.

Example

Grant select on Mark to Mop;

WITH GRANT OPTION

Now the user mop can give the privileges of the mark table to another user.

Revoking the permissions

Permissions once given can be withdrawn by the grantor use the revoke command.

Syntax

Revoke object privileges on object name from user name;

Example

Revoke select, insert on student from mop;

Locks

Oracle automatically uses different types of locks to control concurrent access to data. When
a transaction begins, oracle automatically locks the required resource on behalf of that
transaction. This prevents other transaction to access the same resource.

Example

56
One user tries to update a row where as another user tries to delete the same row. Here
both transactions require the same resource. To overcome this situation Oracle provides a
locking facility.

Types of Locks

Locks can be acquired at two different levels. They are

 Row Level Lock


 Table Level Lock

Row Level Lock

In the row level lock, a row is selected exclusively so that other users cannot modify the row
until the transaction holding the lock is committed or rolled back.

The select statement with the ‘for update’ clause places an exclusive lock on the row or set of
rows retrieved by the query.

Example

SQL> Select * from purchase_details where purchase_no = 1005 for update of discount;

Table level lock

Table level lock is essential to maintain data integrity, when data is being accessed by
multiple users concurrently. A table lock can be acquired in several modes. They are

 Share lock
 Share update lock
 Exclusive lock

Lock table command

The syntax for locking a table explicitly is

Lock table <table name> in <share or share update or exclusive mode>;

Share Lock

A share lock locks the table for the user allowing other users to query but not to insert,
update or delete rows in the table.

Example

SQL> Lock table sales_details in share mode;

Share update lock

57
A share update lock locks rows to be updated in a table.

Example

SQL> Lock table item_master in share update mode;

Exclusive Lock

Exclusive lock is most restrictive table level lock. When a table is locked exclusively by one
user, the other users can only query.

Example

SQL> Lock table sales_details in exclusive mode;

Releasing a Lock

A Lock can be released by issuing either commit or rollback.

Table Partition

A partitioned table consists of a number of pieces having the same logical attributes. Each
partition is stored in a different segment and has different physical attributes. They can be
stored in different table spaces. We can access and manipulate data in one partition even if
other partitions are not available.

Advantages of Table Partition

1. Table partition reduces the possibility of data corruption.


2. Backup and recovery of each partition can be done independently.
3. There is a reduction in the size of unit of failure.
4. Table partitioning provides supports for very large data bases.

Maintaining Partitions

The following operators are involved in maintaining partitions.

 Moving Partitions
 Adding Partitions
 Dropping Partitions

Moving Partitions

The Move Partitions clause is used in the Alter table command to move a table partition
from an active table space to a different table space in order to balance Input Output operations.

EXAMPLE

SQL> Alter table order_master move partition omp1 tablespace inventory;

Adding Partitions

58
We can add a be particular after the last partition in a table if the last partition is not
bounded by MAX VALUE. Alter table add partition statement is used to add the partition.

Example

SQL> Alter table order_master add partition omp3 values less than (‘0060’);

Dropping partitions

A table partition can also be dropped. The drop partition clause is used in the alter table to
drop a partition.

Example

SQL> Alter table order_master drop partition omp2;

Splitting Partitions

A table partition can be split into two partitions using the SPLIT PARTITION clause in the alter
table statement.

Example

SQL> Alter table order_master split partition omp3 at (‘0045’,) into (partition om_p11, partition
on_p12);

Exchanging Table partitions

The Exchange Partition clause is used to exchange the data segments between non-
partitioned table and the partition of partitioned table.

59
Unit-IV

PL/SQL

Introduction

PL/SQL refers to Procedural Language/Structural Query Language. With PL/SQL , we can use
SQL statements to manipulate Oracle data and flow-of-control statements to process the data.
Moreover, we can declare constants and variables define procedures and functions and trap runtime
errors. Through PL/SQL we can insert, delete, update and receive table data and we can also use
procedural techniques such as writing loops or branching to another block of code.

Performance of SQL

Without PL/SQL, Oracle can process SQL statements one at a time. Each SQL statement
results in another call to Oracle and higher performance overhead. With PL/SQL , an entire block of
statements can be sent to Oracle at one time. This can reduce communication between our
application and Oracle. We can use PL/SQL blocks and subprograms SQL statements before sending
them to Oracle for execution.

Performance Improvement

PL/SQL also improves performance by adding procedural processing power to Oracle tools.
Using PL/SQL, a tool can do any computation quickly and efficiently without calling on the Oracle
server. This saves time and reduces network traffic.

Portability

Applications with in PL/SQL are portable to any operating system and platform on which
Oracle runs. In other words, PL/SQL programs can run wherever Oracle can run. We need not tailor
them to each new environment. That means we can write portable libraries, which can be reused in
different environments.

Need for PL/SQL for Programmers

 PL/SQL is used to write procedural programs to access and manipulate the data in the tables.

 SQL’s data manipulation statements are used in PL/SQL to manipulate the table data.

 SQL’s transaction processing statements are used in PL/SQL to commit or roll back the

changes made to the table’s data.

 All SQL functions may be used in PL/SQL.

60
PL/SQL Executing Environment

Wherever the PL/SQL technology is required, the PL/SQL engine accepts any valid PL/SQL
block as input. The PL/SQL engine executes procedural statements in the block and SQL statements
are sent to the SQL statement executor in the Oracle RDBMS.

PL/SQL Engine

PL/SQL Procedural
PL/SQL Statement
BLOCK
BLOCK Procedural Executor

SQL

SQL Statement Executor

When the PL/SQL engine resides in the Oracle RDBMS, the RDBMS can process not only
single SQL statements but also the entire PL/SQL blocks. These blocks are sent to the PL/SQL engine,
where procedural statements are executed and SQL statements are sent to the SQL executor in the
RDBMS. Since the PL/SQL engine resides in the RDBMS, this is an efficient and quick operation.

PL/SQL syntax

PL/SQL also has its own character set, variables, literals and constants.

Character set

We write a PL/SQL program as lines of text using a specific set of characters. PL/SQL
character set includes-

 The upper case letters (A to Z).


 The lower case letters (a to z).
 The numerals (0 to 9).
 The special symbols : (),+,-,*,/, etc.,
The combination of characters is known as lexical unit.

Simple symbols used in PL/SQL block

(,),+,-,*,/,<,>,=,’,[,],;

61
Compound symbols

Compound symbols consist of more than one simple symbol.

**,<>,!=,~=,>=,<=,:=,

Literals

The values of the variables are called Literals.

Types of Literals

 Character Literals
 String Literals
 Numeric Literals
 Boolean Literals
Character Literals

The value of only one character is called character literal.

Month = ’m’;

Alpha Val = ’I’

String Literals

The literal which contains more than one character is called string literal.

Example

Name= ‘vasanth’;

City = ‘ madurai’;

Numeric Literals

The literals which contains numeric value, is called Numeric Literal.

Example

Age=12; Salary = 1000;

Boolean Literals

The Literals only store the values ‘TRUE’,’FALSE’ and ‘NULL’.

Example

Result_Pass_Fail:=’TRUE’;

Result_Pass_Fail:=’FALSE’;

62
Data types

A PL/SQL variable can be declared using any one of the Oracle data types. They are:

Number types

Number types allow us to store numeric data (integers, real numbers, and floating-point
numbers)

Binary Integer

Using this data type we can store signed integers in the range -2147483647 to 2147483647.
Result_Pass_Fail:=’TRUE’;

Number

Using this type we can store the NUMBER values or decimal values in fixed number of digits.

Example

Regno number(5);

Average number(5,2);

Character Types

CHAR

Using the CHAR data type, we can store fixed-length character data. We can store upto
2000 characters.

Example

Name char(30);

Word char(40);

Varchar2

Using this data type, we can store variable length character data. We can store 32,767
characters.

Long

Using this data type, we can store variable-length character strings. We can store up to
32760 characters.

Boolean

Using the Boolean data type, we can store either TRUE or FALSE.

63
Syntax

Variable_name Boolean;

Example

Selection BOOLEAN; Sex BOOLEAN;

DATE

Using this data type, we can store date/time values. The date is stored in the format ‘DD-
MON-YY’. The time is stored in the format ‘HH:MI:SS’. SYSDATE returns the current date and time.

Example

Birth_day DATE;

Issure_date DATE;

Variables

Variables in PL/SQL blocks are named variables. A variable name must begin with a character
and can be followed by a maximum of 29 other characters.

 Reserved words cannot be used as variable names unless enclosed with in double quotes.
Variable must be separated from each other by at least one space or by a punctuation mark.
 The case is insignificant when declaring variables. A space cannot be used in variable name.
 We declare a variable of any data type such as number, char, and date, Boolean etc.
 PL/SQL allow us to declare constants and variables in the declaration part, then use them in
SQL and procedural statements anywhere in the execution block.
Declaring variables

We declare the variables in two ways as follows:

 Using SQL data types.


 Using Existing table column’s data type.
 Using SQL data types
Syntax

Variable_name data type (size);

Example

DA number (5);

Using Existing table column’s data type

The % type attribute is used in the declaration of a variable when the variable’s attributes
must be picked up from a table column.

64
Syntax

Variable_name tablename.column%type;

Example

DA EMP_SALARY.DA%TYPE;

Assigning values to variables

we can assign values to a variables in two ways. They are:

using the assignment operator(:=)

We can use the assignment operator := to assign a value to a variable.

Example

Tax:=price*tax_rate;

Done:=FALSE;

Using the SELECT…INTO Statement

The SELECT…INTO Statement is used to assign the values retrieved from a table into
variables.

Example

Select sal*0.10 into bonus from emp where empno = emp_id;

Picking up a variable’s parameter from a table cell

% type attribute is used to define variables equivalent to the columns in an existing table.
Here we need not define the data type and its size. They are automatically taken from the table’s
cell. If we change the parameters of the table column, the variable’s parameters will change as well.

Example

DA EMP_SALARY.DA%TYPE;

Declaring Constants

Declaring constant is just like declaring a variable except that we must add the key word
CONSTANT and assign a value to the constant.

Pi CONSTANT NUMBER (5,2):=3.14;

Logical comparison in PL/SQL

65
Comparison Operators

Comparison Operators compare one value with another. The result of the comparison is
always TRUE OR FALSE.

Operators

= - Equal

<>- Not Equal

<= - Less than or equal

>= - Greater than

!= - Not Equal

Example

Salary >=5000

Name=’Pandi’

Logical Comparisons

AND, OR, NOT Operators are used for logical comparisons.

Example

Mark1>=40 and Mark2>=40

Dept=’Computer Technology’ or Dept=’civil engg’

Name=’pandi’ and salary >=5000

PL/SQL Block Structure

THE PL/SQL BLOCK

DECLARE

Declarations of memory variables used later.

BEGIN

SQL executable statements for manipulating table data

EXCEPTION

Codes to handle errors.

END;
66
Parts of PL/SQL Block Structure

 Declarative part
 Executable part
 Exception-handling part
1. Declaration Part
In this part, we declare the variables, cursors and constants. We use these variables in the
execution part. All the variables used in the execution part must be declared in this part. If we are
not using any variable in the execution part, then this part is not needed. In this case, it is optional.

2. Execution part
In this part, we write the actual executable code. This part must be present in the block. We
use any PL/SQL Statement in this part. Create, Connect, Revoke, DBA, Resource, Alter and Drop
commands cannot be used in PL/SQL.

3. Exception Part
This part is optional. If we want to recover any error during execution, this part is very
useful. This part is present in the execution block itself.

An identifier in the PL/SQL block

Identifiers are the names of the variables, constants, and cursors.

Example

Bonus:= salary*0.10—computer bonus

Here bonus and salary are identifiers.

Rules

 An identifier must be unique in the same block.


 We can define the same identifier in different blocks.
 If the same identifier is defined in more than one block, the inside identifier loses its value
outside the block.
Displaying user message on the screen

DBMS_OUTPUT.PUT_LINE () Function is used to display the variables and other messengers.


The messages we want to display must be given as argument to put_line. It accepts only one
argument. If we want to display the columns of two variables, then they must be concatenated using
||(pip line symbol) and should be passed to put_line.

Syntax

Dbms_output.put_line(argument);

Example

Dbms_output.put_line(‘My name is’ || name);

Dbms_output.put_line(‘The rate is’ || rate);

67
To display the messages, at first we must type the statement SET SERVEROUTPUT ON at the
SQL prompt. Server output is a SQL*PLUS environment parameter that displays the information
passed as a parameter to the put_line function.

Conditional Controls in PL/SQL

These control structure are used to execute the set of statements with specified condition.

Simple IF structure

Syntax

IF <Condition> THEN

…. Statement 1;

ELSE

… Statement 2;

END IF;

In the above structure, if the condition is TRUE then the statements between the IF
and ELSE are executed; otherwise the statements between the ELSE and ENDIF are executed.

Example

The following program is used to check whether the given number is greater than 100 or
not.

Declare

a number(3);

Begin

a:= &a;

if a< 100 then

Dbms_output.put_line (‘A is present between 1 and99’);

Else

Dbms_output.put_line (‘A is bigger than 100’);

ENDIF;

END;

68
IF…ELSE IF… END IF Structure

Syntax

If <condition> then

…. Statement 1;

Else if <condition> then

… Statement 2;

Else if <condition> then

… Statement 3;

Else

… Statement 4;

End If;

Nested If…THEN

IF <Condition> THEN

… Statement 1;

IF <Condition> THEN

… Statement 2;

ELSE

… Statement 3;

Else

… Statement 4;

End if;

Iterative Control

Iterative controls are used to execute the same set of statements up to a desired number of
times or until a specific condition is matched.

Syntax

LOOP

Executing Statements

END LOOP;

69
Example

Declare

Sum number;

i number;

Begin

Loop

Exit when i>100;

Sum:=Sum+I;

End Loop

Dbms_output.put_line (‘Sum up to 100 is || sum’);

While Loop

The While-loop statement is used to execute a set of statements whenever the conditions is
true. When the condition is false then controlgoes to the next statement after the END Loop.

Syntax

While <condition>

…sequence of statements;

End loop;

Example

Declare

n number:=&n;

c varchar2(20);

s varchar2(20);

L number;

Begin

c:=to_char(n);

L:=length(c);

While (I>0)

Loop

70
S=s ||substr(c,I,1);

L=L-1;

End Loop;

Dbms_output.put_line (‘The Reverse order is || s’);

End;

EXIT

This statement is used to terminate the loop without any condition.

EXIT-WHEN

This statement is used to terminate the loop with the condition.

Example

LOOP

EXIT WHEN I>10; -- exit loop if condition is true

End Loop;

FOR LOOP

This statement is used to execute a sequence of statements in a fixed number of times. For
identifying the number of times, a variable is used. This variable is called fixed variable. This variable
need not be declared.

Syntax

FOR variable IN [REVERSE] start_no_...last_no

LOOP

Statements

END LOOP;

Example

The following program prints the numbers from 1 to12.

71
Begin

FOR I 1..12

LOOP

Dbms_output.put_line (i);

END LOOP;

END;

Conditions

 The looping variable need not be declared.


 The looping variable’s should not be changed within the loop.

Sequential Control

The GOTO statement is used to alter the flow of the control to any part of the PL/SQL Block
with out any condition.

Syntax

GOTO label;

--- block statements;

<< label >>

Example

Declare

A number:=0;

Begin

Dbms_output.put_line (‘TNPT’);

<<st>>

Dbms_output.put_line (‘Welcome’);

If a=10 then

Goto end1;

Else

72
a:=a+1;

GOTO st;

<<end1>>

END;

Cursors

Processing of SQL statements in Oracle

Whenever a SQL Statement is executed, oracle performs the following tasks.

 Reserves and area in memory called private SQL area.


 Fills this area with the appropriate data.
 Processes the data in the memory area.
 Frees the memory area when the execution is completed.

Example

Select Name, Total, Result from student order total desc;

To execute the above table, Oracle will reserve an area in memory and fills it with the
records from student table. These records are then sorted in the descending order of Total and
displayed to the user. When all the records from the student table are displayed, Oracle will free the
memory area used for retrieving and sorting the data.

Definition

A cursor is a named work area in memory where oracle stores the data while executing the
current SQL statement. So we can store the data in the cursor and retrieve it when required while
executing in the PL/SQL Block.

Active set

The set of all data stored in a cursor is called the active data set.

Row pointer

Oracle maintains a row pointer for each row if the query returns multiple rows. Using this
row pointer we can locate a particular row in the active data set.

Use of Cursors in PL/SQL

We cannot use the select statement in the PL/SQL execution block. By using select… into we
can retrieve only one row at a time. Suppose if the query returns more than one row, it will give an
error message. To avoid this, we must use cursor to retrieve multiple rows and manipulate them.

73
Types of Cursors

There are two types of cursors. They are

 Implicit cursor
 Explicit cursor
Implicit cursor

Oracle automatically creates the cursor when the SQL statement is retrieving a single row.
This is called implicit cursor.

Explicit Cursor

Apart from implicit cursors, we can also define cursors of our own. If we declare a cursor
explicitly then it is called explicit cursor.

Need for explicit cursor

For queries that return more than one row, we can explicitly declare a cursor to process the
rows individually.

Explicit Cursor Management

Four steps are required to use an explicit cursor. They are:

 Declaring the cursor.


 Opening the cursor
 Fetching the record from the cursor
 Closing the cursor
Declaring the cursor

In PL/SQL, like any other variables, cursor must be declared in the declaration part.

Syntax

Cursor <cursor_name> is select [*col1, col2 …]from <table_name>[where <condition>][order by


column name];

Example

Declare

Cursor stu_cur IS SELECT name from student;

Opening the cursor

We must open the cursor before using it in the execution block using the open statement.

Syntax

Open <cursor_name>;

74
Example

Begin

Open stu_cur;

Fetching the record from the cursor

We can retrieve the records from the cursor one by one using the fetch statement. We can
also store the data into the SQL variables.

Syntax

Fetch <cursor_name>into var1, var2, …;

Example

Loop

Exit when stu_cur% not found;

Fetch stu_cur into cur_name;

Dbms_output.put_line(cur_name);

End loop;

Closing the cursor

After using the cursor, we must close the cursor in the execution part using the close
statement.

Syntax

Close <cursor_name>;

Example

Close stu_cur;

Example for cursor

Declare

Cursor stu_cur is select name from student;

Cur_name student.name%type;

Begin

Open stu_cur;

Loop

75
Exit when stu_cur %not found;

Fetch stu_cur in to cur_name;

Dbms_output.put_line(cur_name);

End loop

Close stu_cur;

End;

Cursor Attributes

Each cursor has four attributes

% FOUND

% IS OPEN

% NOT FOUND

% ROW COUNT

% FOUND

If a cursor returns a row from the table then this attribute returns TRUE, otherwise this
returns FALSE.

% IS OPEN

When a cursor is opened, this attribute returns TRUE. Otherwise, it returns FALSE.

% NOT FOUND

If a cursor does not have a row to return then this attribute returns TRUE, otherwise this
returns FALSE. This is very useful when we want to know whether data is present in the cursor or not
while fetching it.

Syntax

Cursor_name %not found

% row count

It returns the number of rows fetched from the cursor using FETCH statement.

Syntax

Cursor_name %row count

76
Procedures and Functions

Procedures and functions are named PL/SQL blocks that can take parameters and return
values from the block.

Procedures

A procedure is a subprogram that performs a specific action and accepts more than one
argument and returns more than one values.

Syntax

Create or replace procedure <procedure_name> [argument [IN|OUT | INOUT|],…])]IS

./*Variable Declarations

Begin

/* PL/SQL block*/

Exception

/*EXCEPTION BLOCK*/

END;

Keywords and Prameters

Keywords/ Description
Parameters
Create or Replace Creates a new Procedure
Procedure
Argument Variable used to input or retrieve values
In Specifies that value for the argument must be given when the procedure is
called.
OUT Specifies that a value is returned from the procedure using this variable.
INOUT Specifies that a value for the argument must be given and procedure can
return a value using the same variable.
Data type Data type of the argument. This is given without the width specification.

Parts of a Procedure

1. Declaration part
2. Executable part
3. Exception-handling part

77
1. Declaration part
In this part, we declare the variables, cursors and constants. We use these variables in the
execution part. All the variables used in the execution part must be declared in this part. If we are
not using any variable in the execution part, this part is not needed. In this case, it is optional.

2. Execution part
In this part, we write the actual executable code. This part must be present in the block. We
use any PL/SQL statement in this part.

3. Exception part
This part is optional. If we want to recover any error during execution, this part is very
useful. This part is present in the execution block itself.

Example

We can write a simple procedure to calculate the addition of the two numbers.

Create or Replace procedure add(no1 in number, no2 in number, result out number) is

Begin

Result:=no1+no2;

End;

Calling the Procedure

We can call the procedure using it’s name in any PL/SQL block or any other procedure or
function.

Syntax

Procdure_name (argument1, argument2 ,…);

The number of arguments at the time of calling must be equal to the number of arguments
in the procedure definition.

Example

Declare

Get number(5);

Begin

Add(12,12,get);

Dbms_output.put_line(get);

End;

78
Deleting stored procedures

The drop procedure statement is used to delete stored procedures.

Syntax

Drop procedure <procedure_name>;

Example

Drop procedure add;

Functions

A function is a subprogram that accepts more than one argument and returns only one
value.Procedures returns more than one value, but function returns only one value.

Functions returns the value using the Return Statement.

Syntax

Create or Replace function <function_name>[argument1 datatype, argument2 datatype…])]

Return datatype is

Declaration part

Begin

Executable part

Exception

Exception part

End;

Keywords and Parameters

Keywords/ Parameters Description


Create or Replace Creates a new function or replaces an existing function.
Function
Function name The name of the function
Argument1 datatype, The arguments declarations.
argument2 datatype…
RETURN data type It specifies the function value datatype.

79
Parts of a function

1. Declartion part
2. Execution part
3. Exception-handling part
Declaration part

In this part, we declare the variables, cursors and constants. We use these variables in the
execution part. All the variables used in the execution part must be declared in this part. If we are
not using any variable in the execution part, then part is not needed. In this case, it is optional.

Execution part

In this part, we write the actual executable code. This part must be present in the block. We
use any PL/SQL statement in this part.

Exception part

This part is optional. If we want to recover any error during execution, this part is very
useful. This part is present in the execution block itself.

Example 1

We can write a function to calculate the factorial value for the given number.

Create or replace function factorial (fact_no number) return number is

Fact_value number(7):=1;

Begin

For I in 1..fact_no

Loop

Fact_value:=fact_value*I;

End loop;

Return fact_value;

End;

Calling the function

We can call the function using it’s name in any PL/SQL block or any other procedure
function. We can also store the returned value to any other variable.

80
Example 1

Declare

Giv_var number(5):=12;

St_var number(7);

Begin

St_var:=factorial(giv_var);

Dbms_output.put_line(‘factorial of 12 is’ ||st_var);

Dbms_output.put_line(‘factorial of 10 is || factorial (10));

End;

Deleting the function

Drop function statement is used to delete a function.

Syntax

Drop function <function name>;

Example

Drop function factorial;

81
UNIT-V

E-COMMERCE

E-Commerce refers to the paperless exchange of business information using network based
technologies. In past, a consumer had ample time to go from store to store to locate a desired item,
followed by bargaining, placing an order and finally getting the supply. This entire process could
range from a few hours to weeks depending on the product, quantity, quality and source of
purchase. But the entire scenario has changed. Everything in today’s world is electronics whether it
is EDI (Electronic Data Interchange), EFT (Electronic Funds Transfer), E-cash (Electronic Cash), E-
Stamp (Electronic Stamp), E-Mail (Electronic Mail), E-Business (Electronic Business) and E-Commerce
(Electronic Commerce).

Electronic Commerce is a critical action tool for competitive business strategies in


international trade. Electronic Commerce encompasses the entire online process of developing,
marketing, selling, delivering, servicing and paying for products and services. The Internet’s Web
Browser and client/server architecture and networks of hypermedia databases on the World Wide
Web serve as the technology platform for electronic commerce among internetworked communities
of customers and business partners. Since communication through Internet and other online
services have become very popular and easy to operate traditional EC activities can now be
conducted with new participants on a global scale.

Electronic Commerce uses the Internet Intranet and Extranets to accomplish online
transactions with customers and business partners. EC means different things to different people.
To some it may mean transfer of standardized & structured information between firms i.e., EDI
(Electronic Data Interchange). To others it may mean shopping on the internet and to still others it
may mean tracking & tracing the course of action through its journey in the value chain.

Meaning of E-Commerce

E-Commerce refers to the paperless exchange of business information using network based
technologies.

Definition of E-Commerce

E-Commerce or Electronic Commerce, a subset of E-business, is the purchasing, selling, and


exchanging of goods and services over computer networks through which transactions or terms of
sale are performed electronically.

REASONS FOR THE GROWTH OF E-COMMERCE – WHY?

There have been a number of reasons, which have led to the growth of E-Commerce. A few
of them are:

1. Age of competition
2. Globalization of economy
3. Commercialization and Privatization of Internet
4. High labour cost and lesser available time
5. Higher volumes of sales at lower profits

82
6. Shorter product life cycles due to changes in technology
7. Faster communication of information over computer networks the reducing distances
world wide as a result of emergence of a new field information.
Features of E-Commerce

The following are the features of E-Commerce.

 Ubiquity
 Global Reach
 Universal Standards
 Interactivity
 Information Density and Richness
 Personalization
Ubiquity

E-Commerce is ubiquitous, meaning that it is available just about everywhere at all times. It
liberates the market from being restricted to a physical space and makes it possible to shop from our
desktop. It reduces the consumer transaction costs.

Global Reach

E-Commerce technology permits commercial transactions to cross cultural and national


boundaries far more conveniently and effectively as compared to traditional commerce.

Universal Standards

The technical standards of the Internet and therefore the technical standards for conducting
E-Commerce are universal standards. They are shared by all the nations around the world.

Interactivity

E-Commerce technologies are interactive, meaning they allow for two-way communication
between merchants and consumer.

Information Density and Richness

E-Commerce technologies reduce information collection, storage, communication and


processing costs. At the same time, these technologies increase greatly the accuracy and timeliness
of information, making information more useful and important than ever.

Personalization

E-Commerce technologies permit personalization. Merchants can target their marketing


messages to specific individuals by adjusting the message to person’s name, interests and past
purchase. Merchants can change the product or service based on user’s preferences or prior
behavior.

83
IMPORTANCE OF E-COMMERCE

E-Commerce becomes popular because of the following:

1. Low Setup cost

Any body can easily set up a website. In fact there are many organizations and training
institutes who help customer is developing and launching websites. To market a product large
retail showrooms are not required, just a web site showing the characteristics of the product
including cost details are sufficient.

2. Global Free Market

Nobody can dominate the global market as presence on the internet is easy not only for
global giants, but even small organizations can participate actively at low costs and compete with
staff competition.

3. Global Access

Since more than 200 countries are hooked onto the Internet, anybody who can afford a TV
and a telephone can fully access the Internet and gain the information required.

4. Availability of Technology

Since the same technology like web servers, browsers, engines, internet, etc., is used
throughout the world therefore business can be easily conducted.

5. Multiple Opportunities

By using E-Commerce multiple activities like selling, renting, purchasing etc., can be
performed, In fact a whole variety of transactions can be provided all less than one roof.

OBJECTIVES OF E-COMMERCE
The objectives of E-Commerce can easily be understand with the help of the following table.

Streamline
Conduct Distant Business Use of Competitive Processes
Procurement Process

To acquire latest technologies and To cut down To decrease the length of


improvements in tech field procurement time Production cycle

To help expand horizon of business and To cut down To create competitive edge in
service procurement cost the respective fields

To create new services and businesses To simplify To improve and maintain


procurement process production quality.

84
TYPES OF E-COMMERCE
The following are the important types of E-Commerce

1. E-tailing or “Virtual storefronts” on Web sites with online catalogs, sometimes gathered into
a “virtual mail”.
2. The gathering and use of demographic data through Web contacts.
3. Electronic Data Interchange, the business-to- business exchange of data.
4. E-mail and fax and their use as media for reaching prospects and established customers (for
example, with newsletters).
5. Business to Consumer Commerce.
6. Business to Business Applications.
7. Consumer to Consumer Applications.
8. Internal Business Processes.
9. The security of business transactions.
1. E-TAILING OR THE VIRTUAL STOREFRONT AND THE VIRTUAL MAIL

As a place for direct retail shopping, with its 24-hour availability, a global reach, the ability to
interact and provide custom information and ordering, and multimedia prospects, the Web is rapidly
becoming a multibillion-dollar source of revenue for the world’s businesses. A number of businesses
already report considerable success.
2. MARKET RESEARCH

In early 1999, it was widely recognized that because of the interactive nature of the internet,
companies could gather data about prospects and customers in unprecedented amounts-through
site registration, questionnaires, and as part of taking orders. The issue of whether data was being
collected with the knowledge and permission of market subjects had been raised.
3. ELECTRONIC DATA INTERCHANGE (EDI)

Common business transaction, such as purchase orders and invoice, are often printed as
standard paper forms. When business information is available in standard format, we can transmit it
direct to our trading partner’s computer system for processing. This type of information
transmission is known as Electronic Data Interchange. EDI lets we replace conventional paper
documents with formatted, standardized business documents transmitted as electronic data.
The importance of EDI : Fist, today’s paper-based system for handling business –to-business
information exchange presents several problems. Second, a number of large firms are moving
rapidly to implement EDI and are sending the message that trading partners should be prepared to
do EDI or face the loss of relationships.

DRAWBACKS OF PAPER-BASED SYSTEM

Some of the problems with paper-based information systems are:

(a) Time delays: In a paper-based transaction systems, a number of delays occur along the
timeline. The first source is transportation delay, caused by the mail system or by other system
required to physically move paper documents between parties. The second source is manual
processing delay caused by the need to key and re-key information along the timeline. Delays in
transporting, billing, payment, poor customer service and poor management information can be
overcome by EDI.

(b) Labour Costs: In a paper-based system, manual processing is required for data keying,
document storage and retrieval, document matching envelop stuffing etc. EDI reduces these types
of paper costs.

85
(c) Errors: Because of the same information is keyed multiple times, paper-based system is
error-prone. The problem is effectively solved with EDI.

(d) Inventory: Because of delays and uncertainties in paper processing, inventory


management can effectively be made with EDI.

(e) Uncertainty: Uncertainty exists in three areas. First, transportation and keying delays
mean that timing is uncertain. Second, the sender does not know whether the transaction is
received at all or whether the firm agrees with what was sent in for that transaction. Third, in the
payment area, it is difficult to tell when a paper check will clear back to the disbursing bank.

ADVANTAGES OF EDI

(a) Ensures quick order processing: Since most purchasing transactions are routing, they can
be handled automatically, freeing staff for more demanding and less routine tasks.

(b) Make sales more easily: With EDI, quotes, estimates, order entry and invoicing can be
processed more smoothly and efficiently. Orders received electronically ensure that information is
available virtually immediately. So the business firms can respond faster and become more
competitive.

(c) Ensures quicker payments: Invoices received electronically can be reconciled


automatically and entered in the accounting department sooner. This helps the purchasing
department to negotiate better terms for faster payment.

(d) Minimise capitalities up in inventory: EDI helps the manufacturing organizations to


minimize the capital invested in inventory. That is the firms can effectively administer their
inventory levels and free from over investment in inventory.

(e) Quick and Easy Enquiries: Through EDI customers and suppliers make direct on line
enquiries on product availability, or other non sensitive information.

(f) Bulk updates to catalogues and part listings: The firms can provide updates of data files,
such as catalogues to customers or part listings to franchisees.
EDI is the exchange of business data using an understood data format. It predates today’s
Internet. EDI involves data exchange among parties that know each other well and make
arrangement for one-to-one (or point-to point) connection, usually dial-up.

4. E-MAIL, FAX AND INTERNET TELEPHONY

E-Commerce is also conducted through the more limited electronic forms of communication
called e-mail, facsimile or fax, and the emerging use of telephone calls over the Internet. Most of
this is business-to business, with some companies attempting to use e-mail and fax for unsolicited
ads (usually viewed as online junk mail or spam) to consumers and other business prospects. An
increasing number of business web sites offer e-mail newsletters for subscribers. A new trend is opt-
in-e-mail in which web users voluntarily sign up to receive e-mail, usually sponsored or containing
ads, about product categories or other subjects they are interested on.

86
5. BUSINESS TO CONSUMER COMMERCE

Formerly whatever was sold in the market, consumers had to buy but the scenario has
changed. Today the customers give their specifications and the manufacturers try and supply it. In
fact it is because of choosy customers, more and more variety has to be ordered. Therefore
business houses have to set up attractive electronic market places to entire the customers. Since
business houses may be remotely located and geographically spread over, they have the ability to
retain customers. Hence they have to optimize on factors like performance service efficiency,
personalization, socialization and offering of incentives. Some key factors which lead to the success
of electronic marketing are:

(a) Price attractiveness


Overpricing will not help to make sales eventhough an effective advertisement is given and
we can not force a customer to buy a particular product. Therefore offering discounts and value
added products are easier to trade using e-commerce.

(b) Attractive Web Sites


No consumer would like to wait while transactions are performed. The web site should be
attractive enough to hold the attention of the consumer by providing quick and easy access and user
friendly ordering processes with instant acknowledgement.

( c) Electronic Payment
Since e-commerce does not rely on money and local cheques, there are many services
introduced, which make payment easy.

i. Smart Card & Credit Services : Online credit card services have made payment,
procedures easy. Large amount of security standards have been improved so as to
make the system fool proof.

ii. Electronic Checks: This is an electronic version of paper cheques which, ensures that
instant clearing of checks takes place so that no `bounding back’ possibility occurs.

iii. Micro Payments: This is a service designed to support small payment/micro


payments for information products over WWW.

(d) Personalisation
Some web sites keep track of the path followed by a customer in his former trip. So when
he returns he is welcomed and guided on to those parts of the site he is attracted to. This makes a
customer more comfortable and encourages him for return visits. Also a list of priorities can be
made so that casual visitors, industrial customers and domestic consumers can be dealt with
separately and in different way.

(e) Socialising
There are chat and discussion groups available which let the customer know of the views of
people already using a specific product. This enabling him to have a feeling of belongingness to a
unique group of like minded individuals and thus helping to build up customer loyalty.

87
(f) Global Marketing
Setting up physical global distribution network and service centers will aid electronic
commerce because e-commerce can only provide information and transmit messages but physical
delivery is in the hands of business houses only.

(g) New technology products


Since awareness rate is high on e-commerce, product life cycles become short with the
arrival of new technology products. Launching of new products is faster using e-commerce as
advertising is instant and immediate success or failure is known quickly.

(h) Electronic catalogs


i. They help in providing more information or simple ways to find products. Two way
communication occurs in real time.
ii. Changes in prices, repackaging, re-channeling and other minor adjustments are
easily performed.
iii. We can go from one part to catalog to another directly and any term requiring
clarification can directly be dealt with first and then we can proceed sequentially.
iv. Global presence of small organization is felt at minimal cost on internet and other
online services.
(i) Convenience
Through e-commerce shopping can be done from anywhere at any time.

(j) Time Saving


Time lost in traveling to and fro the stores is saved. In fact if a consumer knows his
requirement
the entire process of ordering and payment takes a few seconds.

Shortcoming of On-line Shopping


i. Visual Effects only: The web site may display the product but the user can not feel, taste or
try the product.
ii. Time Lag: It is difficult to find out the actual time of the arrival of the product.
iii. Internet Connectivity: Technical delays due to heavy internet traffic may cause lots of delay
and problems.
iv. Slow Web Sites: Web sites using a lot of graphics and images take a lot of time to download
and is frustrating for the consumer as a lot of time is consumed.
v. Search Methods: The customer may not know all search methods, therefore a lot of time
may be wasted before the actual location is reached.
vi. Shipping and Handling Costs: Sometimes shipping and handling costs may be higher than
the cost of item purchased. Again if shipping costs are not known in advance then heavy
amounts may have to be paid at the time of delivery.

6. BUSINESS TO BUSINESS (INTER ORGANIZATIONAL E-COMMERCE)

Organization use e-commerce not only to interact better with their customers, for better
co-ordination within the organization but also for inter organization relationships. A few of
these business applications are:
i. Supplier Management
Here the main objective is to provide purchase managers with better control over
purchasing habits. The number of suppliers is reduced and business relationships are strengthened
thus making strong virtual teams leading to reduced processing costs and cycle time.
ii. Inventory Management

88
The purpose of e-commerce is lower the inventory levels by reducing cut of stock
circumstances and over stuffing of inventory. Again lead time is reduced so that the order-ship-bill
cycle is reduced.
iii. Channel Management
The use of open networks has enhanced inter business communication. No labour cost is
needed to obtain accurate information. Communication on the internet is multipoint and therefore
participants can limit themselves to their field of interest. This ensures channel management.
iv. Distribution Management
As a result of EDI purchase orders, bills, shipping notices all contain accurate and sufficient
data and are transmitted as shipping documents. This helps in distribution management.
v. Payment Management
Electronic payments ensure that payments can be made between suppliers and
organizations quickly thus reducing insecurities and processing costs.
vi. Financial Management
E-Commerce has enabled global companies to manage their money in various foreign
exchange accounts.

vii. Sales force Management


Communication and flow of information among the sales force, customer service divisions
etc., have improved considerably through e-commerce. This results into effective sales force
management.

7. CONSUMER TO CONSUMER APPLICATION

In consumer to consumer commerce, the seller may sell his service or goods by providing its
information on the net. This information may be evaluated by a consumer to carry out a
transaction. Similarly, the buyer may also give his requirements to select the desired services.

8. INTERNAL BUSINESS PROCESS OF INTRA-ORGANIZATIONAL E-COMMERCE


The purpose behind intra organizational e-commerce is to help a company maintain
relationships, which are critical to delivering superior customer services. Many internetworked
enterprises are customer driven and market driven. Therefore constant monitoring and evaluation
of data regarding customers, suppliers and competitors should be compiled from their web sites and
discussion groups. The feed back got is used to shape the organization’s strategies in term of
product design, advertising, customer services etc. E-commerce facilitates managers to
communicate using video conferencing, e-mail and bulletin board so that information is better
disseminated and right decisions can be made.

Today large corporate intranets have been installed so that information can be assessed and
published. On line publishing helps to reduce costs as printing and distributing and faster delivery of
current information takes place. Since information travels faster there is a better co-ordination
between the various departments. In fact all efforts are being made to convert organizations into a
paperless office.

9. THE SECURITY OF BUSINESS TRANSACTIONS


Security includes authenticating business transactions, controlling access to resources such
as web pages for registered or selected users, encrypting communications, and in general, ensuring
the privacy and effectiveness of transactions.

89

You might also like