Sie sind auf Seite 1von 48

Oracle9i and Distributed Database Unit 2

Unit 2 SQL with Oracle9i Database


Structure
2.1 Introduction
2.2 Oracle9i SQL
2.3 SQL Standards
2.4 How SQL Works
2.5 Data Definition Language (DDL)
2.5.1 Create/Drop Statement
2.5.2 Create Table as, an Example
2.5.3 Command to alter a Table
2.5.4 Truncate
2.5.5 Constraints
2.5.6 Data Types
2.6 Data Manipulation Language (DML)
2.6.1 Insert Statement
2.6.2 Select Statement
2.6.3 Update Command
2.6.4 Delete Command
2.7 Operators in SQL *Plus
2.7.1 Arithmetic Operators
2.7.2 Comparison Operators
2.7.3 Logical Operators
2.8 SQL *Plus Functions
2.8.1 Single Row Functions
2.8.1.1 Date Functions
2.8.1.2 Character Functions

Sikkim Manipal University Page No.: 28


Oracle9i and Distributed Database Unit 2

2.8.1.3 Numeric Functions


2.8.1.4 Conversion Functions
2.8.1.5 Miscellaneous Functions
2.9 Summary
2.10 Exercises

2.1 Introduction
Before moving on to further details here below, let us glance at the
terminology that helps us through following points.
 The data dictionary is maintained by the database and contains all the
information on how data is stored in the database, where it is, and how
the database can work with it.
 DDL stands for data definition language. These are the SQL
statements that begins with create, revoke, grant and drop. These are
the statements that are used to create and remove the database
objects. They are also statements that are used to create permission to
access the database and database objects.
 DML (data manipulation language) are SQL statements that begin
with select, insert, delete, or update. These are statements used to
manipulate the contents of a database.
 Grants are privileges given out by owners of objects, allowing other
users to work with the owner's data. Grants fall into two categories:
object-level grants and system-level grants. Object-level grants give
users the ability to select, insert, update, or delete against a database
object like a table. Examples of system-level grants are giving a
database user the ability to connect to the database or permission to
create an object in the database.

Sikkim Manipal University Page No.: 29


Oracle9i and Distributed Database Unit 2

 An index is a minicopy of an Oracle table stored in a presorted manner.


Index entries for a table allow rapid access to the data within your
tables.
 Integrity constraints are business rules associated with the database.
For example, in order for a customer to exist, it must have a unique
customer ID.
 A synonym is an alternative name for an object within the database.
 A table is a database object that holds your data. Information about
every table is stored in the Oracle9i data dictionary; with this information,
Oracle allows you to maintain the data residing in your tables.
 Database triggers are programs that are stored in the database and are
triggered by certain events. Inserting a row of data into a table is an
example of an event that might cause a-trigger to execute.
 A view allows database users to see a customized selection of one or
more tables within the database. A view is created based on a SQL
statement stored within the database. When you access the view, the
stored SQL statement is executed and the results of that query are
made available to the user.
 A role is a group of privileges that are collected together and granted to
users. Once privileges are granted to a role, a user inherits the role's
privileges by becoming a member of that role.

2.2 Oracle9i SQL


Structured Query Language (SQL) is the foundation of an oracle database;
in fact it is the foundation of all relational databases. We can not insert a row
of data into an oracle database unless we have first issued some basic SQL
statement to create the underlying tables. SQL is the set of statements with
which all programs and users access data in an Oracle database.
Application programs and Oracle tools often allow users access to the

Sikkim Manipal University Page No.: 30


Oracle9i and Distributed Database Unit 2

database without using SQL directly, but these applications in turn must use
SQL when executing the user's request. This unit provides background
information on SQL as used by most database systems which covers the
following topics:
 How to log into (access SQL *plus)
 DDL and DML : Difference
 Basic format of every SELECT statement
 How to format retrieved data
 The most common set commands
 How to join tables

2.3 SQL Standards


Oracle Corporation strives to comply with industry-accepted standards and
participates actively in SQL standards committees. Industry-accepted
committees are the American National Standards Institute (ANSI) and the
International Standards Organization (ISO), which is affiliated with the
International Electrotechnical Commission (IEC). Both ANSI and the
ISO/IEC have accepted SQL as the standard language for relational
databases. When a new SQL standard is simultaneously published by these
organizations, the names of the standards conform to conventions used by
the organization, but the standards are technically identical.

2.4 How SQL Works


The strengths of SQL provide benefits for all types of users, including
application programmers, database administrators, managers, and end
users. Technically speaking, SQL is a data sublanguage. The purpose of
SQL is to provide an interface to a relational database such as Oracle, and
all SQL statements are instructions to the database. In this SQL differs from
general-purpose programming languages like C and BASIC.

Sikkim Manipal University Page No.: 31


Oracle9i and Distributed Database Unit 2

SQL provides statements for a variety of tasks, including:


 Querying data
 Inserting, updating, and deleting rows in a table
 Creating, replacing, altering, and dropping objects
 Controlling access to the database and its objects
 Guaranteeing database consistency and integrity

SQL unifies all of the preceding tasks in one consistent language.


To communicate with the database, SQL supports the following commands:
 Data Definition Language – create, alter, drop, grant and revoke
commands.
 Data Manipulation Language – insert, select, delete and update
commands.
 Transaction Control Language – commit, savepoint and rollback
commands.

2.5 Data Definition Language (DDL)


All SQL statement fall into one of the two categories: DDL and DML.DDL is
set of SQL Statements that define or delete database objects such as tables
or views. Examples of DDL are any SQL statements that begin with create,
alter and drop. Table 2.1 lists all the basic DDL statements.

Sikkim Manipal University Page No.: 32


Oracle9i and Distributed Database Unit 2

Command Description
alter procedure Recompiles a stored procedure
Adds a column, redefines a column or changes
alter table
storage allocation of the given table
alter table add constraint Adds a constraint to an existing table
create table Creates table
create index Creates an index
drop table Removes a table
drop index Removes an index
Grant Grants privileges or roles to a user or another role
Revoke Removes privileges from a user or database role
Table 2.1: Basic DDL clauses

2.5.1 Create/Drop Statement:


Each create table is preceded by a drop table command. We know that the
preceding drop statement will remove the table and all its contents. The
tables created in this script will be basis of the examples.
SQL> create table a
2 (colour (char 5));
Table created.
SQL> drop table b;
Table dropped;

Table
Table is the database object that gets loaded into an Oracle database must
be placed inside an Oracle table. In fact all the information needed by an
oracle database to manage itself is stored in a series of tables that are
commonly known as the data dictionary.

A table is made up of columns. Each column must be given a unique name


within that table and assigned a data type (such as varchar2, date or
number) with an associated width (which could be predetermined by the
data type as in date)

Sikkim Manipal University Page No.: 33


Oracle9i and Distributed Database Unit 2

Create table, an example


Create table <table name> (column definition 1, column definition 2...);
In a table,
 We should specify a unique column name.
 We should specify proper datatype along with its width.
 We can include 'Not null' condition when needed, by default it is 'Null'.

The following example illustrates how to create a table with pet_id, pet_kind,
pet_name as its column.

If the above command is executed successfully the message "table


created" is displayed.

The table name in the above example should adhere strictly to the following
norms:
 While naming a table the first letter should be an alphabet.
 Oracle9i reserved words cannot be used to name a table.
 Maximum length for a table name is 30 characters.
 Two different tables should not have the same name.
 Underscore, numerals and letters are allowed but not blank space and
single quotes.

