Professional Documents
Culture Documents
Unit I
Unit I
Overview of RDBMS
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.
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 method verifies whether each record has fields containing all information as defined
using data definition.
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:
Student
Attributes
Address
Reg_no
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
Student 1
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 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:
In this model, the data relationship and contains are defined as a collection of idea tools.
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
II YEAR III YEAR II YEAR III YEAR I YEAR II YEAR III YEAR
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
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
Students table
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
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.
The RDBMS supports for null values (zero or space) to represent missing or inapplicable
information.
RDBMS keeps the description of database in the data dictionary to maintain database.
The rule is supporting for data definition, View definition and data manipulation.
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.
Application program is not dependent when any change is made in storage representation.
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.
The system can be able to manipulate the data that is distributed in other system.
This rule states that different levels of the languages cannot by no space pass the integrity
rules and constraints.
Relational RDBMS
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
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
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
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.
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.
Every database has the system table space. This table space is created automatically when we create
a database.
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
D:\inodbf\inu_temp.dbf ‘temporary’;
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.
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
Object based logical model are used in describing data at the logical and view levels. They
are many different models.
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
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 models are the predecessors are object oriented model. Interdependencies
among the entities can be express in this model.
Object, properties and their relationship are viewed uniformly are defined as functions in
this model.
a) Relational model
b) Network model
c) Hierarchical 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
Student 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
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
E-R relationship consists of a set of basic objects called entities and relationship among these
objects.
Basic concepts
Entity sets
Relationship sets
Attributes
Entity
An entity is an object, place, person are event that the system stores information about.
Example
Entity sets
It is a set of entity of the same type that share the same attributes.
Example
Attributes
13
Types of attributes
Simple Attributes
The attributes have been simple that is they are not divided into sub parts.
Composite Attributes
Example
Entity- Student
Student Name
All the attributes that we have specified have a single value for a particular entity.
Example
Reg_no
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.
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
If the relation has more than one key and each of the key is called candidate key.
Example
Entity Attributes
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.
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
Normalization
Relational Schemas
Example
15
Consider the relation sports shown in the table.
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
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
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
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.
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
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.
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
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.
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
Example
Syntax
NUMBER (P)
Where
Example
All types of time related information, including data and associated times can be
stored in a column declared with Date Data type.
Syntax
DATE
Example
Date_of_birth DATE
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
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
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
1. To create an object
2. To alter an structure of an object
3. To drop an object
The Data Definition Languages used for table definition are classified as
20
3. Truncate table command
4. Drop table command
1. Creating a table
Syntax
Example
SQL> Create table student (roll_no number(4), name varchar2(15), DOB DATE, address
varchar2(100));
2. Altering a table
The structure of a table can be changed using this command. Using this command
we can do the following.
Syntax
21
Example
Truncating a table
Syntax
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
Dropping a table
Syntax
Example
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:
-----------------------------------------------------------------------------------
Roll no number(4)
Name varchar2(25)
DOB DATE
Address varchar2(100)
-----------------------------------------------------------------------------------
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
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’);
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
As soon as the statement is executed, Oracle will prompt the user to enter values for all the
columns in the table.
Output
On successful execution of the command, the message “ 1 row will be created” will be
displayed.
Syntax
INSERT INTO <new table name> SELECT * (columnname1, columnname2 …..) FROM <old
table name>;
Example
SQL> INSERT INTO student1 select (name, regno, mark, course) from student;
Syntax
INSERT INTO <NEW TABLE NAME> SELECT (columnname1, columnname2….) FROM <old
table name>;
Example
SQL> INSERT INTO Student1 (name, regno, course) FROM student;
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.
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;
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;
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.
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
The above command will list name and regno of the student from the student table
for the course is equal to Bcom.
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.
Syntax
SELECT *FROM table name ORDER BY column name, column name, (sort order);
Example
SQL> SELECT * FROM student ORDER BY name;
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:
Syntax
UPDATE table name SET column name =expression, column name =expression;
Example
SQL> UPDATE student SET total=m1+m2+m3;
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.
The contents of the row for the student harish will be charged.
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.
Syntax
Example
SQL> DELETE FROM student;
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.
The above example will delete rows for the salary is less than Rs.5000.
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;
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
Example
INSERT…….
UPDATE……
DELETE…….
INSERT…..
29
DELETE…..
This will undo all changes made after the creation of the savepoint id1.
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.
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
Syntax
Example
30
2. Object Privilege
Revoke Command
Permissions granted to a user can also be taken by a Grantor. This can be done by
the revoke command.
Example
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.
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.
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));
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
31
Primary key as a table constraint
Example
Example
SQL> Create table dept (deptno number(2), dname varchar2(10), loc varchar2(10),
constraint unq_dname1 UNIQUE(dname));
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));
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.
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));
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
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
Queries
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
Oracle creates a new table hosteller exactly same as the table student_master
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;
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
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
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 >=
Example1
Example2
Logical Operators
Logical operators are used to combine two or more conditions. The value of a
condition is either true or false.
&
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.
SQL Functions can be widely classified into two groups. They are:
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
----------------
129.56
ii. CEIL
SYNTAX :
CEIL (n)
36
Purpose : Returns smallest integer greater than or equal to n .
----------------
135
iii. COS
SYNTAX :
COS (n)
--------------------------
0.70688321
iv. EXP
SYNTAX :
EXP (n)
-------------
148.41316
v. FLOOR
SYNTAX :
FLOOR (n)
-------------
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.
Output: LOG(10,1000)
-------------
vii. MOD
SYNTAX:
MOD(m,n)
Output: MOD(13,3)
-------------
viii. POWER
SYNTAX:
POWER(m,n)
Output: POWER(7,3)
-------------
343
ix. SQRT
SYNTAX:
SQRT (n)
38
Example: SQL> Select SQRT(25) from dual;
-------------
B. DATE FUNCTION
Date function accept date input and may return a value of date type.
i) ADD_MONTHS
SYNTAX :
ADD_MOMTH (d,n)
ii) Last_Day
SYNTAX LAST_DAY (d)
Purpose: Returns the date of the last day of the month that contains d.
iii) MONTHS_BETWEEN
SYNTAX
MONTHS_BETWEEN (d1, d2)
Purpose: Returns the number of months between d1 and d2.
iv) NEXT_DAY
SYNTAX NEXT_DAY (d,day_name)
Purpose: Returns the first date which is day name that comes after the date d.
v) SYSDATE
SYNTAX SYSDATE
39
EXAMPLE
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)
Example
SQL> SELECT INITCAP (‘WELCOME’) FROM dual;
OUTPUT: Welcome.
2. LOWER:
Syntax
LOWER(CHAR)
Example
SQL> SELECT LOWER (‘HARISH’) FROM dual;
Output: harish
3. UPPER:
40
Syntax
UPPER (CHAR)
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
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.
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
Output: CHANDRAN.
7. LENGTH:
Syntax
LENGTH(char)
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
Syntax
To_char (d [, fmt]
Purpose
Convert the date d to varchar2 data type, in the format specified by the date format
fmt.
Example
Output:
42
Sales_to_char (sales_date)
---------------------------------
S02 12-January-2012
S03 31-March-2012
Syntax
To_char(n[,fmt])
Purpose
Convert the number n to varchar2 data type using the optional number format fmt.
Example
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
Example
OUTPUT
43
UID
-----
22
2. USER
SYNTAX
USER
T
Purpose : Returns the current Oracle User.
Output
user
SCOTT
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
Output AVG(Cost_Price)
--------------------
2247.6667
COUNT
44
Output No. of Clients
--------------------
MAX
MAX ([DISTINCT │ALL] expr)
SYNTAX
Output MAX(Cost_Price)
--------------------
5500
MIN
MIN ([DISTINCT │ALL] expr)
SYNTAX
Output MIN(Cost_Price)
--------------------
195
STDDEV
STDDEV ([DISTINCT │ALL] X)
SYNTAX
Output STDDEV(Cost_Price)
--------------------
1966.9609
SUM
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
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
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
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
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.
Example
47
SQL> Create table emp14 (name, job) as select ename, job from emp13;
Output
Name Job
Vasanth clerk
Jayanth Manager
Suba Accountant
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.
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
Vasanth
Jayanth
Suba
Sankari
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.
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
Example
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
Dropping indexes
Example
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
Output
50
Emp_n Emp_name
o
1 Kalai
2 Kannan
3 Murugan
4 Sathya
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;
Destroying View
Syntax
Example
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.
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
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
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
52
Example
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
Syntax
Example
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
Example
Syntax
Example
53
Connect system/manager;
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
Example
Example
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]
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.
The with grant options allows the grantee to grant object privileges to other user.
Example
Steps:
Now the user computer is created with no privileges. Then give the privileges to the user computer
as given below.
Connect computer/comp;
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.
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
Example
Now the user mop can give the privileges of the mark table to another user.
Permissions once given can be withdrawn by the grantor use the revoke command.
Syntax
Example
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
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 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
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
57
A share update lock locks rows to be updated in a table.
Example
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
Releasing a Lock
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.
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
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
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);
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.
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
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
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-
(,),+,-,*,/,<,>,=,’,[,],;
61
Compound symbols
**,<>,!=,~=,>=,<=,:=,
Literals
Types of Literals
Character Literals
String Literals
Numeric Literals
Boolean Literals
Character Literals
Month = ’m’;
String Literals
The literal which contains more than one character is called string literal.
Example
Name= ‘vasanth’;
City = ‘ madurai’;
Numeric Literals
Example
Boolean Literals
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
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
Example
DA number (5);
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;
Example
Tax:=price*tax_rate;
Done:=FALSE;
The SELECT…INTO Statement is used to assign the values retrieved from a table into
variables.
Example
% 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.
65
Comparison Operators
Comparison Operators compare one value with another. The result of the comparison is
always TRUE OR FALSE.
Operators
= - Equal
!= - Not Equal
Example
Salary >=5000
Name=’Pandi’
Logical Comparisons
Example
DECLARE
BEGIN
EXCEPTION
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.
Example
Rules
Syntax
Dbms_output.put_line(argument);
Example
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.
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;
Else
ENDIF;
END;
68
IF…ELSE IF… END IF Structure
Syntax
If <condition> then
…. Statement 1;
… Statement 2;
… 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
Sum:=Sum+I;
End Loop
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;
End;
EXIT
EXIT-WHEN
Example
LOOP
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
LOOP
Statements
END LOOP;
Example
71
Begin
FOR I 1..12
LOOP
Dbms_output.put_line (i);
END LOOP;
END;
Conditions
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;
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
Example
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.
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
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.
For queries that return more than one row, we can explicitly declare a cursor to process the
rows individually.
In PL/SQL, like any other variables, cursor must be declared in the declaration part.
Syntax
Example
Declare
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;
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
Example
Loop
Dbms_output.put_line(cur_name);
End loop;
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;
Declare
Cur_name student.name%type;
Begin
Open stu_cur;
Loop
75
Exit when stu_cur %not found;
Dbms_output.put_line(cur_name);
End loop
Close stu_cur;
End;
Cursor 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
% row count
It returns the number of rows fetched from the cursor using FETCH statement.
Syntax
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
./*Variable Declarations
Begin
/* PL/SQL block*/
Exception
/*EXCEPTION BLOCK*/
END;
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;
We can call the procedure using it’s name in any PL/SQL block or any other procedure or
function.
Syntax
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
Syntax
Example
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.
Syntax
Return datatype is
Declaration part
Begin
Executable part
Exception
Exception part
End;
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.
Fact_value number(7):=1;
Begin
For I in 1..fact_no
Loop
Fact_value:=fact_value*I;
End loop;
Return fact_value;
End;
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);
End;
Syntax
Example
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 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
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
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
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.
Personalization
83
IMPORTANCE OF E-COMMERCE
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.
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 help expand horizon of business and To cut down To create competitive edge in
service procurement cost the respective fields
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.
(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.
(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.
(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.
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:
( 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.
(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.
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.
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.
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.
89