Let’s take a look at an example table called PETS:

SQL> CREATE TABLE PETS (

2. PET_ID INTEGER PRIMARY KEY,

3. PET_KIND VARCHAR2(20) NOT NULL,

4. PET_NAME VARCHAR2(20);

SQL > /

Sikkim Manipal University Page No.: 34


Oracle9i and Distributed Database Unit 2

Table created
PETS has three columns associated with it. The first column is PET_ID,
which is of type integer. It has an integrity constraint of primary key
associated with it, which means that database will enforce the business rule
that each per ID must be unique with in this table. This means that no two
entries in the table PETS could share the same pet ID. If you attempted to
place a duplicate pet ID in the tables PETS, you would receive an error.

The next column is PET_KIND, which is of type varchar2 with a width of up


to 20 characters; the not null attribute means that whenever an entry is
made in the PETS table, it must contain a valid value for the PET_KIND
column.

The last column is PET_NAME, which is also of type varchar2 with a width
of up to 20 characters. Unlike PET_KIND column, whenever a row of data is
entered into PETS, an associated data entry is optional for the PET_NAME
column.

2.5.2 Create Table as, an Example:


A very useful feature within the Oracle9i database is the ability to create a
table based on an existing table. You can use this feature to create a quick
copy of the entire table or just a subsection. This is a great way to create a
test environment. Here is a very simple example of it in action:

SQL> CREATE TABLE mass_newhire


2 AS select * from newhire
3* where state_cd = 'MA'
SQL> /

Table created
SQL> create or replace type <type name> as object (column1 data
type, column2 data type, column3 datatype…) ;

Sikkim Manipal University Page No.: 35


Oracle9i and Distributed Database Unit 2

In the syntax that is given above, the 'create or replace' command is given
so that the type could be created or replaced. The keyword type precedes
the name of the type itself. Since the type is a database object the keyword
object follows it. Following this, the column names and the data types are
given in the order required by the user. This command is processed as a
PL/SQL statement and hence there will not be a semi-colon following the
SQL statement. Instead, a back slash is given.

Example
SQL> create or replace type address as object(add1 number(5),
add2 varchar2(10), add3 varchar2(5), add4 number(7));

Type created
The object types that are created could be made public. This type could be
used in other database objects such as tables, procedures etc. A row could
be inserted using the select command. The standard dot notation is used to
represent the data type that has been defined by the user. It is possible to
nest the user defined types i.e., a type can be enclosed within another type.

Example
SQL> create or replace type emp as object (eno number(2),
ename varchar2(10), eadd address) ;

2.5.3 Command to alter a Table:


So far we learnt how to create a table. After creating a table if the user feels
like adding a column or modify the existing column definition he can do so
by using the alter table command.

alter table <table name> modify (column definition... );

alter table <table name> add (column definition... );

Sikkim Manipal University Page No.: 36


Oracle9i and Distributed Database Unit 2

Alter table commands cater to the need of the following situations:


 When a user wants to add a new column.
 When a user wants to modify the existing column definition to change
the width of the datatype or datatype itself, if NOTNULL isn’t specified.
 To include or drop integrity constraints.

Example
SQL > alter table MITE modify (empno number(8));

The following example explains how to add a column of type long to the
customer table.

Example
SQL > alter table MITE add (remarks long);

When a table is created with a partition it can be altered to merge two


partitions or a single partition can be split into two. We can make use of the
alter table add partition to append a partition to a table. If a table is not
partitioned when it was created then the table cannot be partitioned using
the alter table command. The split partition clause can be used to add a
partition in the beginning of a table or in the middle.

An example to understand the above-mentioned concept of altering a table


to add a new partition.

Example
SQL> alter table MITE add partition p3 values less than ('r');

The example shows us how to alter a table to add a partition. When we add
a partition to a table we must remember that the partition can be added only
to the end of the table. In other words a partition can only be appended to
the table. If the last partition contained values that are less than the max
value then no other partition can be appended to the table. In such a case

Sikkim Manipal University Page No.: 37


Oracle9i and Distributed Database Unit 2

the split partition option can be used to insert a partition in the desired
position.

A split partition gives us the option of splitting a partition in two. It gives the
new partitions, new physical attributes and the older attributes are
discarded. An example with the split partition option explains this concept
clearly.

Example
SQL> alter table MITE split partition p1 at (‘c’) into (partition p1,
partition p3)

The example shows us how a single partition can be split into two with the
help of the split partition keyword. This gives us two partitions i.e., p1 and
p2. p1 contains values that are less than c and the partition p3 contains
values that are less than h.

A partition name can be renamed using the rename option. The rename
option works as shown below:

Example
SQL> alter table MITE rename partition p2 to par2;

The above statement shows us how we can rename the partition.

A partition can be altered to delete all rows from it. To delete all rows from a
partition we can use the truncate partition command along with the alter
table command.

The following example helps in a better understanding of the alter table


command with the truncate option & shows us how we can remove all rows
in a partition using the alter table command with the truncate option.

Example
SQL> alter table MITE truncate partition p1;

Sikkim Manipal University Page No.: 38


Oracle9i and Distributed Database Unit 2

2.5.4 Truncate:
The following command would delete all the records from the table.
Command to truncate a table is truncate table <table_name>;

Example
SQL > Truncate table MITE;
Implementation of this command would delete all the rows associated with
the table, only the structure of the table remains. The truncate command
deletes all rows from the specified table. An example gives a better
understanding of the concept.

Example
SQL > truncate table MITE reuse storage;

The above command deletes all rows from the table employee and reuses
any space that was occupied by the rows of the table employee.

Desc
If the user wants to view the structure of the table, the following Desc helps
to achieve the same. Command to view the table's structure is Desc <table
name>

Example
SQL > Desc MITE;

The above command will display the structure of the MITE table.

2.5.5 Constraints:
Constraints would be defined along with the columns in a table to avoid
invalid entries. For example, an organization maintaining details regarding
textbooks, purchase order and employee's name wants to secure these
informations, they can enforce data integrity on the related data objects.

Sikkim Manipal University Page No.: 39


Oracle9i and Distributed Database Unit 2

Integrity Constraints
An Integrity Constraint is a mechanism used by Oracle9i to prevent invalid
data entry into the table. It is nothing but enforcing rule for the columns in a
table. The various types of integrity constraints are explained below:

Domain integrity constraints


Maintains value according to the specifications like 'Not null' condition, so
that the user has to enter a value for the column on which it is specified.
'Not null' and 'Check' constraints fall under this category.

Not Null
Null is a column that contains no data. In other words, it contains nothing.
Null values have a way of getting into your database where you lease
expect them for example, in numeric columns. This creates a big problem
since 1+null=null. Null is not 0.

It is advisable to create primary key columns with the not null clause. This
makes it mandatory, before entering a row of data to specify a valid entry for
all the table columns so tagged. Or the database will refuse the record.

Example
SQL > create table IT (empno number(6) constraint eno Not Null, empname
varchar2(30));

where eno is the constraint name.

This command will ensure that the user enters a value for the empno
column on the IT table, failing which it returns an error message.

Check constraints
These are rules governed by logical expressions or Boolean expressions.
Check conditions cannot contain subqueries. The following example will
help us to understand it much better & creates a table IT_order with a check
constraint to restrict the values of ordid to be within 1000.

Sikkim Manipal University Page No.: 40


Oracle9i and Distributed Database Unit 2

Example
SQL > create table IT_order (ordid number(4) constraint checkit check
(ordid > 1000), orderdate date, commplan character(l), custid number(6),
shipdate date, total number (8, 2));

Entity integrity constraint


Maintains uniqueness in a record
An entity is any data recorded in a database. Each entity represents a table
and each row of a table represents an instance of that entity. To identify
each row in a table uniquely we need to use this constraint.

Unique Constraints
Usage of the unique key constraint is to prevent the duplication of values
within the rows of a specified column or a set of columns in a table.
Columns defined with this constraint can also allow Null values. If unique
key constraint is defined in more than one column, it is said to be
composite unique key. In the above case combination of columns cannot
be duplicated. Maximum combination of columns that s composite unique
key can contain is 16.

Example
SQL > create table ITT (id number(6), stdprice number(8,2), minprice
number(8,2), startdate date, enddate date constraint unidate unique);

The same constraint can be enforced using table level syntax also.

Example
SQL > create table IT (id number(6), stdprice number (8,2), enddate date,
startdate date, constraint unitab unique (enddate));

The above example prevents the duplication of values to be entered in


enddate column.

Sikkim Manipal University Page No.: 41


Oracle9i and Distributed Database Unit 2

Example
SQL > create table MITE(empid number(6),empname varchar2(30),
constraint compuni unique(empid, empname));

In this case combination of columns custid and name cannot be duplicated.

Primary key and foreign keys


We relate two or more tables together based on common fields. These
common fields are known as keys. There are two types of keys:
 A primary key is what a row of data unique within the table. In the
emptable table, state_id is the primary key.
 A foreign key is the primary key of one table that is stored inside another
table. The foreign key connects the two tables together.

We relate the two tables together in the where clause. Once we understand
what primary key is and what is foreign key, joining them becomes simple.
The foreign key is a direct road map to the source table.

This constraint avoids duplication of rows and does not allow Null values,
when enforced in a column or set of columns. As a result it is used to
identify a row. A table can have only one primary key. If a primary key
constraint is assigned to more than one column (i.e.) or combination of
columns it is said to be a composite primary key, which can contain a
maximum of 16 columns. Primary key constraint cannot be defined in an
alter table command when the table contains rows having Null values.

In below example, we are going to define primary key on a single column,


so we go for column level syntax.

Example
SQL > create table IT_customer (custid number(6) constraint prim_con
primary key, name varchar(45), address varchar2(30), city char(30), repid
number(4), creditlimit number(8,2));

Sikkim Manipal University Page No.: 42


Oracle9i and Distributed Database Unit 2

Example
SQL> create table ITT_item (itemid number(6), ordid number(6), prodid
number(6), actualprice number(8, 2), qty number(8,2), constraint prim_id
primary key(itemid));

This constraint ensures that no two itemid's in the table will have the same
values and that they do not contain Null values.

The example below illustrates composite primary key.

Example
SQL > alter table ITT_item add primary key (IT_order, orderdate) disable;

The above command ensures that no two rows in the table have a same
value for both IT_order and orderdate. Since the constraint is disabled it can
only be defined in the Oracle9i database dictionary but not enforced.

Referential integrity constraint


Enforces relationship between tables
One can either enable or disable a constraint. The former enforces the
constraint and the latter will not enforce the rule, even though the syntax
would remain as it is in the data dictionary. By default, the syntax would be
enabled. Further we can define a constraint either at table or column level. If
it is defined at the table level, then, it can be enforced to any number of
columns in a table. On the other hand, if it is defined at the column level
then, it holds good only for the column for which it is defined.

Referential Integrity Constraints


To establish a 'parent-child' or a 'master-detail' relationship between two
tables having a common column, we make use of referential integrity
constraints. To implement this, we should define the column in the parent
table as a primary key and the same column in the child table as a foreign
key referring to the corresponding parent entry.

Sikkim Manipal University Page No.: 43


Oracle9i and Distributed Database Unit 2

Example
SQL > create table T_order (IT_order number(4), orderdate date, commplan
character(1), shipdate date, total number(8,2), empid number(6), constraint
fk_empid foreign key (empid) references MITE(empid));

On delete cascade clause


If all the rows under the referenced key column in a parent table are deleted,
then all rows in the child table with dependent foreign key column will also
be deleted automatically.

Basic concepts related to referential integrity are:


 Foreign key: A column or combination of columns included in the
definition of referential integrity that would refer to a referenced key.
 Referenced key: It is a unique or a primary key, which is defined on a
column belonging to the parent table.
 Child table: This table depends upon the values present in the
referenced key of the parent table, which is referred, by a foreign key.
 Parent table: This table determines whether insertion or updation of
data can be done in child table. This table would be referred by child's
table foreign key.

Example
SQL > create table IT_order (order number(4), orderdate date, commplan
character(1), shipdate date, total number(8,2), empid number(6) constraint
fk_empid references IT_customer(empid));

The above command creates a table IT_order and will also enable a foreign
key on empid column, which would refer to the primary key on the empid
column of the IT_customer table. Before enabling this constraint, we ensure
that empid column of the customer table has been defined with either
unique key or primary key constraint. The foreign key constraint ensures

Sikkim Manipal University Page No.: 44


Oracle9i and Distributed Database Unit 2

that all values in the column empid in IT_order table have a corresponding
empid value in the IT_customer table.

The referential integrity constraint does not use foreign key keyword to
identify the columns that make up the foreign key, because the constraint is
defined at column level on custid column, the foreign key is automatically
enforced on the custid column.

We can define a referential integrity constraint using table level syntax also.
The example illustrates the same concept for better understanding.

Example
SQL > create table IT_order (order number(4), orderdate date, commplan
character(1), ship_date date, total number(8,2), empid number(6), constraint
fk_empid references IT_customer(empid) on delete cascade);

Foreign key keyword is an optional one and can be used for a more
understandable syntax and missing it doesn't cause any error. Because of
the on-delete-cascade option we find that deleting a particular empid value
from the IT_customer table, results in the deletion of the corresponding rows
from the order table also.

Referential integrity constraints with composite keys.

A composite foreign key can contain a maximum of 16 columns. It must


either refer to a composite unique key or a composite primary key. To
maintain referential integrity constraints with foreign keys, each row in the
child table must satisfy one of the conditions mentioned below.
 The value of atleast one of the columns which make up the foreign key
can be Null.
 The values of foreign key columns must match the values of referenced
key columns.

Sikkim Manipal University Page No.: 45


Oracle9i and Distributed Database Unit 2

In addition to the above options a defer constraint checking is possible in


Oracle9i. When a constraint is made deferrable, the Oracle9i leaves the
checking until the transaction is committed. Defer constraint checking is
exactly what it says – it can be used to defer the checking of constraints but
it cannot be used to defer trigger execution.

To support deferred checking of constraints, each constraint has two


additional attributes:
 It may be deferrable or not deferrable
 It may be initially deferred or initially immediate
Syntax
alter table <table name> add constraint <constraint name> foreign key
<column name> references <table name> deferrable initially deferred;
The above syntax when used will add a constraint which will by default only
is checked at commit time. The constraint and the fact that it is checked at
commit time are both encapsulated within the definition of the table. A user
with enough knowledge of the data dictionary can find out that the deferred
constraint exists, but code that manipulates the table, need not know about
the existence of this feature.

An option that could be used to set all constraints to deferred or enable all
constraints is available and has the following syntax:

Sikkim Manipal University Page No.: 46


Oracle9i and Distributed Database Unit 2

set constraints all immediate;


This enables all constraints.
To disable all constraints:

set constraints all deferred;


Oracle9i has an option to enforce a constraint rather than enable it.
Enforcement is applied to any future inserts and updates, but does not care
about data already in the table. The syntax is the following:
alter table <table name> enforce constraint <constraint name>;

2.5.6 Data Types


Each value manipulated by Oracle has a datatype. A value's datatype
associates a fixed set of properties with the value. These properties cause
Oracle to treat values of one datatype differently from values of another. For
example, we can add values of NUMBER datatype, but not values of RAW
datatype.

When we create a table or cluster, we must specify a datatype for each of its
columns. When we create a procedure or stored function, we must specify a
datatype for each of its arguments. These datatypes define the domain of
values that each column can contain or each argument can have. For
example, DATE columns cannot accept the value February 29 (except for a
leap year) or the values 2 or 'SHOE'. Each value subsequently placed in a
column assumes the column's datatype. For example, if we insert '01-JAN-
98' into a DATE column, then Oracle treats the '01-JAN-98' character string
as a DATE value after verifying that it translates to a valid date.

Oracle provides a number of built-in datatypes as well as several categories


for user-defined types that can be used as datatypes.

Sikkim Manipal University Page No.: 47


Oracle9i and Distributed Database Unit 2

Each data type has a set of rules associated with it, and the Oracle9i
database engine is designed to support those rules.
Data type Description
char(size) Stores fixed-length character data
varchar2(size) Stores variable length character data
number(l, d) Stores numeric data, where l stands for length and d stands
for number of decimal digits
Blob A binary large object the BLOB data type stores up to 4GB
of binary data(such as text, graphic images, video clips and
sound waveforms) in the database. Oracle recommends that
you always use LOB(BLOB,CLOB, NCLOB and BFILE) data
types rather than LONG data types.
Raw(size) Raw binary data the raw data type is variable length data
type like varchar2 character data type. It is intended for
binary data or byte strings such as graphics, sound
documents or array of binary data.
Date Stores dates
Long Stores variable – length character data column defined as
LONG can store variable character data containing up to
2GB of information. A table can obtain multiple LOB
columns but on one LONG column.

Number datatype
This datatype can store positive numbers, negative numbers, zeroes, fixed
point numbers, floating point numbers of magnitude ranging between
1.0 x 10 –130 to 9.9.9 x 10125 with a precision of 38.
Column_name number {p = 38, S = 0}
Column_name number (p) {fixed point}
Column_name number (p, s) {floating point}

Where p is the precision, which refers to the total number of digits, it varies
between 1 - 38; s is the scale, which refers to number of digits to the right of
the decimal point, which varies between -84 to 127.

Date datatype
Date datatype is used to store date and time in a table. Oracle9i database
makes use of its own format to store date in a fixed length of 7 bytes each
for century, month, day, year, hour, minute and second. Default date
Sikkim Manipal University Page No.: 48
Oracle9i and Distributed Database Unit 2

datatype is "dd-mon-yy". To view system's date and time we can use the
SQL function called sysdate(). Valid date is from Jan 1, 4712 BC to Dec 31,
4712 AD.

Raw (size)
Raw datatype is used to store byte oriented data like binary data or byte
strings and the maximum size of this datatype is 255 bytes. Only storage
and retrieval of data are possible, manipulations of data cannot be done.
Raw datatype can be indexed.

Long raw
Long datatype is used to store binary data of variable length, which can
have a maximum size of 2 GB. This datatype cannot be indexed.

User defined data types.

LOB
This is otherwise known as Large Object data types. This can store
unstructured information such as sound clips. Video files etc., up to
4 gigabytes in size. They allow efficient, random, piece-wise access to the
data. The LOB types store values, which are known as locators. These
locators store the location of the large objects. The location may be stored
out-of-line or in an external file. LOB values can be operated upon through
the use of the locators. To manipulate LOBs the DBMS_LOB package can
be used. LOBs can be either external or internal depending on their location
with regard to the database.

CLOB
A column with its data type as CLOB stores character objects with single
byte characters. It cannot contain character sets of varying widths. A table
can have multiple columns with its data type as CLOB.

Sikkim Manipal University Page No.: 49


Oracle9i and Distributed Database Unit 2

BLOB
A column with its data type as BLOB can store large binary objects such
as graphics, video clips and sound files. A table can have multiple columns
with BLOB as its data type.

BFILE
A BFILE column stores file pointers to LOBs managed by file systems
external to the database.

Literals
The terms literal and constant value are synonymous and refer to a fixed
data value. For example, 'JACK', 'BLUE ISLAND', and '101' are all character
literals; 5001 is a numeric literal. Character literals are enclosed in single
quotation marks, which enable Oracle to distinguish them from schema
object names.

Many SQL statements and functions require you to specify character and
numeric literal values. You can also specify literals as part of expressions
and conditions. You can specify character literals with the 'text’ notation,
national character literals with the N 'text' notation, and numeric literals with
the integer or number notation, depending on the context of the literal.

Text Literals
Text specifies a text or character literal. You must use this notation to
specify values whenever 'text' or char appear in expressions, conditions,
SQL functions, and SQL statements in other parts of this reference.
The syntax of text is as follows:

text:: =

Sikkim Manipal University Page No.: 50


Oracle9i and Distributed Database Unit 2

where
 N specifies representation of the literal using the national character set.
Text entered using this notation is translated into the national character
set by Oracle when used.

 c is any member of the user's character set, except a single quotation


mark (').

 ' ' are two single quotation marks that begin and end text literals. To
represent one single quotation mark within a literal, enter two single
quotation marks.

A text literal must be enclosed in single quotation marks. This reference


uses the terms text literal and character literal interchangeably.

Text literals have properties of both the CHAR and VARCHAR2


datatypes:

 Within expressions and conditions, Oracle treats text literals as though


they have the datatype CHAR by comparing them using blank-padded
comparison semantics.

 A text literal can have a maximum length of 4000 bytes.

Here are some valid text literals:


'Hello'
'ORACLE.dbs'
'Jackie's raincoat'
'09-MAR-98'
N'nchar literal'

Integer Literals
You must use the integer notation to specify an integer whenever integer
appears in expressions, conditions, SQL functions, and SQL statements
described in other parts of this reference.

Sikkim Manipal University Page No.: 51


Oracle9i and Distributed Database Unit 2

The syntax of integer is as follows:

integer::=

where digit is one of 0, 1, 2, 3, 4, 5, 6, 7, 8, 9.


An integer can store a maximum of 38 digits of precision.

Here are some valid integers:


7
+ 255

Number Literals
You must use the number notation to specify values whenever number
appears in expressions, conditions, SQL functions, and SQL statements in
other parts of this reference.

The syntax of number is as follows:

number::=

where
 + or - indicates a positive or negative value. If you omit the sign, then a
positive value is the default.
 digit is one of 0, 1, 2, 3, 4, 5, 6, 7, 8 or 9.

Sikkim Manipal University Page No.: 52


Oracle9i and Distributed Database Unit 2

 e or E indicates that the number is specified in scientific notation. The


digits after the E specify the exponent. The exponent can range from
130 to 125.

A number can store a maximum of 38 digits of precision.

If you have established a decimal character other than a period (.) with the
initialization parameter NLS_NUMERIC_CHARACTERS, then you must
specify numeric literals with 'text' notation. In such cases, Oracle
automatically converts the text literal to a numeric value.

For example, if the NLS_NUMERIC_CHARACTERS parameter specifies a


decimal character of comma, specify the number 5.123 as follows:
'5, 123'.

Here are some valid representations of number:


26 26e – 08
+ 6.54 – 20
0.5

Interval Literals
An interval literal specifies a period of time. You can specify these
differences in terms of years and months, or in terms of days, hours,
minutes, and seconds. Oracle supports two types of interval literals, YEAR
TO MONTH and DAY TO SECOND. Each type contains a leading field and
may contain a trailing field. The leading field defines the basic unit of date or
time being measured. The trailing field defines the smallest increment of the
basic unit being considered. For example, a YEAR TO MONTH interval
considers an interval of years to the nearest month. A DAY TO MINUTE
interval considers an interval of days to the nearest minute.

Sikkim Manipal University Page No.: 53


Oracle9i and Distributed Database Unit 2

If you have date data in numeric form, then you can use the
NUMTOYMINTERVAL or NUMTODSINTERVAL conversion function to
convert the numeric data into interval literals.

2.6 Data Manipulation Language (DML)


DML is any SQL statement that begins with select, insert, update or
delete.
 insert is used when you want to load data into the database.
 select is used when you want to retrieve data from an oracle database.
Any report you write always begins with select.
 update is used when you want to load data into the database.
 delete is used when you want to remove the contents of the table.

2.6.1 Insert statement:


Syntax
Insert into <table_name> values (a list of data values);
Here is an example of using the insert statement in its simplest form:
SQL> insert into mytable values(‘rama’, ‘HA’, ‘02-May-04’, ‘20000’);
1 row created.

SQL> insert into mytable values(‘seeta’, ‘TN’, ‘12-Nov-04’, ‘14000’);


1 row created.

SQL> insert into mytable values(‘rahul’, ‘MH’, ‘18-Jan-04’, ‘25000’);


1 row created.

SQL> insert into mytable values(‘rony’, ‘KA’, ‘25-Dec-04’, ‘60000’);


1 row created.

Each time the command is executed you receive the message “1 row
created”. When you load data into a table, you may also specify the column
to load it into. This ensures that there is no mistaking where you want the

Sikkim Manipal University Page No.: 54


Oracle9i and Distributed Database Unit 2

data to be places. In the next example, the columns are specified after the
insert command.

SQL> insert into state(state_id, state_name) values(‘MH’, “Maharastra”);


1 row created.

SQL> insert into state(state_id, state_name) values(‘MH’, “Maharastra”);


1 row created.

SQL> insert into state(state_id, state_name) values(‘KA’, “Karnataka”);


1 row created.

SQL> insert into state(state_id, state_name) values(‘TN’, “TamilNadu”);


1 row created.

Insert command with a query


We can use an insert command along with a query to select rows from one
table and insert them into another table. Only those columns and rows
selected by the query will be inserted.

The following example copies all the rows from order_info table to ord table,
provided a table named ord exists having the same structure as order_info.

Example
SQL > Insert into ord (select * from order_info);
But the structure of the table ord is the same as that of order_info.

Insertion of values into table with object types


To insert into a table that has data types defined by the user, use the type
name.

Sikkim Manipal University Page No.: 55


Oracle9i and Distributed Database Unit 2

2.6.2 Select statement:


The select statement is used to retrieve information from the database. It
has five components as described below :
Component Description
Select(mandatory) This tells oracle which information you want to receive.
Note that * means “retrieve all columns” from a table. It is
a great time-aver when doing quick select.
from(mandatory) This tells the database where to find the information. This
is the name of one or more oracle tables in which the data
is resides.
Where(mandatory) This is where you set any special condition(s) or selection
criteria that might restrict the data that is retrieved. It also
specifies how the contents of two tables are corrected
together.
Group by(optional) This tells the database how you want the data to be
summarized.
Order by(optional) This tells the database how you want the data to be
sorted. In a relational database, the data is not stored in a
presorted order. Although optional, it is a good rule of
thumb to include an order by clause in every select
statement.

SQL> select * from mytable;


rama HA 02-May-04 20000
seta TN 12-Nov-04 14000
rahul MH 18-Jan-04 25000
rony KA 25-Dec-04 60000

SQL>
Note the semicolons which signify that you have completed the given SQL
statement. In SQL *Plus there are two ways to signify that you have reached
the end of the SQL statement by
 the semicolon at the end of a line
 the slash on a separate line

Sikkim Manipal University Page No.: 56


Oracle9i and Distributed Database Unit 2

Let's take a look at the contents of the original table:

SQL> select * from newhire;

LNAME ST HIREDATE SALARY

Corey MA 01-jan -01 20000


Calisi NJ 10-jun-01 30000
Smith CA 15-aug-01 40000
Abby MA 12-dec-01 50000
Tony CT 12-nov-01 60000
Tom MA 08-may-01 70000

6 rows selected
Now let's take a look at the contents of the newly created MASS_NEWHIRE
table. Remember, this new table only contains entries from the state_cd =
'MA'.

SQL> select * from mass_newhire;

LNAME ST HIREDATE SALARY

Corey MA 01-jan -01 20000


Abby MA 12-dec-01 50000
Tom MA 08-may-01 70000

Selecting distinct rows


As we know how to select rows or specific columns from a table, let us go
about discussing, how to prevent the selection of duplicate rows. To prevent
the selection of duplicate rows, we include distinct clause in the select
command. The following example would eliminate duplicate values present
in 'repid' column of the customer table.

Example
SQL > select distinct repid from IT_customer;

Sikkim Manipal University Page No.: 57


Oracle9i and Distributed Database Unit 2

Unlike the other types of database, relational databases stores in no


predetermined order. With that in mind, when it’s important to present the
result in a particular order, use the order by clause.

There are two ways to use the order by clause


 By numbered position: specify a number of the ordered position you
want to sort on.
 By column name: name the particular column you want to sort on.

The only other decision you have to name is whether the named column is
retrieved in ascending or descending order. By default, you get ascending
order. This is done on column-by-column or number-by-number basis.
SQL> select state_id, lname, salary
2 from emptable
3* order by state_id desc, lname;

SQL>select state_id, lname, salary


2 from emptable
3* order by 1 desc, 2;

To restate the point, the order by clause determines how the results of the
query will be played back.

Alias
When a column which has a user defined data type is used we have to use
an alias name for the table from which the columns are being selected. After
the alias name we give the column name followed by the attribute from the
user-defined type. This retrieves a single row with two columns from the
database.
SQL > select eno, e.eadd.add1 from emp e;

An alias name is required because the compiler associates the variable


name with an address or memory location. This process is known as

Sikkim Manipal University Page No.: 58


Oracle9i and Distributed Database Unit 2

binding. This association lasts through all subsequent transactions until a


recompilation occurs.

Before binding all references must be resolved. This process is called name
resolution. All names are considered to be in the same namespace. One
declaration or definition in an inner scope can hide another in an outer
scope. Hence an alias name is required so that the exact data is retrieved
and displayed.

To retrieve specific rows from the table we have to use the 'where' clause as
mentioned before. In addition to this we have to use the dot notation if the
table contains user-defined types. We also should use an alias name. As
you see in the example will help in better understanding of the concept.

Example
SQL> select eno, e.eadd.add1 from emp e where e.eadd.add1 = 11;

2.6.3 Update Command:


Update command is used to alter the column values in a table. The update
command consists of a 'set' clause and an optional 'where' clause. The
syntax to the update command is given below :
Update table_name set field = value, …. Where condition;

In the above syntax, the 'where' clause and the 'set' clause can also include
queries. Update sets each field with the value that we supply, provided it
satisfies the 'where' condition. In the following example a query has been
included in the 'where' clause to select the rows which are to be updated.

In the following example the custid in the customer table is incremented by


one, if the same is present in the order_info table.

Example
SQL>Update item set actualprice = 150.50 where prodid in (select prodid
from product);

Sikkim Manipal University Page No.: 59


Oracle9i and Distributed Database Unit 2

With the update command one can update rows in the table. A single
column may be updated or more than one column could be updated.
Specific rows could be updated based on a specific condition. The following
example shows how to update tables that contain user defined data types.

Example
SQL > update employee set eadd = address (10, 'MITE', 576119 ) where
eno = 10;

The where clause allows updation of a single row.


To update tables that have user defined types and specific columns of the
type the dot notation is followed. Here also the table is given an alias name.

Example
SQL> update employee e set e.eadd.add2 = 'bgl' where e.eno = 10;
The above example shows us how we can update a table, which contains a
column, which has a user-defined type as its data type. It also shows how a
single column of the user defined type can be accessed and its value
changed. An alias for the table has to be used so that internal references
are resolved.

2.6.4 Delete Command:


After inserting rows in a table we can also delete them if required. The
delete command consists of a 'from clause' followed by an optional 'where
clause'.

delete from <table_name> where conditions;

To delete several rows from a table, select the rows with appropriate
conditions in a 'where' clause. The 'where' clause can also include a query.
The following example will delete a row from customer whose comm_type
is 'b'.

Example
SQL > delete from IT_customer where custid in (select custid from
order_info where commplan = 'b');

Sikkim Manipal University Page No.: 60


Oracle9i and Distributed Database Unit 2

The delete command allows deletion of rows from a table. A single row or
many rows could be deleted. Alternatively, all rows of a table could also be
deleted while the structure is maintained. To delete specific rows from a
table the 'where' clause is used in combination with the delete command.

To delete rows from a table that contains a user-defined type we have to


use the dot notation to identify the column and use an alias name for the
table to resolve the locations. An example helps in a better understanding of
the concept.

Example
SQL> delete from emp e where e.eadd.add1 = 10;
The above example shows how we can delete a specific row from a table
that has a user defined type.

2.7 Operators in SQL *Plus


The following are the operators supported by SQL *Plus:
 Arithmetic operators
 Comparison operators
 Logical operators

2.7.1 Arithmetic Operators:


To perform calculations based the number values, we include arithmetic
expressions in SQL command. An arithmetic expression consists of column
names with number datatype and an arithmetic operator connecting them.
The arithmetic operators are
 + (Addition)
 – (Subtraction)
 *(Multiplication)
 / (Division).

Sikkim Manipal University Page No.: 61


Oracle9i and Distributed Database Unit 2

Consider the following example.

Example
SQL> select prodid, stdprice, minprice, stdprice + minprice from price where
enddate = '4-jun-89';

We know that stdprice + minprice is not a column in the table price, yet
SQL *Plus would display it as a separate column. Arithmetic operations can
also be performed in a 'where clause’.

If there are several operators in an arithmetic expression then the


precedence of each operator must be known *and / have equal higher
precedence whereas + and – have equal lower precedence.

An example given below illustrates the precedence of operator.

Example
SQL > select ordid, itemid, 100 * (actualprice + qty) from IT_item
where prodid = 120;

In the above example, only after adding actual_price with qty it is multiplied
by 100. If parenthesis is omitted then multiplication will be performed first
followed by addition. Thus we can control the order of evaluation by using
parenthesis. We now move on to study about comparison operators.

2.7.2 Comparison Operators:


Comparison operators are used in conditions to compare one expression
with another. The comparison operators are =,! =, <, >, <=, >=, between (to
check between any two values), in (to match with any of the values in the
list), like (to match a character pattern) and is Null (to check whether it
is Null).

The last four operators mentioned above can also be used for checking the
NOT conditions like NOT BETWEEN, and so on. The following example
illustrates the comparison operator "greater than".
Sikkim Manipal University Page No.: 62
Oracle9i and Distributed Database Unit 2

Example
SQL > select * from EMP where sal > 5000;
The above example displays the rows for which the sal is greater than 5000.
An example discussed below is used to check for negations, (i.e. check for
NOT conditions).

Example
SQL > select * from order_info where not (custid = 2 or custid = 4);
The above command will display all columns where custid is neither 2 nor 4.
The IN operator can be used to select rows that match one of the values in
a list.

Example
SQL > select * from emp where sal in (5000, 7000);

The above example lists all the columns in a table for which salary lies in the
given list. When we search for character values using IN operator, the
column name must exactly match with the values present in the list. In the
case of LIKE operator, which is used to search a character pattern, we need
not know the exact character value. The LIKE operator recognizes special
characters like % and _. The former can match zero or more characters,
while the latter matches exactly one character. % cannot be used to match
a Null character.

Example
SQL > select name, address, city from IT_customer where name like 'S%';

The above command will display the columns name, address, city and
phone whose name begins with 'S'.

Example
SQL > select * from IT_customer where name like 'A_F';

The above command lists all the columns from customer table whose
names are three letters long, starting with 'A' and ending with 'F'.

Sikkim Manipal University Page No.: 63


Oracle9i and Distributed Database Unit 2

2.7.3 Logical Operators:


A logical operator is used to combine the results of two conditions to
produce a single result.
The logical operators are
 AND
 NOT
 OR

AND operator:
Example
SQL > select * from emp where sal >4000 AND deptno < 2;

And operator will display all the columns from EMP table provided both the
conditions mentioned below are satisfied.

We have now gone through the various operators supported by SQL *Plus.
Now let us have a look at the order in which these operators are evaluated.

Operator precedence
The precedence of the operators discussed above are given below: -
 Arithmetic operators ------------------- highest precedence
 Comparison operators
 NOT logic operator
 AND logic operator
 OR logic operator -----------------------lowest precedence

2.8 SQL *Plus Functions


This section deals with SQL *Plus functions. They are divided into single
row functions and group functions.

2.8.1 Single Row Functions:


Single row function or a scalar function returns only one value for every row
queried in table. Single row functions can appear in a select command and

Sikkim Manipal University Page No.: 64


Oracle9i and Distributed Database Unit 2

can also be included in a ‘where’ clause. The single row functions can be
broadly classified as:
 Date Functions
 Character functions
 Numeric function
 Conversion functions
 Miscellaneous functions.

The examples that follow mostly use the system table "dual". It is a table,
which is automatically created by Oracle9i along with the data dictionary.
Dual table has one column defined to be of varchar2 type and contains only
one row with value 'x'.

Example
SQL > select * from dual;

2.8.1.1 Date Functions:


They operate on date values producing output which also belongs to date
datatype, except for months_between date function which returns a number.
We shall discuss some of the most important date functions with examples.

Add_months
This date function returns a date after adding a specified date with the
specified number of months. The format is add_months(d,n), where d is the
date and n represents the number of months.

Example
SQL > select add_months(sysdate, 2) from dual;

The result will be '7-apr-99', if sysdate is '7-feb-99' .The sysdate variable will
display system date.

Last_day
The format is last_day(d), which returns the date corresponding to the last
day of the month.

Sikkim Manipal University Page No.: 65


Oracle9i and Distributed Database Unit 2

Example
SQL > select sysdate, last_day(sysdate) from dual;

The above command will display the system date and last day of the current
month.

Months_between
To find out the number of months between two dates, we use the
months_between function.

The format is months_between(d1, d2)

Where d1, d2 are dates. The following example returns the number of
months between two dates. The output will be a number.

Example
SQL > select months_between(to_date('1-5-99','dd-mm-yy'),
to_date ('1-3-99', 'dd-mm-yy')) "date" from dual;
The result will be 2.

Next_day
The format for this function is next_day(d,day)
Where d represents date and day implies any weekday. This function can
be illustrated with the following example.

Example
SQL > select next_day (sysdate, 'Wednesday') from dual;

Wednesday that immediately follows the sysdate will be displayed. If


sysdate is '7-feb- 99', then '13-feb-99' will be displayed which is the next
Tuesday.

Round
This function returns the date, which is rounded to the unit specified by the
format model. Its format is Round(d,[ fmt])

Sikkim Manipal University Page No.: 66


Oracle9i and Distributed Database Unit 2

Where d is the date and fmt is the format model. Fmt is only an option, by
default date will be rounded to the nearest day.

Example
SQL> select round (to_date('23-sept-98', 'dd-mon-yy'), 'year') from dual;
'1-jan-99' will be the result.

Example
SQL > select round (to_date('23-sept-98', 'dd-mon-yy'), 'month') from dual;
'01-oct-99' will be the result.

Example
SQL > select round (to_date('23-oct-98', 'dd-mon-yy'), 'day') from dual;
'20-oct-99' will be the result because it rounds '23-oct-99'.

Truncate
This function return the date with the time portion of the day truncated to the
unit specified by format model. The syntax is trunc(d,(fmt]). If fmt is
neglected, then date is converted to the nearest day.

Example
SQL > select trunc(to_date('23-oct-99', 'dd-mon-yy'), 'year') from dual;
'01-jan-99' will be the result.

Example
SQL > select trunc(to_date('23-oct-99', 'dd-mon-yy'), 'month') from dual;
‘01-oct-99' will be the result.

Example
SQL > select trunc(to_date('23-oct-99','dd-mon-yy'), 'day') from dual;
'20-oct-99' will be the result because it rounds '23-oct-99' to the nearest
Sunday.

Example
SQL > select trunc (to_date('23-oct-99', 'dd-mon-yy')) from dual;

Sikkim Manipal University Page No.: 67


Oracle9i and Distributed Database Unit 2

The above statement does not include fmt, and therefore it is rounded to
nearest day i.e. '23- oct-99'.

Greatest
The function is greatest(d1, d2,), where d1 and d2 are dates. This function
returns the last date present in the argument. Consider the following
example, which will display the date in the list.

Example
SQL> select greatest(to_date('2-7-88', 'dd-mm-yy'), to_date('7-4-99',
'dd-mm-yy')) from dual;
Output will be '7-apr-99'
Arithmetic operations on date values
We can perform arithmetic operations on date values which comprises
 date + number -------- adds number of days to date
 date – number --------subtracts number of days from date
 date – date --------- subtracts dates, producing number of days

Example
SQL> select ordid, shipdate + 15 from order_info where ordid =700;

2.8.1.2 Character Functions:


Character functions accept character input and return either character or
number values. i.e. character functions supported by Oracle9i are listed
below:
 string || string : || concatenates two strings
 ASCII(string): ASCII gives the ASCII value of the first character of a
string.
 CHR(integer): CHR gives the character with ASCII value equal to a
given positive integer.
 CONCAT(string1, string2): CONCAT concatenates two strings. It is
equivalent to ||.

Sikkim Manipal University Page No.: 68


Oracle9i and Distributed Database Unit 2

 INITCAP(string): This stands for INITial CAPital. It changes the first


letter of a word or series of words into uppercase.
 INSTR(string, set [, start [ ,occurrence ] ]): INSTR finds the location of
the beginning of a set of characters IN a string.
 LENGTH(string): This tells the LENGTH of a string.
 LOWER(string): LOWER converts every letter in a string to lowercase.

 LPAD(string, length [,'set']): LPAD stands for Left PAD. It makes a


string a specific length by adding a specified set of characters to the left.
 LTRIM(string [,'set']): LTRIM stands for Left TRIM. It trims all the
occurrences of any one of a set of characters off of the left side of a
string.
 NLS_INITCAP(string [,'NLS_SORT=sort']): NLS_INITCAP stands for
National Language Support Initial Capital. This version of INITCAP uses
the collating sequence sort to do the case conversion.
 NLS_LOWER(string [,'NLS_SORT=sort']): NLS_LOWER stands for
National Language Support Lower Case. This version of LOWER uses
the collating sequence sort to do the case conversion.
 NLS_UPPER(string [,'NLS_SORT=sort']): NLS_UPPER stands for
National Language Support Upper case. This version of UPPER uses
the collating sequence sort to do the case conversion.
 NLSSORT(string [,'NLS_SORT=sort']): Oracle uses National
Language Support SORT. This gives the collating sequence value of the
given string based on the collating sequence sort, or if omitted, the
National Language Support option chosen for the site.
 REPLACE(string, if [,then]): REPLACE returns string with every
occurrence of if replaced with then (zero or more characters). If no then
string is specified, then all occurrences of if are removed.

Sikkim Manipal University Page No.: 69


Oracle9i and Distributed Database Unit 2

 RPAD(string, length [,'set']): RPAD stands for Right PAD. It makes a


string a specific length by adding a specified set of characters to the
right.
 RTRIM(string [,'set']): RTRIM stands for Right TRIM. It trims all the
occurrences of any one of a set of characters off of the right side of a
string.
 SOUNDEX(string): SOUNDEX converts a string to a code value.
Names with similar sounds tend to have the same code value. You can
use SOUNDEX to compare names that might have small spelling
differences but are still the same.
 SUBSTR(string, start [,count]): SUBSTRing clips out a piece of a
string beginning at start position and counting for count characters from
start.
 TRANSLATE(string, if, then): This TRANSLATEs a string, character by
character, based on a positional matching of characters in the if string
with characters in the then string. See REPLACE.
 TRIM ( [{ { LEADING | TRAILING | BOTH } [trim_character] } |
trim_character } FROM ] trim_source ): TRIM removes all the
occurrences of any one of a set of characters off of the right side, left
side, or both sides of a string.
 UPPER(string): UPPER converts every letter in a string into upper
case.
 USERENV(option): USERENV returns information about the USER
ENVironment, usually for an audit trail. Options include 'ENTRYID',
'SESSIONID', and 'TERMINAL'. USERENV is still supported but has
been replaced by SYS_CONTEXT's UserEnv namespace.
 VSIZE(string): VSIZE gives the storage size of string in Oracle.

Sikkim Manipal University Page No.: 70


Oracle9i and Distributed Database Unit 2

2.8.1.3 Numeric Functions:


Numeric function accepts numeric input and returns numeric values as the
output. The values that the numeric functions return are accurate up to
38 decimal digits. The following tabular column will enlighten us on numeric
functions supported by Oracle9i.
Function Definition
Single-Value Functions
Value1 + value2 Addition
Value1 – value2 Subtraction
value1 * value2 Multiplication
value1 / value2 Division
ABS(value) Absolute value
ACOS(value) Arc COSine of value, in radians
ASIN(value) Arc SINe of value, in radians
ATAN(value) Arc TANgent of value, in radians
ATAN2 (value1, value2) ATAN2 returns the arc tangent of two values.
Input values are unbounded, outputs are
expressed in radians
BITAND (value1, value2) BITwise AND of value1 and value2, both of
which must resolve to nonnegative integers,
and returns an integer
CEIL(value) Numeric CEILing: the smallest integer larger
than or equal to value
COS(value) COSine of value
COSH(value) Hyperbolic COSine of value
EXP(value) e raised to value EXPonent
FLOOR(value) Largest integer smaller than or equal to value
LN(value) Natural Logarithm of value
LOG(value) Base 10 LOGarithm of value
MOD(value, divisor) MODulus NVL(value, substitute) substitute for
value if value is NULL
POWER(value, exponent) Value raised to an exponent POWER
ROUND(value, precision) ROUNDing of value
to precision
SIGN(value) 1 if value is positive, –1 if negative, 0 if zero
SIN(value) SINe of value

Sikkim Manipal University Page No.: 71


Oracle9i and Distributed Database Unit 2

SINH(value) Hyperbolic SINe of value


SQRT(value) SQuare RooT of value
TAN(value) TANgent of value
TANH(value) Hyperbolic TANgent of value
TRUNC(value, precision) Value TRUNCated to precision
VSIZE(value) Storage SIZE of value in Oracle
Group-Value Functions
AVG(value) AVeraGe of value for group of rows
CORR(value1, value2) Coefficient of CORRelation of a set of number
pairs
COUNT(value) COUNT of rows for column
COVAR_POP(value1, value2) POPulation COVARiance of a set of number
pairs
COVAR_SAMP(value1, value2) SAMPle COVARiance of a set of number
pairs
CUME_DIST(value) CUMulative DISTribution of a value in a group
of values
DENSE_RANK(value) Rank of a row in an ordered group of rows
FIRST(value) Analytic function performed on the row
ranking FIRST in a set
GROUP_ID(value) Distinguishes duplicate groups resulting from
a GROUP BY specification
GROUPING(expression) Used in conjunction with ROLLUP and CUBE
functions to detect NULLs
GROUPING_ID Returns a number corresponding to the
GROUPING bit vector associated with a row
LAST(value) Analytic function performed on the row
ranking LAST in a set
MAX(value) MAXimum of all values for group of rows
MIN(value) MINimum of all values for group of rows
PERCENTILE_CONT(value) Calculates the PERCENTILE ranking of a
value in a set assuming a CONTinuous linear
model
PERCENTILE_DISC(value) Calculates the PERCENTILE ranking of a
value in a set assuming a DISCrete
distribution model
PERCENT_RANK(value) Calculates the PERCENTILE ranking of a
value in a set

Sikkim Manipal University Page No.: 72


Oracle9i and Distributed Database Unit 2

RANK(value) Calculates the RANK of a value in a group of


values
STDDEV(value) STanDard DEViation of all values for group of
rows
STDDEV_POP(value) POPulation STanDard DEViation
STDDEV_SAMP(value) SAMPle STanDard DEViation
SUM(value) SUM of all values for group of rows
VAR_POP(value) POPulation VARiance
VAR_SAMP(value) SAMPle VARiance
VARIANCE(value) VARIANCE of all values for group of rows
List Functions
COALESCE(value1, value2, …) Returns the first non-NULL value in the
expression list
GREATEST(value1, value2, …) GREATEST value of a list
LEAST(value1, value2, …) LEAST value of a list

2.8.1.4 Conversion Functions:


ASCIISTR Translates a string in any character set and returns
an ASCII string in the database character set.
BIN_TO_NUM Converts a BINary value TO its NUMerical
equivalent.
CAST CASTs one built-in or collection type to another;
commonly used with nested
Tables and varying arrays
CHARTOROWID CHARacter TO ROW IDentifier. Changes a
character string to act like an internal Oracle row
identifier, or RowID.
COMPOSE Translates a string in any datatype to a unicode
string in its fully normalized form in the same
character set as the input.
CONVERT CONVERTs a character string from one national
language character set to another.
DECODE DECODEs a CHAR, VARCHAR2, or NUMBER into
any of several different
Character strings or NUMBERs, based on value.
This is a very powerful if- then, else function.
DECOMPOSE Translates a string in any datatype to a unicode
string after canonical decomposition in the same
character set as the input.

Sikkim Manipal University Page No.: 73


Oracle9i and Distributed Database Unit 2

HEXTORAW HEXadecimal TO RAW. Changes a character string


of hex numbers into Binary.
NUMTODSINTERVAL Converts a NUMber to an INTERVAL DAY TO
SECOND literal.
NUMTOYMINTERVAL Converts a NUMber to an INTERVAL YEAR TO
MONTH literal.
RAWTOHEX RAW TO HEXadecimal. Changes a string of binary
numbers to a character string of hex numbers.
RAWTONHEX RAW TO NHEX. Converts raw to an NVARCHAR2
character value containing its hexadecimal
equivalent.
ROWIDTOCHAR ROW Identifier TO CHARacter. Changes an internal
Oracle row identifier, or RowID, to a character
string.
ROWIDTONCHAR RAW TO NCHAR. Converts a RowID value to an
NVARCHAR2 datatype.
TO_CHAR TO CHARacter. Converts a NUMBER or DATE to a
character string.
TO_CLOB TO CLOB. Converts NCLOB values in a LOB
column or other character strings to CLOB values.
TO_DATE TO DATE. Converts a NUMBER, CHAR, or
VARCHAR2 to a DATE (an Oracle datatype).
TO_DSINTERVAL Converts a character string of CHAR, VARCHAR2,
NCHAR, or NVARCHAR2
Datatype to an INTERVAL DAY TO SECOND type.
TO_LOB TO LOB. Converts a LONG to a LOB as part of an
insert as select.
TO_MULTI_BYTE TO MULTI_BYTE. Converts the single-byte
characters in a character string to multibyte
characters.
TO_NCHAR TO NCHAR. Converts a character string, NUMBER,
or DATE from the database character set to the
national character set.
TO_NCLOB TO NCLOB. Converts CLOB values in a LOB
column or other character strings to NCLOB values.
TO_NUMBER TO NUMBER. Converts a CHAR or VARCHAR2 to
a number.
TO_SINGLE_BYTE TO SINGLE BYTE. Converts the multibyte
characters in a CHAR or VARCHAR2 to single
bytes.

Sikkim Manipal University Page No.: 74


Oracle9i and Distributed Database Unit 2

TO_YMINTERVAL Converts a character string of CHAR, VARCHAR2,


NCHAR, or NVARCHAR2
Datatype to an INTERVAL YEAR TO MONTH type.
TRANSLATE TRANSLATEs characters in a string into different
characters.
UNISTR Converts a string into unicode in the database
unicode character set.

2.8.1.5 Miscellaneous Functions:


UID UID returns an integer that uniquely identifies
the session user(the user who logged on)
DUMP(string [, format [, start DUMP displays the value of the string in internal
[, length] ] ] ) data format, in ASCII, octal, decimal, hex or
character format.
NVL(value, substitute) If value is NULL the NVL function returns
substitute. Otherwise it returns value.
NVL2(expr1, expr2, expr3) If expr1 is not NULL, NVL2 returns expr2. If
expr1 is NULL, NVL2 returns expr3.
VSIZE(expression) VSIZE tells how many bytes oracle needs in
order to store the expression in its database.

2.9 Summary
This unit has given the broad details about structured Query Language for
Oracle9i. It has helped in preparing Queries using DML, DDL. It also lists
the various operators available for SQL using Oracle9i. And also given light
on functions of Oracle9i SQL.

2.10 Exercise
1. Write a note on SELECT, INSERT, DELETE and UPDATE with
example.
2. What are the operators available with SQL for Oracle9i ?
3. List the 10 Numeric functions with examples.

Sikkim Manipal University Page No.: 75

Das könnte Ihnen auch gefallen