You are on page 1of 132

Oracle Complete – A Quick Reference

SQL

General Instructions
1. SQL commands are not at all case sensitive. You can type the command in any
case one case or a mix of cases.
2. While typing commands at the SQL prompt, the cursor cannot be moved back
using the left arrow key. The cursor can be moved back using the back space key.
In other words, a mistake in the typed command cannot be corrected directly
without deleting the command.
3. For correcting the mistake in a typed command without deleting it, you have to
open the editor. For opening the editor, simply type ed at the SQL prompt. The
last typed command will always remain in the SQL Buffer, and the same shall be
seen and edited by opening the editor.

If he editor is used to edit a command, save it after the edition and close the editor
window. Subsequently type / (forward slash) a the SQL prompt to execute the
command saved in the editor.
4. The table name should not exceed 30 characters.
5. No spaces are permitted in a table name
6. The column name should not exceed 30 characters
7. No spaces are permitted in a column name

Data Types
Data Type Width Type of Value
CHAR 1 – 255 Alphanumeric
VARCHAR2 1 – 4000 Alphanumeric
NUMBER 38 Numeric
DATE DD-MON-YY Date
LONG 2 GB CHAR
RAW 1 – 4000 Binary
LONG RAW 2 GB Binary

CHAR Data Type

A field having CHAR data type will accept alphanumeric characters. The database will
hold memory for all the defined length of a CHAR data type field irrespective of the
actual length occupied by a value in that field.

VARCHAR2 Data Type

A field having VARCHAR2 data type will accept alphanumeric characters. The database
will hold memory only for the length occupied by the value of a VARCHAR2 data type

Thampy Mathew 1
Oracle Complete – A Quick Reference
SQL
field. Like the CHAR data type, it will not hold memory for the entire field width without
considering the actual length occupied by a value.

NUMBER Data Type

The maximum data width of a NUMBER data type field is limited to 38. For NUMBER
data type fields, it is optional to specify field with.

Syntax:
Number OR
Number(Precision) OR
Number (Precision, Scale)
The scale can range from –84 to 127.

Example:

Salary Number
Salary Number(5)
Salary Number(7, 2) – Total 7 digits out of which 2 is reserved for decimals.

DATE Data Type

A DATE data type field can accept dates ranging from Jan 1 4712 BC to Dec 31, 4712
AD. In the database the date is stored as a numeric value derived from the given date.

LONG, LONG RAW Data Types

A LONG or LONG RAW data type field can accept image files, sound files etc. Both
LONG and LONG RAW data types cannot be used in the same table. Either use LONG
or LONG RAW.

RAW Data Type

It is mandatory to specify the field size if the data type is RAW.

Checking the Current User


The USER_USERS Table

USERNAME VARCHAR2(30) NOT NULL,


USER_ID NUMBER NOT NULL,
ACCOUNT_STATUS VARCHAR2(32) NOT NULL,
LOCK_DATE DATE,

Thampy Mathew 2
Oracle Complete – A Quick Reference
SQL
EXPIRY_DATE DATE,
DEFAULT_TABLESPACE VARCHAR2(30) NOT NULL,
TEMPORARY_TABLESPACE VARCHAR2(30) NOT NULL,
CREATED DATE NOT NULL,
EXTERNAL_NAME VARCHAR2(4000)

Select Username from User_Users;

DDL – Data Definition Language


Create
Drop
Rename

The Create Command


The ‘Create’ key word is used to create database objects like Tables, Views, Synonyms,
Sequences, Indexes, Database Triggers, Procedures, Functions, Packages etc.

Syntax:

Create Table <table name>


(<Col Name 1 Data Type(width)>,
<Col Name 2 Data Type(width)>,
<Col Name 3 Data Type(width)>,
------------------------------------------
------------------------------------------
<Col Name n Data Type(width)>);

Caution:
Within a database the table names cannot be repeated. Similarly, within a table
the column names also cannot be repeated. Column names may be repeated across
tables within a database.

Note:
The coma after every column definition indicates the continuity of the table
definition and hence it is known as the continuity sign.

The semi-colon or sometimes a forward slash (/) used at the end of the create
command is known as the execution sign as Oracle will try to execute the
command as soon as it come across the execution sign.

Thampy Mathew 3
Oracle Complete – A Quick Reference
SQL
Example:

Create Table EMP


(Ename Varchar2(30),
Empno Varchar2(30),
Sal Number
Comm Number(6,2));

Note:
Specifying width for a Number Data Type is optional.

Assigning Default Values to Columns

Example:

Create Table EMP


(Ename Varchar2(30),
Empno Varchar2(30),
Sal Number,
Comm Number(6,2),
Hiredate Date Default Sysdate);

The Drop Command


The ‘Drop’ key word is used to delete database objects like Tables, Views, Synonyms
Sequences and Indexs.

Syntax:

Drop Table <Table Name>;

Example:

Drop Table EMP;

Thampy Mathew 4
Oracle Complete – A Quick Reference
SQL

The Rename Command


The ‘Rename’ key word is used to rename tables with a new name.

Syntax:

rename <Current Name of the Table > To <New Name for the Table>;
Example:

Rename EMP To EMP1;

Viewing the Table Structure


At the SQL prompt type:

Syntax:

Desc <Table Name >

Semi-colon is not required.

Example:

Desc EMP

Clearing the Screen


Syntax:

Cle Scr

The TAB Table (Synonym)


Any table created in a database is getting stored in a Data Dictionary table called TAB.

The of TAB Table

TNAME VARCHAR2(30) NOT NULL,


TAB TYPE VARCHAR2(7),
CLUSTERED NUMBER

Thampy Mathew 5
Oracle Complete – A Quick Reference
SQL

Checking the Existence of a Table


Select Tname from TAB where Tname like ‘%EMP%’;

Caution:
Irrespective of the case in which you typed the table name at the time of creating,
the table name will get stored only in uppercase in the TAB Table. So ensure that
you mention the Tname (full or partial) in upper case only.

The COL Table


The column detals of a defined table is getting stored in a Data Dictionary table called
COL

The COL Table.

TNAME VARCHAR2(30) NOT NULL,


COLNO NUMBER NOT NULL,
CNAME VARCHAR2(30) NOT NULL,
COLTYPE VARCHAR2(106),
WIDTH NUMBER NOT NULL,
SCALE NUMBER,
PRECISION NUMBER,
NULLS VARCHAR2(19),
DEFAULTVAL LONG,
CHARACTER_SET_NMAE VARCHAR2(44)

Creating a Partitioned Table


About Partitioning
Partitioning is useful for very large tables. By splitting a large table’s rows across
multiple smaller partitions, you accomplish several important goals:

 The performance of queries against the tables may improve, since Oracle
may have to search only one partition (one part of the table) instead of the
entire table to resolve a query.

 The table may be easier to manage. Since the portioned table’s data is
stored in multiple parts, it may be easier to load and delete data in the
partitions than in the large table.

Thampy Mathew 6
Oracle Complete – A Quick Reference
SQL
 Backup and recovery operations may perform better. Since the partitions
are smaller than the partitioned table, you may have more options for
backing up and recovering the partitions than you would have for a single
large table.

Range Partitioning

Create Table WORKER (


Name Varchar2(25),
Age Number,
Lodging Varchar2(15),
Constraint WORKER_PK Primary Key (Name)
}
Partition By Range (Lodging)
(Partition PART1 Values Less Than (‘F’)
Tablespace PART1_TS,
Partition PART2 Values Less Than (‘N’)
Tablespace PART2_TS,
Partition PART3 Values Less Than (‘T’)
Tablespace PART3_TS,
Partition PART4 Values Less Than (MAXVALUE)
Tablespace PART4_TS) ;

Hash Partitioning

Create Table WORKER (


Name Varchar2(25),
Age Number,
Lodging Varchar2(15),
Constraint WORKER_PK Primary Key (Name)
}
Partition By Hash (Lodging)
Partitions 10 ;

In the Hash Partition also you can name the partition and tablespace as follows.

Create Table WORKER (


Name Varchar2(25),
Age Number,
Lodging Varchar2(15),
Constraint WORKER_PK Primary Key (Name)
}
Partition By Hash (Lodging)
Partitions 10
Store In (PART1_TS, PART2_TS) ;

Thampy Mathew 7
Oracle Complete – A Quick Reference
SQL
A hash partition determines the physical placement of data by performing a hash function
on the values of the partition key. In Range Partitioning, consecutive values of the
partition key are usually stored in the same partition. In hash partitioning, consecutive
values of the partition key are not necessarily stored in the same partition. Hash
partitioning distributes a set of records over a greater set of partitions than range
partitioning does, potentially decreasing the likelihood for I/O contention.

Querying Directly From a Partitions


If you know the partition from which you will be retrieving your data, you can specify
the name of the partition as part of the From clause of your query. For example, suppose
you want to query the records for the workers whose lodgings begin with the letter R.
The optimizer should be able to use the partition definitions to determine that only
PART3 partition could contain data that can resolve this query. If you wish, you can tell
Oracle to use PART3 as part of your query.

Select *
From WORKER Partition (PART3)
Where Name Like ‘R%’ ;

Managing Partitioned Tables


You can use the alter table command to add drop, exchange, move modify, rename,
split and truncate partitions. These alter table command options allow you to alter the
existing partition structure, as may be required after a partitioned table has been used
heavily. For example, the distribution of the Lodging values within the partitioned table
may have changed, or the maximum value may have increased.

Stored Objects
Views
Synonyms
Sequences
Indexes

Views
A View is nothing but a query stored in a data dictionary table called USER_VIEWS. A
view does not consume any memory except for storing the query statement. The records
displayed on the terminal through a view are not data it stores but fetching them from the
base tables involved in the query statement when ever a DML operation is performed

Thampy Mathew 8
Oracle Complete – A Quick Reference
SQL
with it. All DML operations are possible on views depending upon the query from which
it is created.

Features of Views

1. Dropping a view doesn’t affect the base table at all.


2. No alteration of the base table structure is possible through a view.
3. Using aliases the base table field names can be hidden.
4. No constraints are possible on views
5. No database triggers are possible on views
6. A view can be replaced with another query statement
7. A view cannot be altered.
8. View can have different privileges for different users.

Creating a View

Syntax:

Create or Replace View <View Name> As


<Query Text>;

Example:

Create or Replace View EMP1 As


Select * from EMP;

Hiding Base Table Field Names in Views

Create or Replace View EMP1 As


Select Ename As Employee,
Sal As Salary,
Comm As Commission,
From EMP;

OR

Create or Replace View EMP1 As


Select Ename Employee,
Sal Salary,
Comm Commission,
From EMP;

Thampy Mathew 9
Oracle Complete – A Quick Reference
SQL
Views Having Order By Clause

Create or Replace View EMP1 As


Select * From EMP
Order By Ename;

Note:
No DML operation is possible through views having Order By clause in its query
text. This is because, when the user deletes the first record from the view, the
system will try to delete the same first row from the base table which will be
another record.

Views Having Group By Clause

Create or Replace View EMP1 As


Select * From EMP
Group By Empno, Ename;

Note:
No DML operation is possible through views having Order By clause in its query
text.

Views Linking Master/Details Tables

Create or Replace View EMP1 As


Select Dept.Deptno,
Emp.Empno
Emp.Ename,
Emp.Sal
From
Dept,
Emp,
Where
Dept.Deptno = Emp.Deptno;

Note:
Only delete operation is possible on Master Table
All DMLs are possible on Child Table

The USER_VIEWS Table

VIEW_NAME VARCHAR2(30) NOT NULL,


TEXT_LNGTH NUMBER,
TEXT LONG,

Thampy Mathew 10
Oracle Complete – A Quick Reference
SQL
TYPE_TEXT_LENGTH VARCHAR2(4000),
OLD_TEXT_LENGTH NUMBER,
OLD_TEXT VARCHAR2(4000),
VIEW_TYPE_OWNER VARCHAR2(30),
VIEW_TYPE VARCHAR2(30)

Viewing the Query Text of a Defined View

Set Long4000

Select View_Name, Text From USER_VIEWS


Where View_Name like ‘EMP%’;

Synonyms
Synonyms are pointers on database objects like Tables Procedures, Functions, Database
Triggers and Views. As the name suggests it is only an alternate name for a database
object.

Thampy Mathew 11
Oracle Complete – A Quick Reference
SQL
Differences Between Views and Synonyms
Sl.No. Views Synonyms
1. Views can be created on limited Synonyms are always created on the
columns of a table complete table
2. View cannot be created as public Synonyms can be created as private or
directly. public.
(It may be made public using a
synonym.)
3. View is created from table(s) or Synonyms are created for database
other view(s) objects like Tables Procedures,
Functions, Database Triggers and Views.
4. A view cannot be created without A Synonym can be created for any object
the involved tables existing. even when the object does not exist. The
object shall be created later.
5. Only limited DML operations are All DML operations are possible using a
possible using a View synonym.

How Private and Public Differs


Any user can use a public object without using the owner’s schema name. Another user
can use a private object only if the owner grants privileges on the object to him. When
another user uses a private object, he has to use the owner’s schema name.

Schema
In the most simple terms a schema is a User/Password

Creating a Private Synonym

Syntax:

Create Synonym <Synonym Name> For <Object Name>;


Example:

Create Synonym EMPLOYEE For EMP;

Creating a Public Synonym

Syntax:

Create Public Synonym <Synonym Name> For <Object Name>;

Thampy Mathew 12
Oracle Complete – A Quick Reference
SQL
Example:

Create Public Synonym EMPLOYEE For EMP;

The USER_SYNONYMS (DBA_SYNONYMS) Table

OWNER VARCHAR2(30) NOT NULL


SYNONYM_NAME VARCHAR2(30) NOT NULL
TABLE_OWNER VARCHAR2(30)
TABLE_NAME VARCHAR2(30) NOT NULL
DB_LINK VARCHAR2(128)

Indexes
Indexing will make the execution of a select statement faster. When an index is created
on a column of a table, implicitly an index segment will be created which will store
ROWIDs and column values of the indexed columns in ascending order.

When the user fires a select statement, using the indexed column as a where condition
based on the ROWID of the index, Oracle will fetch the corresponding records from the
table.

When the table is dropped, all the indexes will be dropped implicitly because an index
physically stores records of the indexed column.

Records in the Table EMP

Deptno Ename ROWID


10 John 001
40 Xavier 002
10 William 003
20 Smith 004
30 Allen 005
40 Mishra 006

Index on Deptno

Deptno ROWID
10 001
10 003
20 004
30 005
40 002
40 006

Thampy Mathew 13
Oracle Complete – A Quick Reference
SQL
For the primary key of a table oracle implicitly creates an index segment and stores data
of the PK column.

Creating an Index

Syntax:

Create Index <Index Name> On <Table Name>(<Field Name);

Example:

Create Index EMP_IND On EMP(Ename);

The USER_INDEXES (DBA_INDEXES) Table

OWNER VARCHAR2(30) NOT NULL


INDEX_NAME VARCHAR2(30) NOT NULL
INDEX_TYPE VARCHAR2(12)
TABLE_OWNER VARCHAR2(30) NOT NULL
TABLE_NAME VARCHAR2(30) NOT NULL
TABLE_TYPE VARCHAR2(11)
UNIQUENESS VARCHAR2(9)
TABLESPACE_NAME VARCHAR2(30)
INI_TRANS NUMBER
MAX_TRANS NUMBER
INITIAL_EXTENT NUMBER
NEXT_EXTENT NUMBER
MIN_EXTENTS NUMBER
MAX_EXTENTS NUMBER
PCT_INCREASE NUMBER
PCT_THRESHOLD NUMBER
INCLUDE_COLUMN NUMBER
FREELISTS NUMBER
FREELIST_GROUPS NUMBER
PCT_FREE NUMBER
LOGGING VARCHAR2(3)
BLEVEL NUMBER
LEAF_BLOCKS NUMBER
DISTINCT_KEYS NUMBER
AVG_LEAF_BLOCKS_PER_KEY NUMBER
AVG_DATA_BLOCKS_PER_KEY NUMBER
CLUSTERING_FACTOR NUMBER
STATUS VARCHAR2(8)

Thampy Mathew 14
Oracle Complete – A Quick Reference
SQL
NUM_ROWS NUMBER
SAMPLE_SIZE NUMBER
LAST_ANALYZED DATE
DEGREE VARCHAR2(40)
INSTANCES VARCHAR2(40)
PARTITIONED VARCHAR2(3)
TEMPORARY VARCHAR2(1)
GENERATED VARCHAR2(1)
BUFFER_POOL VARCHAR2(7)

Sequences
Sequences are used to create unique numbers automatically.

Creating a Sequence

Syntax:

Create Sequence <Sequence Name>


Maxvalue <Value>
Minvalue <Value>
Start With <Value>
Increment By <Value>
Cache <Value>
Cycle <or> Nocycle;

Example:

Create Sequence MY_SEQ


Maxvalue 10000
Minvalue 1
Start With 10
Increment By 1
Cache 3
Nocycle;

Simple Syntax:

Create Sequence <Sequence Name>

Example:

Create Sequence MY_SEQ;

Thampy Mathew 15
Oracle Complete – A Quick Reference
SQL
Choosing the Next Value from the Sequence

Select MY_SEQ.Nextval From Dual;

Choosing the Current Value from the Sequence

Select MY_SEQ.Currval From Dual;

Alteration of Sequence Definition

Alter Sequence MY_SEQ Nextval 5000;

Alter Sequence MY_SEQ Cycle;

Dropping Sequence

Drop Sequence MY_SEQ;

The USER_SEQUENCES Table

SEQUENCE_OWNER VARCHAR2(30) NOT NULL,


SEQUENCE_NAME VARCHAR2(30) NOT NULL,
MIN_VALUE NUMBER,
MAX_VALUE NUMBER,
INCREMENT_BY NUMBER NOT NULL,
CYCLE_FLAG VARCHAR2(1),
ORDER_FLAG VARCHAR2(1),
CACHE_SIZE NUMBER NOT NULL,
LAST_NUMBER NUMBER NOT NULL

DML – Data Manipulation Language


Insert
Update
Delete
Select

The Insert Command


The ‘Insert’ command is used to insert new records into a table.

Thampy Mathew 16
Oracle Complete – A Quick Reference
SQL
Inserting Records by Including All Fields of a Table

Syntax:
Insert into <table name>
values(<field 1 value>,
<field 2 value>,
…………………….
…………………….
<field n value>);

Example:

Insert into EMP


values(‘MOHAN’,
‘1023,
5000
‘’);

Caution:
1. The specified values must be in the same order of columns defined in the
table.
2. If the data type of the field is CHAR or VARCHAR2, then he values must be
enclosed in single quotes.
3. If no value is to be inserted into a particular field, then it must be indicated by
typing two single quotes without spaces. In the given example, a null is
inserted into the field ‘Comm’ by typing two quotes without spaces.

Inserting Records by Including Only Specific Fields of a Table

Syntax:

Insert into <table name>(field 3, filed 1)


values(<field 3 value>, <field 1 value>);

Example:
Insert into EMP (Sal, Ename)
values(5000, ‘MOHAN’);

Note:
If you want to insert values only for selected columns of a table, the column
names must be specified. When you specify the column name, the order of the

Thampy Mathew 17
Oracle Complete – A Quick Reference
SQL
columns in the table need not to be considered. But, subsequently when you
specify the values, they must come in the same order in which the columns are
specified in the Insert command.

The Update Command


Updating Only One Field of a Table

Syntax:

Update <table name> Set <Col Name> = <Value>;

Example:

Update EMP Set Sal = 6000;


Update EMP Set Ename = ‘Mohan’;

Caution:
1. The update command as given above will set the value of the specified field of
all records with the given value.
2. If the data type of the field being updated is CHAR or VARCHAR2 then the
given value must be enclosed in single quotes.

Conditional Update

Example:
Update EMP Set Sal = 7000 where Ename = ‘Mohan’;

Updating Multiple Fields in One Command

Syntax:

Update <table name> Set


<Col Name 1> = <Col 1 Value>,
<Col Name 2> = <Col 2 Value>;

Example:

Update EMP Set Sal = 3500, Ename = ‘JOHN’;

Thampy Mathew 18
Oracle Complete – A Quick Reference
SQL

The Delete Command


The ‘Delete’ command deletes records from a table.

Deleting All Records From a Table

Syntax:

Delete from <table name>;

Example:

Delete from EMP;

Conditional Deletion

Delete from EMP where Ename = ‘MOHAN’;


Delete from EMP where Ename Like ‘MOHAN’;
Delete from EMP where Ename Like ‘MOH%’;
Delete from EMP where Ename Like ‘%HAN’;
Delete from EMP where Ename Like ‘%OHA%’;
Delete from EMP where Ename Like ‘%OHA%’ And Sal = 5000;
Delete from EMP where Ename Like ‘%OHA%’ Or Comm = 300;

Caution:
For deleting values only from one field of a table, you should not use the ‘Delete’
command. In such cases use the ‘Update’ command.

Update EMP Set Sal = Null;

Taking User Input While Performing DML


Example 1:

Insert Into EMP(Ename, Empno) Values(


&Name,
&No.);

If single quotes are not used for character data type columns along with the &,
you will have to enter values in single quotes later. To avoid it, the statement can
be rewritten as follows.

Insert Into EMP(Ename, Empno) Values(


‘&Name’, ‘&No’);

Thampy Mathew 19
Oracle Complete – A Quick Reference
SQL
When the above command is executed, Oracle will ask for values of Ename and
Empno to the user. This command can be executed n number of times without
retyping the command all over again. After one execution, simply type forward
slash (/) and enter. For each execution, Oracle will ask for values of Ename and
Empno to the user.

This command can be used again and again only till another command is typed at
the SQL prompt.

Example 2:

Update EMP Set Empno = 1500 Where Ename = ‘&Ename’;


Update EMP Set Empno = &Empno Where Ename = ‘&Name‘;

Example 3:

Delete From EMP Where Ename = ‘&Name‘;

DTL – Data Transaction Language


Commit
Rollback

Commit
Any DML operation (Insert, Update, Delete) performed on a database table will become
permanent only if it is saved using the ‘Commit’ command.

Syntax:

Commit;

Note:
The saving operation is required only for DML commands. It is not applicable to
the DDL commands (Create, Drop, Rename). The DDL commands perform auto
commit along with the object creation.

Rollback
If the effect of an executed DML command is to be revoked, do rollback before
committing. The rollback will not work after executing the ‘Commit’ command.

Thampy Mathew 20
Oracle Complete – A Quick Reference
SQL
Syntax:

Rollback;

The Truncate Command


The ‘Truncate’ command is similar to the ‘Delete’ command. But it is much more
powerful in the sense that the ‘Truncate’ command simultaneously execute two
commands viz. Delete and Autocommit. The ‘Delete’ command gives you the chance to
rollback the deletion whereas the ‘Truncate’ command does not give the rollback chance.

Syntax:

Truncate Table <Table Name>;

Example:

Truncate Table EMP;

Caution:
1. The ‘Truncate’ command does not give a chance to rollback the deletion it
performed.

2. No conditional deletion is possible with the ‘Truncate’ command. It simply


deletes all records from a table and autocommit.

Snapshots And DTL Commands


When a DML operation is performed on a table, the table will get locked and
simultaneously a snapshot will be created with all the previously committed records. The
Users other than the one who is performing the DML operation will be having access
only to the snapshot. When a second user performs another DML operation on the same
table, again another snapshot will be created and other users will have access only to the
third snapshot. The snapshot will be removed along with a DTL command.

User1 can see both new and old records but other users can see only the old committed
records.

Thampy Mathew 21
Oracle Complete – A Quick Reference
SQL
Script Files
Script files are nothing but Notepad files with one or more SQL commands. When the
script file is run, all the commands written in it will get executed serially.

Opening a Script File

Syntax:

Ed <Path> \ <File Name>.txt;

Example:

Ed C:\ My_Script.txt; (A Notepad file with the name My_Scrpt.txt is


Created in C drive)

Type all the required commands in the script file as shown below.

Create Table DEPT


(Deptno Varchar2(10),
Dname Varchar2(15),
Location Varchar2(15))
/

Create Table EMP


(Empno Varchar2(10),
Ename Varchar2(15),
Deptno Varchar2(10),
Sal Number,
Comm Number)
/

Insert into DEPT Values


(‘10’, ‘FINANCE’, NULL)
/
Insert into DEPT Values
(‘20’, ‘PRODN’, NULL)
/

Insert into EMP(Ename, Empno, Deptno) Values


(‘JOHN’, ‘1005’, ‘10’)
/
Commit
/
Save and close the file.

Thampy Mathew 22
Oracle Complete – A Quick Reference
SQL
Caution:
In script files do not use semi-colon as execution sign. Instead, use forward slash
that also in a separate line as shown.

Executing a Script File

SQL> @C:\My_Script.txt

When the script runs, all commands typed in it will get executed serially.

Major Use of Script Files.

When database objects and programs are to be transferred from one database to
another in the same or a different machine, scripts can be used.

Spool Files
A Spool file is nothing but a text file created to capture the output of SQL operations.

Opening a Spool file

SQL> Spool C:\My_Spool.txt

Note:
After opening a spool file, whatever commands are typed in the SQL prompt
along with its output will be stored in the spool file till then it is closed.

Closing the Spool File

SQL> Spool Off

Modification of Structures
Adding a New Column to a Table
Syntax:

Alter Table <table name>


Add (<New Col Name> <Data Type>(<Width>));

Thampy Mathew 23
Oracle Complete – A Quick Reference
SQL
Example:

Alter Table EMP


Add (Mgr Varchar2(15));

Changing the Data Type of an Existing Column


Syntax:

Alter Table <table name>


Modify (<Existing Col Name> <New Data Type>(<Width>));

Example:

Alter Table EMP


Modify (Empno CHAR(20));

Caution:
1. The width of an existing column cannot be decreased if records are present in
that column. This limitation is not applicable for increasing the column width.
2. The data type of an existing column cannot be changed from numeric to
character and vice versa if records are present in that column. However, we
can change the data type from CHAR to VARCHAR2 and vice versa provide
that the width of the new data type specified is equal to or more than the width
of the existing data type.

Duplicating a Table
Major Uses:

1. Changing the structure of an existing table with records. (The existing table is
duplicated. Then delete all records from the existing table. Make the required
modifications in the original table structure. Bring back all records to the
original table and drop the duplicate table.)
2. Dropping certain fields from an existing table. (Duplicate the existing table
only with the required number of columns. Drop the original table and rename
the duplicate table with the original table name.)
3. To change the column names. (Duplicate the existing table with new column
names. Drop the original table and rename the duplicate tab with the original
table name.)

Thampy Mathew 24
Oracle Complete – A Quick Reference
SQL
Duplicating Only the Structure of a Table

Syntax:

Create Table <Duplicate Table Name>


As Select * From <Existing Table Name> where 1=2;

Example:

Create Table EMP1


As Select * From EMP where 1=2;

Bringing Records to the Duplicate Table From Original Table

Syntax:

Insert Into <Duplicate Table Name>


As Select * From <Existing Table Name;

Example:

Insert Into EMP1


As Select * From EMP;

Drop Table EMP;


Rename EMP1 To EMP;

Caution:
If records are brought back after modifying the data type or width, ensure that the
data matches the new field definitions.

Dropping Column(s) from an Existing Table With Records

Syntax:

Create Table <Duplicate Table Name>


As Select <Column 1, Column 2, …….. Column n From <Existing Table>;

Example:

Create Table EMP1


As Select Ename, Empno, Sal From EMP;

Thampy Mathew 25
Oracle Complete – A Quick Reference
SQL
Drop Table EMP;
Rename EMP1 To EMP;

Renaming Column(s) of an Existing Table with Records

Syntax:

Create Table <Duplicate Table Name>(<New Col Name 1>,


<New Col Name 2>,
……………………..
……………………..
<New Col Name n>)
As Select <Col Name 1,
Col Name 2,
…………..
……………
Column n From <Existing Table>;

Example:

Create Table EMP1(Name, No, Salary)


As Select Ename, Empno, Sal From EMP;

Drop Table EMP;


Rename EMP1 To EMP;

Caution:
1. The column(s) can be renamed without removing the records.
2. The Data Type and Width of both original and duplicate table fields will
remain the same.
3. The number of column(s) mentioned in both duplicate and original tables
must match.

Dropping a Column from a Table Without Duplicating


Syntax:

Alter Table <Table Name> Drop Column <Column Name>;

Example:

Alter Table EMP Drop Column Comm;

Thampy Mathew 26
Oracle Complete – A Quick Reference
SQL
Dropping Multiple columns in One command

Alter Table EMP Drop (Comm, Sal);

Caution:
If multiple columns are dropped in one command the ‘column’ key word should
not be used.

Marking a Column As Unused


The column marked as ‘Unused’ cannot be accessed.

Syntax:

Alter Table <Table Name> Set Unused Column <Column Name>;

Example:

Alter Table EMP Set Unused Column Deptno;

Dropping Unused Columns


Syntax:

Alter Table <Table Name> Drop Unused Columns;

Example:

Alter Table EMP Drop Unused Columns;

Checking the Constraints on a Table


The User_Constraints Table

OWNER VARCHAR2(30) NOT NULL,


CONSTRAINT_NAME VARCHAR2(30) NOT NULL,
CONSTRAINT_TYPE VARCHAR2(1),
TABLE_NAME VARCHAR2(30) NOT NULL,
SEARCH_CONDITION LONG,
R_OWNER VARCHAR2(30),
R_CONSTRAINT_NAME VARCHAR2(30),

Thampy Mathew 27
Oracle Complete – A Quick Reference
SQL
DELETE_RULE VARCHAR2(9),
STATUS VARCHAR2(8),
DEFERRABLE VARCHAR2(14),
DEFERRED VARCHAR2(9),
VALIDATED VARCHAR2(13),
GENERATED VARCHAR2(14),
BAND VARCHAR2(3),
RELY VARCHAR2(4),
LAST_CHANGE DATE

Select Constraint_Name,
Constraint_Type,
Search_Condition
From User_Constraints
Where Table_Name = EMP;

Constraints
Constraints are restrictions imposed on the columns of a table to accept values. The
constraints are always validated at the end of he execution and if any value that violates
the defined constraint is found, Oracle rollback that row automatically.

Following are the constraints that can be imposed on column(s) of a table.

Primary Key
Unique
Not Null
Check
Foreign Key

Rules of Constraints

1. There can be one and only one Primary Key per table.

2. One column cannot have both Primary Key and unique constraints defined for
it.

3. There can be up to 254 Check constraints defined for one column of a table.

4. There can be Primary Key, Not Null and Check constraints on a particular
column.

5. There can be up to 254 Not Null constraints defined for a table.

Thampy Mathew 28
Oracle Complete – A Quick Reference
SQL
6. There can be up to 254 Unique constraints defined for a table.

Caution:
1. If the key word ‘Constraint’ is used, you should specify a constraint
name. If you don’t want to specify a constraint name, don’t use the key
word ‘Constraint’ while defining constraints at column level or table
level.

2. Not Null constraint cannot be defined at table level.

The Primary Key Constraint


A Primary Key column must be Unique and Not Null. i.e. if a Primary key constraint is
defined for a column of a table, you can neither insert a duplicate value into that column
nor you can insert a record without a value for that column.

Primary Key Definition at Column Level

Create Table EMP


(Empno Varchar2(20) Primary Key,
Ename Varchar2(20),
Sal Number);

Primary Key Definition at Column Level With User Constraint Name

Create Table EMP


(Empno Varchar2(20) Constraint Empno_PK Primary Key,
Ename Varchar2(20),
Sal Number);

Primary Key Definition at Table Level

Create Table EMP


(Empno Varchar2(20),
Ename Varchar2(20),
Sal Number,
Primary Key(Empno));

Primary Key Definition at Table Level with User Constraint Name

Create Table EMP


(Empno Varchar2(20),
Ename Varchar2(20),
Sal Number,
Constraint Emno_PK Primary Key(Empno));

Thampy Mathew 29
Oracle Complete – A Quick Reference
SQL
Composite Primary Key

Create Table EMP


(Empno Varchar2(20),
Ename Varchar2(20),
Sal Number,
Primary Key(Empno, Ename));

Note:
If the user does not specify a constraint name, system will automatically create a
unique name for each constraint. The system generated constraint names with a
prefix SYS_C.

The Unique Constraint


Unique Constraint Definition at Column Level

Create Table EMP


(Empno Varchar2(20) Unique,
Ename Varchar2(20),
Sal Number);

Unique Constraint Definition at Column Level With User Constraint


Name

Create Table EMP


(Empno Varchar2(20) Constraint Empno_UN Unique,
Ename Varchar2(20),
Sal Number);

Unique Constraint Definition at Table Level

Create Table EMP


(Empno Varchar2(20),
Ename Varchar2(20),
Sal Number,
Unique(Empno));

Unique Constraint Definition at Table Level with User Constraint


Name

Create Table EMP


(Empno Varchar2(20),

Thampy Mathew 30
Oracle Complete – A Quick Reference
SQL
Ename Varchar2(20),
Sal Number,
Constraint Emno_UN Unique(Empno));

Composite Unique Constraint (Candidate Key)

Create Table EMP


(Empno Varchar2(20),
Ename Varchar2(20),
Sal Number,
Constraint Unique(Empno, Ename));

Note:
If the user does not specify a constraint name, system will automatically create a
unique name for each constraint. The system generated constraint names will start
with the characters SYS.

The Not Null Constraint


Not Null Constraint Definition at Column Level

Create Table EMP


(Empno Varchar2(20) Primary Key,
Ename Varchar2(20) Not Null,
Sal Number);

Not Null Constraint Definition at Column Level With User Constraint


Name

Create Table EMP


(Empno Varchar2(20) Constraint Empno_PK Primary Key,
Ename Varchar2(20) Constraint Ename_NN Not Null,,
Sal Number);

Not Null Constraint Definition at Table Level

Not possible.

Not Null Constraint Definition at Table Level with User Constraint


Name

Not possible.

Thampy Mathew 31
Oracle Complete – A Quick Reference
SQL
The Check Constraint
Check Constraint Definition at Column Level

Create Table EMP


(Empno Varchar2(20) Primary Key,
Ename Varchar2(20) Not Null,
Sal Number Check (Sal Between 5000 And 10000));

Check Constraint Definition at Column Level With User Constraint


Name

Create Table EMP


(Empno Varchar2(20) Constraint Empno_PK Primary Key,
Ename Varchar2(20) Constraint Ename_NN Not Null,
Sal Number Constraint EMP_Sal_CK Check (Sal > 5000));

Check Constraint Definition at Table Level

Create Table EMP


(Empno Varchar2(20),
Ename Varchar2(20),
Sal Number,
Comm Number,
Total Number,
Check(Total = Sal + Comm));

Check Constraint Definition at Table Level with User Constraint


Name

Create Table EMP


(Empno Varchar2(20),
Ename Varchar2(20),
Sal Number,
Comm Number,
Total Number,
Constraint EMP_Sal_CK Check(Total = Sal + Comm));

Note:
While defining check constraint, if another column is to be referenced, the
constraint must be defined at the table level. Referencing another column for
defining a constraint at the column level is not permitted.

Thampy Mathew 32
Oracle Complete – A Quick Reference
SQL

The Foreign Key Constraint


Foreign Key Constraint Definition at Column Level

Create Table EMP


(Empno Varchar2(20) Primary Key,
Ename Varchar2(20) Not Null,
Deptno Varchar2(10) References Dept.Deptno,
Sal Number);

Foreign Key Constraint Definition at Column Level With User


Constraint Name

Create Table EMP


(Empno Varchar2(20) Constraint Empno_PK Primary Key,
Ename Varchar2(20) Constraint Ename_NN Not Null,
Deptno Varchar2(10) Constraint Deptno_FK References Dept (Deptno),
Sal Number);

Foreign Key Constraint Definition at Table Level

Create Table EMP


(Empno Varchar2(20),
Ename Varchar2(20),
Deptno Varchar2(10),
Sal Number,
Foreign Key (Deptno) References Dept (Deptno));

Foreign Key Constraint Definition at Table Level with User Constraint


Name

Create Table EMP


(Empno Varchar2(20),
Ename Varchar2(20),
Deptno Varchar2(10),
Sal Number,
Constraint Empno_PK Primary Key(Empno),
Constraint Deptno_FK Foreign Key (Deptno) References Dept (Deptno));

Note:
Deptno column of EMP table will not accept a value that is not present in the
Deptno field of DEPT Table. But it will accept NULL.

Thampy Mathew 33
Oracle Complete – A Quick Reference
SQL
On Delete Cascade Clause on Foreign Key Constraint

It only work with the Foreign Key constraint of a child table.

If the foreign key is having an ‘On Delete Cascade’ defined in it, when the user deletes
records from the Master table, Oracle automatically deletes the corresponding records
from the child table. (Internally the child records are deleted first and then the Master
records are deleted.)

Create Table EMP


(Empno Varchar2(20),
Ename Varchar2(20),
Deptno Varchar2(10),
Sal Number,
Foreign Key (Deptno) References Dept (Deptno) On Delete Cascade );

Caution:
1. While referential integrity constraints are defined for a column of a table, the
referenced column must be of the same data type and width. The referenced
and referencing column names may be different.
2. The referenced column must be a Primary Key or Unique.

Cascade Constraint Clause on Foreign Key Constraint

This clause of the foreign key constraint can be used to disassociate the referenced
records of a child table from the master records when a Master table is to be dropped
without dropping the child table. Using the Cascade Constraint clause, if the master table
is dropped the child table can remain intact and independent with all its records.

Syntax:

Drop Table <Master Table whose records are referenced by child tables> Cascade
Constraint;

Example:

Drop Table Dept Cascade Constraint;

Thampy Mathew 34
Oracle Complete – A Quick Reference
SQL
Table Level & Column Level Constraints Compared
Sl. Column Level Table Level
1. The constraint is defined in The constraint is defined at the end
continuation to the column after all column definitions
definition
2. Only one column can be made into Composite (Combined) Primary Key
a Primary Key can be created by combining a
maximum of 16 columns
3. Only one column can be made into Composite (Combined) Unique
Unique columns can be created by
combining a maximum of 16
columns
4. Check constraint cannot reference Check constraint can reference
another column. another column of the same table
5. Not Null constraint with or without Not Null constraint cannot be
user specified constraint name can defined.
be defined for any column

Referencing Composite Primary Key


Master Table

Create Table Dept


(Deptno Varchar2(10),
Dname Varchar2(20),
Primary Key (Deptno, Dname));

Child Table

Create Table Emp


(Empno Varchar2(20),
Ename Varchar2(20),
DeptnoVarchar2(10),
Dname Varchar2(20),
Foreign Key (Deptno, Dname) References Dept(Deptno, Dname));

Master Table Values

Deptno Dname
10 Null /* Not Acceptable */
10 QC /* Acceptable */
20 FIN /* Acceptable */
Null PROD /* Not Acceptable */

Thampy Mathew 35
Oracle Complete – A Quick Reference
SQL
Child Table Values

Empno Ename Deptno Dname


100 John 10 Null /* Not Aceptable */
101 Suman 10 QC /* Aceptable */
102 Shibu 20 Null /* Not Aceptable */
103 Mary 10 FIN /* Not Aceptable */
104 James 20 FIN /* Aceptable */
105 Abraham Null PROD /* Not Aceptable */

Referencing Composite Unique Fields


Master Table

Create Table Dept


(Deptno Varchar2(10),
Dname Varchar2(20),
Unque (Deptno, Dname));

Child Table

Create Table Emp


(Empno Varchar2(20),
Ename Varchar2(20),
DeptnoVarchar2(10),
Dname Varchar2(20),
Foreign Key (Deptno, Dname) References Dept(Deptno, Dname));

Master Table Values

Deptno Dname
10 Null /* Aceptable */
10 QC /* Aceptable */
20 FIN /* Aceptable */
Null PROD /* Aceptable */

Child Table Values

Empno Ename Deptno Dname


100 John 10 Null /* Aceptable */
101 Suman 10 QC /* Aceptable */
102 Shibu 20 Null /* Not Aceptable */
103 Mary 10 FIN /* Not Aceptable */
104 James 20 FIN /* Aceptable */
105 Joy Null PROD /* Aceptable */

Thampy Mathew 36
Oracle Complete – A Quick Reference
SQL

Adding Constraints to Existing Columns


Caution:
For adding Primary Key, Unique or Check constraint ‘Add’ key word is used, but
for adding a Not Null constraint ‘Modify’ key word is used.

Adding Primary Key Constraint

Alter Table EMP


Add Primary Key (Empno):

Alter Table EMP


Add Primary Key (Empno, Ename):

Adding Unique Constraint

Alter Table EMP


Add Unique (Empno):

Alter Table EMP


Add Unique (Empno, Ename):

Adding Check Constraint

Alter Table EMP


Add Check (Sal Between 5000 And 8000):

Alter Table EMP


Add Check (Total = Sal + Comm):

Adding Not Null Constraint

Alter Table EMP


Modify (Ename Varchar2(20) Not Null):

Adding Multiple Constraints in One command

Alter Table EMP


Add Primary Key (Empno) /* No coma after the Add statement */
Add Unique (Ename):

Order of Firing of Constraints

Thampy Mathew 37
Oracle Complete – A Quick Reference
SQL
The constraints are fired in the following order if all of them present in a table

1. Not Null
2. Check
3. Primary Key
4. Unique

Disabling Constraints
Syntax:

Alter Table <Table Name> Disable Constraint <Constraint Name>;

Example:

Alter Table EMP Disable Constraint SYS_C004539;

Note:
The Constraint_Name must be found out from the User_Constraints table.

Enabling Constraints
Syntax:

Alter Table <Table Name> Enable Constraint <Constraint Name>;

Example:

Alter Table EMP Enable Constraint SYS_C004539;

Note:
The Constraint_Name must be found out from the User_Constraints table.

Dropping Constraints
Syntax:

Alter Table <Table Name> Drop Constraint <Constraint Name>;

Thampy Mathew 38
Oracle Complete – A Quick Reference
SQL
Example:

Alter Table EMP Drop Constraint SYS_C004539;

Note:
The Constraint_Name must be found out from the User_Constraints table.

Dropping Multiple Constraints in One Command

Alter Table EMP


Drop Constraint SYS_C004539 /* No coma after each drop statement */
Drop Constraint SYS_C004549
Drop Constraint SYS_C004550;

SQL*Plus
Set sqlprompt ‘Thampy’
Set Feed Off
Set Feed On
Set Head Off
Set Head On
Set Long10000
Set Linesize 100
Set Autotrace On
Set Autotrace Off

Formatting Reports

Break on Deptno

Break on Deptno Skip1

Compute Sum of Sal on Deptno

Break on Deptno Skip1 on Report (One blank row at the end of the report)

Adjusting Column Width

column ename format a6

The values will not be truncated, but if any value exceeds 6 characters they will go to the
next line.

Thampy Mathew 39
Oracle Complete – A Quick Reference
SQL
Titles

Title ‘Concourse Ltd’

TTitle Center ‘Concourse Ltd’

TTitle Left ‘Concourse Ltd’

TTitle Right ‘Concourse Ltd’

TTitle Left ‘Concourse Ltd’ Skip1

BTitle ‘Pageno’: Format99 SQL:PNO

Set Pagesize 30

Clearing the Formats

TTitle Off
BTitle Off
Clear Break
Clear Compute
Column format off

Manipulating the Last Executed SQL Statement

The last executed command always remains in the SQL Buffer. For editing that command
you can either open an editor or you can do so from the SQL prompt as follows.

SQL> L (The last executed command will be redisplayed)

SQL> L1 (The first line of the last executed command will be redisplayed)

SQL> L2 (The second line of the last executed command will be redisplayed)

Editing the Commands

SQL> Select Ename From EMP;

SQL> C/Ename/Empno (Change Ename to Empno)

SQL> C/Empno/Dname

SQL> C/EMP/DEPT

Thampy Mathew 40
Oracle Complete – A Quick Reference
SQL
Running the Command

SQL> R (Run the command. The command will be ‘Select Dname From DEPT’)

SQL> Select * From EMP Where


Ename = ‘smith’;

SQL> L2

SQL> C/smith/SMITH

SQL> Select * From EMP Where


Ename = ‘smITH’;

SQL> L2

SQL> C/sm/SM

SQL> L1

Removing Word(s)

SQL> C/Where/(insert 2 spaces) (The ‘Where’ will be removed)

SQL> L2

SQL> C/Ename = SMITH/(insert 2 spaces) (The Ename = SMITH will be removed)

(The command will become ‘Select * From EMP’)

Adding Word(s)

SQL> Select * From EMP Where


Ename = ‘SMITH”;

SQL> L2

SQL> A AND Deptno = 10 (A for Append)

The command will become ‘Select * From EMP Where


Ename = ‘SMITH”; AND Deptno = 10’

Thampy Mathew 41
Oracle Complete – A Quick Reference
SQL
Operators
Mathematical Operators
+ - Addition
- - Subtraction
* - Multiplication
/ - Division

Single Value Operators


= - Equal to
> - Greater than
< - Less Than
>= - Greater than or equal to
<= - less than or equal to
! - Not
!= - Not equal to
Is Not Null
Is Null
Like
Not Like
Exists
Not Exists

Multiple Value Operators

Any - Checks one value between two given values


In - Checks one value from many given values
Not In
Between - Checks all values between to given values
Not Between

Examples:

Records in Table DEPT Records in Table EMP


Deptno Dname Deptno Ename
10 A/C 10 Alex
20 FIN 20 Thomas
30 PROD 30 Mathew

Select Ename From EMP Where deptno = ANY (10, 40);


(All the single value operators can be used with ‘Any’)

Thampy Mathew 42
Oracle Complete – A Quick Reference
SQL
Output:
Alex

Select Ename From EMP Where deptno IN (10, 20);

Output:
Alex
Thomas

Select Ename From EMP Where deptno NOT IN (10, 20);

Output:
Mathew

Select Ename From EMP Where deptno BETWEEN 10 And 30;

Output:
Alex
Thomas
Mathew

Select Ename From EMP Where deptno NOT BETWEEN 10 And 20;

Output:
Mathew

Set Operators

Union - Returns all values without repeats


Union All - Returns all values with repeats
Intersect - Returns only common values
Minus - Returns uncommon values

Examples:

Records in Table DEPT Records in Table EMP


Deptno Dname Deptno Ename
10 A/C 10 Alex
20 FIN 20 Thomas
30 PROD

Select Deptno From DEPT UNION (Select Deptno From EMP);

Output:
10
20

Thampy Mathew 43
Oracle Complete – A Quick Reference
SQL
30

Select Deptno From DEPT UNION ALL (Select Deptno From EMP);

Output:
10
20
30
10
20

Select Deptno From DEPT INTERSECT (Select Deptno From EMP);

Output:
10
20

Select Deptno From DEPT MINUS (Select Deptno From EMP);

Output:
10

AND, OR Conditions
AND
It always check whether all the conditions specified in the select statement using AND
are met before fetching records. Any record that fails to meet any one condition will be
skipped.

OR
It always check whether at least one condition specified in the select statement using OR
is met before fetching records. Any record that meets at least one condition will be
fetched.

Functions
Character Functions
CONCATENATE
Select ‘Mr’||’.’||Ename From EMP;
Output: Mr.Alex Mr.Mathew etc.

Thampy Mathew 44
Oracle Complete – A Quick Reference
SQL
INITCAP (String)
Select INITCAP (cONCOURSE) From Dual;
Output: CONCOURSE

LENGTH (String)
Select LENGTH (Ename) From EMP;
Output: 6 (The length of the longest name the EMP Table)

LOWER (String)
Select LOWER (‘ABC’) From EMP;
Output: abc

UPPER (String)
Select UPPER (‘abc’) From EMP;
Output: ABC

RPAD (String, Total Length Required, ‘Padding Character’ )


Select RPAD (Ename, 10, ‘x’’) From EMP;
Output: Thomasxxxx Mathewxxxx Johnxxxxxxetc.

LPAD (String, Total Length Required, ‘Padding Character’ )


Select LPAD (Ename, 10, ‘x’’) From EMP;
Output: xxxxThomas xxxxMathew xxxxxxJohn etc.

RTRIM (String, ‘Characters to be trimmed from the left end’ )


Select RTRIM (‘Mathew’, ‘ew’’) From Dual;
Output: Math

LTRIM (String, ‘Characters to be trimmed from the left end’ )


Select LTRIM (‘Mathew’, ‘m’’) From Dual;
Output: athew

SOUNDEX (String)
Select Ename From EMP Where SOUNDEX (Ename) = SOUNDEX (Smyth);
Output: SMITH

SUBSTR (String, Start, Count )


Select SUBSTR (‘Mathew’, 2, 2) From Dual;
Output: at

INSTR (String, What to search, Start, Occurrence )


Select INSTR (‘Mathew’, ‘t’) From Dual;
Output: 3
Select INSTR (‘Mathew’, ‘T’) From Dual;
Output: 0

Thampy Mathew 45
Oracle Complete – A Quick Reference
SQL
Select INSTR (‘Smith’, ‘t’) From Dual;
Output: 4

ASCII (Value)
Select ASCII (65) From Dual;
Output: A
Select ASCII (‘A’) From Dual;
Output: 65
Select ASCII (‘a’) From Dual;
Output: 97
Select ASCII (‘AMIT’) From Dual;
Output: 65
Select ASCII (‘aMIT’) From Dual;
Output: 97

CHR (Value)
Select CHR (65) From Dual;
Output: A
Select CHR (‘65’) From Dual;
Output: A

REPLACE (String, What to replace, Replace with what )


Select REPLACE (‘Jack and Jue’, ‘ue’, ‘ill’) From Dual;
Output: Jack and Jill

USER
Select USER From Dual;
Output: SCOTT

Combined Use of functions


Select RPAD (LPAD (SUBSTR (‘AMIT’, 2, 3), 4, ‘S’), 5, ‘H’) From Dual;
Output: SMITH

Order of Firing
SUBSTR(‘AMIT’, 2, 3) = MIT
LPAD(‘MIT’, 4, ‘S’) = SMIT
RPAD(‘SMIT’, 5, ‘H’) = SMITH

Number Functions
ABC (Value)
Select ABS (-12) From Dual;

Thampy Mathew 46
Oracle Complete – A Quick Reference
SQL
Output: 12

FLOOR (Value)
Select FLOOR (14.6) From Dual;
Output: 14
Select FLOOR (-14.3) From Dual;
Output: 15

ROUND (Value, Precision)


Select ROUND (14.687, 0) From Dual;
Output: 15
Select ROUND (14.687, 1) From Dual;
Output: 14.7

TRUNC (Value, Precision)


Select ROUND (14.687, 1) From Dual;
Output: 14.6

MOD (Value, Divisor)


Select MOD (10, 2) From Dual;
Output: 0
Select MOD (100, 0) From Dual;
Output: 100
Select MOD (0, 100) From Dual;
Output: 0

POWER (Value, Exponent)


Select POWER (10, 2) From Dual;
Output: 100

SQRT (Value)
Select SQRT (100) From Dual;
Output: 10

SIGN (Value)
Select SIGN (100) From Dual;
Output: 1
Select SIGN (-100) From Dual;
Output: -1
Select SIGN (0) From Dual;
Output: 0

NVL (Value, Substitution)


Select Sal + NVL (Comm, 0) From EMP;
Output: All records in the Comm column having Null values will be
substituted with 0 and 0 will be added to the Sal. If NVL is not

Thampy Mathew 47
Oracle Complete – A Quick Reference
SQL
used, the Sal of all those employees whose Comm field is null will
not be displayed at all

Select Sal + NVL (Comm, Sal*0.10) From EMP;


Output: This will add 10% commission to all those employees whose
commission field is Null.

Group Functions
SUM (Value)
Select SUM (Sal) From EMP;
Output: Total of the Sal Column of EMP table

SUM (Value)
Select SUM (Sal + Comm) From EMP;
Output: Total of the Sal + Comm - Records with null values in Comm
field will be omitted.

Select SUM (Sal + NVL(Comm, 0)) From EMP;


Output: Total of the Sal + Comm - Records with null values in Comm
field will be included.

MIN (Value)
Select MIN (Sal), MIN(Ename) From EMP;
Output:

MAX (Value)
Select MAX (Sal), MAX(Ename) From EMP;
Output:

AVG (Value)
Select AVG (Sal) From EMP;
Output: Average of the salary
Select AVG (Comm) From EMP;
Output: Average of the Comm column excluding null fields
Select AVG (NVL(Comm, 0)) From EMP;
Output: Average of the Comm column including null fields

COUNT (Value)
Select COUNT (*), COUNT (Comm), COUNT (NVL(Comm, 0)) From EMP;
Output: No. of total records, No. of records in Comm column without Null
and No. of records in Comm column (with and without null)

Thampy Mathew 48
Oracle Complete – A Quick Reference
SQL
Date Functions
The Full Date Format

'DD-MON-YYYY HH:MI:SS'
'DD-MON-YYYY HH12:MI:SS'
'DD-MON-YYYY HH24:MI:SS'

LAST_DAY (Date) The end date of the month of a given date.


Select LAST_DAY (Sysdate) From Dual;
Output: 30-NOV-99 The command is executed on 25-NOV-99

NEXT_DAY (Date, Day) Date of the mentioned day in the next week
Select NEXT_DAY (Sysdate, ‘Friday’) From Dual;
Output: 03-NOV-99 The command is executed on 25-NOV-99

ADD_MONTHS (Date, How much to add)


Select ADD_MONTHS (Sysdate, 3) From Dual;
Output: 25-FEB-99 The command is executed on 25-NOV-99

MONTHS_BETWEEN (From Date, To Date)


Select ADD_MONTHS (Sysdate, 25-NOV-99) From Dual;
Output: 3 The command is executed on 25-NOV-99

NEW_TIME(Date 'this', 'other')

Time Zones

AST Atlantic Standard Time


ADT Atlantic Daylight Time

BST Bering Standard Time


BDT Bering Daylight Time

CST Central Standard Time


CDT Central Daylight Time

EST Eastern Standard Time


EDT Eastern Daylight Time

GMT Greenwich Mean Time

HST Alaska-Hawali Standard Time


HDT Alaska-Hawali Daylight Time

Thampy Mathew 49
Oracle Complete – A Quick Reference
SQL
MST Mountain Standard Time
MDT Mountain Daylight Time

NST Newfoundland Standard Time

PST Pacific Standard Time


PDT Pacific Daylight Time

YST Yukon Standard Time


YDT Yukon Daylight Time

Alter Session Set NLS_DATE_FORMAT = 'DD-MON-YYYY HH24:MI:SS'

Select NEW_TIME(Sysdate, 'EST', 'GMT') From Dual;


Output:23-JUL-2003 22:26:36

Select NEW_TIME(Sysdate, 'EST', 'AST') From Dual;


Output:23-JUL-2003 18:27:07

Select NEW_TIME(Sysdate, 'EST', 'ADT') From Dual;


Output:23-JUL-2003 19:27:18

Conversion Functions
TO_NUMBER (From Date, To Date)
Select TO_NUMBER (‘12’) From Dual;
Output: 12 The numeric 12

TO_CHAR (From Date, To Date)


Select TO_CHAR (Sysdate, ‘Day’) From Dual;
Output: thursday

TO_CHAR (From Date, To Date)


Select TO_CHAR (Sysdate, ‘Month’) From Dual;
Output: november

TO_CHAR (From Date, To Date)


Select TO_CHAR (Sysdate, ‘Year’) From Dual;
Output: nineteen ninty-nine

TO_CHAR (From Date, To Date)


Select TO_CHAR (Sysdate, ‘Day-Month-Year’) From Dual;

Thampy Mathew 50
Oracle Complete – A Quick Reference
SQL
Output: Thursday-november-ninteen ninty nine

TO_CHAR (Date, Format)


Select TO_CHAR (Sysdate, ‘Day-Month-YYSP’) From Dual;
Output: Thursday-november-ninteen ninty nine

TO_DATE (Date String, Format)


Select TO_DATE (Sysdate) From Dual;
Output: 25-NOV-99

Select TO_DATE (‘25/NOV/99’) From Dual;


Output: 25-NOV-99

Combined Use of TO_CHAR, TO_DATE

Select TO_CHAR(TO_DATE (‘28/NOV/99’), ‘Day’) From Dual;


Output: Sunday

TO_DATE converts the input value into a date value. ‘Day’ extracts the day value
from the date value and TO_CHAR converts the day value into characters and
displayed.

Format Strings for TO_CHAR.

The below given format strings will not work with TO_DATE

Fm Without fm the Month and Day will be displayed in the same width. With
fm Months and Days are only as long as their count of characters.

Fx Specifies exact format matching for the character argument and the date
format model.

TH Sufix to a number. ddTH or DDTH produces 24th or 24TH. Capitalization


comes from the number-DD- no fro the case of TH. Works with any
number in a date. YYYY, DD, MM, HH, MI, SS and so on.

SP Suffix to a number that forces number to be specified out. DDSP, DdSP or


ddSP THREE, Three or three. Capitalization comes from the number-DD-
no fro the case of SP. Works with any number in a date. YYYY, DD, MM,
HH, MI, SS and so on.

SPTH Suffix combination of TH and SP that forces number to be both spelled


out and given an ordinal suffix. Mmspth produces Third. Capitalization

Thampy Mathew 51
Oracle Complete – A Quick Reference
SQL
comes from the number-DD- no fro the case of SP. Works with any
number in a date. YYYY, DD, MM, HH, MI, SS and so on.

Use of fm With Month in TO_CHAR

Select TO_CHAR(Sysdate, 'Month'),


LENGTH(TO_CHAR(Sysdate, 'Month')) From Dual;

Output: July 9

Select TO_CHAR(Sysdate, 'Month'),


LENGTH(TO_CHAR(Sysdate, 'fmMonth')) From Dual;

Output: July 4

Use of fm With Day in TO_CHAR

Select TO_CHAR(TO_DATE('20-JUL-03'), 'Day'),


LENGTH(TO_CHAR(TO_DATE('20-JUL-03'), 'Day')) From Dual;

Output: Sunday 9

Select TO_CHAR(TO_DATE('20-JUL-03'), 'Day'),


LENGTH(TO_CHAR(TO_DATE('20-JUL-03'), 'fmDay')) From Dual;

Output: Sunday 6

Date in Words
Select TO_CHAR(Sysdate, 'year') From Dual;
Output: two thousand three

Select TO_CHAR(Sysdate, 'Year') From Dual;


Output: Two Thousand Three

Select TO_CHAR(Sysdate, 'YEAR') From Dual;


Output: TWO THOUSAND THREE

Select TO_CHAR(TO_DATE('25/JUL/03'), 'Year') From Dual;


Output: Two Thousand Three

Select TO_CHAR(Sysdate, 'month') From Dual;

Thampy Mathew 52
Oracle Complete – A Quick Reference
SQL
Output: july

Select TO_CHAR(Sysdate, 'Month') From Dual;


Output: July

Select TO_CHAR(Sysdate, 'MONTH') From Dual;


Output: JULY

Select TO_CHAR(Sysdate, 'day') From Dual;


Output: wednesday

Select TO_CHAR(Sysdate, 'Day') From Dual;


Output: Wednesday

Select TO_CHAR(Sysdate, 'DAY') From Dual;


Output: WEDNESDAY

Use of TH in TO_CHAR

Select TO_CHAR(Sysdate, 'ddth-MON-YY') From Dual;


Output: 23rd-JUL-03

Select TO_CHAR(Sysdate, 'DDth-MMth-YY') From Dual;


Output: 23RD-07TH-03

Use of SP in TO_CHAR

Select TO_CHAR(Sysdate, 'DdSP-MM-YYYY') From Dual;


Output: Twenty-Three-07-2003

Select TO_CHAR(Sysdate, 'DdSP-MmSP-YYYY') From Dual;


Output: Twenty-Three-Seven-2003

Select TO_CHAR(Sysdate, 'DdSP-MmSP-YyyySP') From Dual;


Output: Twenty-Three-Seven-Two Thousand Three

Combined Use of DDSPTH in TO_CHAR

Select TO_CHAR(Sysdate, 'DDSPTH-MONTH-YEAR') From Dual;


Output: TWENTY-THIRD-JULY -TWO THOUSAND THREE

Select TO_CHAR(Sysdate, 'DDSPTH-Month-Year') From Dual;


Output: TWENTY-THIRD-July -Two Thousand Three

Select TO_CHAR(Sysdate, 'DdSPth-Month-Year') From Dual;

Thampy Mathew 53
Oracle Complete – A Quick Reference
SQL
Output: Twenty-Third-July -Two Thousand Three

Select TO_CHAR(Sysdate, 'Ddspth-Month-Year') From Dual;


Output: Twenty-Third-July -Two Thousand Three

ROUND Function with Dates


ROUND (Date String, Format)
Without format specified, rounds a date to 12 A.M. (midnight, he beginning of
that day) if time of date is before noon; otherwise rounds t next day.

Formats
cc, scc - rounds to January 1st of next century

year, y, yy, yyy,yyyy - rounds to 1st January of next year

q - rounds to the 1st of next quarter

month, mon, mm - rounds to the 1st of next month

ww - rounds to the closest Monday

w - rounds to closest day which is the same day as the first


day of the month.

ddd, dd, j - rounds to the next day as of noon

day, dy, d - rounds to next Sunday (first day of the week)

hh,hh12, hh24 - rounds to the next whole hour

mi - rounds to the next whole minute

Rounding To Century

Select ROUND(TO_DATE('25/JUL/2049'), 'CC') From Dual;


Output: 01-JAN-2000 12:00:00

Select ROUND(TO_DATE('25/JUL/2050'), 'CC') From Dual;


Output: 01-JAN-2100 12:00:00

Rounding To Year

Thampy Mathew 54
Oracle Complete – A Quick Reference
SQL
Select ROUND(TO_DATE('25/JUL/2050 8:15:00 a.m.'), 'Year') From Dual;
Output: 01-JAN-2051 12:00:00

Select ROUND(TO_DATE('25/MAY/2049 8:15:00 p.m.'), 'Year') From Dual;


Output: 01-JAN-2049 12:00:00

Rounding To Quarter

Select ROUND(TO_DATE('12/FEB/2050 8:15:00 p.m.'), 'q') From Dual;


Output: 01-JAN-2050 12:00:00

Select ROUND(TO_DATE('15/FEB/2050 8:15:00 p.m.'), 'q') From Dual;


Output: 01-JAN-2050 12:00:00

Select ROUND(TO_DATE('16/FEB/2050 8:15:00 p.m.'), 'q') From Dual;


Output: 01-APR-2050 12:00:00

Rounding To Month

Select ROUND(TO_DATE('14/FEB/2050 8:15:00 p.m.'), 'month') From Dual;


Output: 01-FEB-2050 12:00:00

Select ROUND(TO_DATE('15/FEB/2050 8:15:00 p.m.'), 'month') From Dual;


Output: 01-FEB-2050 12:00:00

Select ROUND(TO_DATE('16/FEB/2050 8:15:00 p.m.'), 'month') From Dual;


Output: 01-MAR-2050 12:00:00

Rounding To The Year-Start-Day to Year-Start-Day Week

Select ROUND(TO_DATE('22/JUL/2003 8:15:00 p.m.'), 'ww') From Dual;


Output: 23-JUL-2003 12:00:00

The Input 22-JUL-2003 is a Tuesday.


The Year Stat Date 01-JAN-2003 is a Wednesday.
Wednesday to Wednesday Week in which the input date falls is
16-JUL-2003 to 23-JUL-2003.
23-JUL-2003 is the Nearer Wednesday of the week for the input date of
22-JUL-2003 and so is the Output.

Select ROUND(TO_DATE('19/JUL/2003 8:15:00 a.m.'), 'ww') From Dual


Output: 16-JUL-2003 12:00:00

The Input 19-JUL-2003 is a Saturday.


The Year Stat Date 01-JAN-2003 is a Wednesday.

Thampy Mathew 55
Oracle Complete – A Quick Reference
SQL
Wednesday to Wednesday Week in which the input date falls is
16-JUL-2003 to 23-JUL-2003.
16-JUL-2003 is the Nearer Wednesday of the week for the input date of
19-JUL-2003 and so is the Output.

Rounding To The Month-Start-Day to Month-Start-Day Week

Select ROUND(TO_DATE('19/JUL/2003 8:15:00 a.m.'), 'w') From Dual;


Output:22-JUL-2003 12:00:00

The Input 19-JUL-2003 is a Saturday.


The Month Start Date 01-JUL-2003 is a Tuesday.
Tuesday to Tuesday Week in which the input date falls is
15-JUL-2003 to 22-JUL-2003.
22-JUL-2003 is the Nearer Wednesday of the week for the input date of
19-JUL-2003 and so is the Output.

Select ROUND(TO_DATE('14/JUL/2003 8:15:00 a.m.'), 'w') From Dual;


Output:15-JUL-2003 12:00:00

The Input 14-JUL-2003 is a Monday.


The Month Start Date 01-JUL-2003 is a Tuesday.
Tuesday to Tuesday Week in which the input date falls is
08-JUL-2003 to 15-JUL-2003.
15-JUL-2003 is the Nearer Wednesday of the week for the input date of
14-JUL-2003 and so is the Output.

Select ROUND(TO_DATE('17/JUL/2003 8:15:00 a.m.'), 'w') From Dual;


Output:15-JUL-2003 12:00:00

The Input 17-JUL-2003 is a Monday


The Month Start Date 01-JUL-2003 is a Tuesday
Tuesday to Tuesday Week in which the input date falls is
15-JUL-2003 to 22-JUL-2003
15-JUL-2003 is the Nearer Wednesday of the week for the input
17-JUL-2003 and so is the Output.

Rounding To Day

Select ROUND(TO_DATE('12/FEB/2050 8:15:00 p.m.'), 'dd') From Dual;


Output: 12-FEB-2050 12:00:00

Select ROUND(TO_DATE('12/FEB/2050 8:15:00 a.m.'), 'dd') From Dual;

Thampy Mathew 56
Oracle Complete – A Quick Reference
SQL
Output: 12-FEB-2050 12:00:00

Rounding To Sunday (The First Day of a Week)

Select ROUND(TO_DATE('12/FEB/2050 8:15:00 a.m.'), 'day') From Dual;


Output: 13-FEB-2050 12:00:00

Select ROUND(TO_DATE('12/FEB/2050 8:15:00 p.m.'), 'day') From Dual;


Output: 13-FEB-2050 12:00:00

Rounding To Hour

Select ROUND(TO_DATE('12/FEB/2050 8:15:00 p.m.'), 'hh') From Dual;


Output: 12-FEB-2050 08:00:00

Select ROUND(TO_DATE('12/FEB/2050 8:30:00 p.m.'), 'hh') From Dual;


Output: 12-FEB-2050 09:00:00

Rounding To Minute

Select ROUND(TO_DATE('12/FEB/2050 8:30:29 p.m.'), 'mi') From Dual;


Output: 12-FEB-2050 08:30:00

Select ROUND(TO_DATE('12/FEB/2050 8:30:30 p.m.'), 'mi') From Dual;


Output: 12-FEB-2050 08:31:00

TRUNC Function with Dates

TRUNC (Date String, Format)


Without format specified, sets a date to 12 A.M. (midnight, he beginning of that
day)

Formats

cc, scc - truncates to January 1st of current century

year, y, yy, yyy,yyyy - truncates to 1st January of next year

q - truncates to the 1st of next quarter

month, mon, mm - truncates to the 1st of next month

Thampy Mathew 57
Oracle Complete – A Quick Reference
SQL
ww - truncates to the closest Monday

w - truncates to closest day which is the same day as the first


day of the month.

ddd, dd, j - truncates to the next day as of noon

day, dy, d - truncates to next Sunday (first day of the week)

hh,hh12, hh24 - truncates to the next whole hour

mi - truncates to the next whole minute

Truncating To Century

Select TRUNC(TO_DATE('22/JUL/2003 15:30:00'), 'cc') From Dual;


Output: 01-JAN-2000 00:00:00

Select TRUNC(TO_DATE('22/JUL/2099 15:30:00'), 'cc') From Dual;


Output: 01-JAN-2000 00:00:00

Truncating To Year

Select TRUNC(TO_DATE('22/MAR/2003 15:30:00'), 'Year') From Dual;


Output: 01-JAN-2003 00:00:00

Select TRUNC(TO_DATE('22/AUG/2003 15:30:00'), 'Year') From Dual;


Output: 01-JAN-2003 00:00:00

Truncating To Quarter

Select TRUNC(TO_DATE('22/JAN/2003 15:30:00'), 'q') From Dual;


Output: 01-JAN-2003 00:00:00

Select TRUNC(TO_DATE('22/MAR/2003 15:30:00'), 'q') From Dual;


Output: 01-JAN-2003 00:00:00

Truncating To Month

Select TRUNC(TO_DATE('10/MAR/2003 15:30:00'), 'Month') From Dual;


Output: 01-MAR-2003 00:00:00

Thampy Mathew 58
Oracle Complete – A Quick Reference
SQL
Select TRUNC(TO_DATE('22/MAR/2003 15:30:00'), 'Month') From Dual;
Output: 01-MAR-2003 00:00:00

Truncating To The Year-Start-Day to Year-Start-Day Week

Select TRUNC(TO_DATE('22/JUL/2003 15:30:00'), 'ww') From Dual;


Output: 16-JUL-2003 00:00:00

Input Date 22-JUL-2003 is a Tuesday.


Year Start Day is a Wednesday.
Wednesday to Wednesday Week in which the input date falls is
16-JUL-2003 to 23-JUL-2003.
Lowest Date of the Above Week 16-JUL-2003 is the Output

Select TRUNC(TO_DATE('24/JUL/2003 15:30:00'), 'ww') From Dual;


Output: 23-JUL-2003 00:00:00

Input Date 23-JUL-2003 is a Thursday.


Year Start Day is a Wednesday.
Wednesday to Wednesday Week in which the input date falls is
23-JUL-2003 to 30-JUL-2003.
Lowest Date of the Above Week 23-JUL-2003 is the Output.

Truncating To The Month-Start-Day to Month-Start-Day Week

Select TRUNC(TO_DATE('21/JUL/2003 15:30:00'), 'w') From Dual;


Output: 15-JUL-2003 00:00:00

Input Date 21-JUL-2003 is a Monday.


Month Start Day is a Tuesday.
Tuesday to Tuesday Week in which the input date falls is
15-JUL-2003 to 22-JUL-2003.
Lowest Date of the Above Week 15-JUL-2003 is the Output

Select TRUNC(TO_DATE('23/JUL/2003 15:30:00'), 'w') From Dual;


Output: 22-JUL-2003 00:00:00

Input Date 23-JUL-2003 is a Wednesday.


Month Start Day is a Tuesday.
Tuesday to Tuesday Week in which the input date falls is
22-JUL-2003 to 29-JUL-2003.
Lowest Date of the Above Week 22-JUL-2003 is the Output.

Thampy Mathew 59
Oracle Complete – A Quick Reference
SQL
Truncating to Day

Select TRUNC(TO_DATE('23/JUL/2003 10:30:00'), 'dd') From Dual;


Output: 23-JUL-2003 00:00:00

Select TRUNC(TO_DATE('23/JUL/2003 23:30:00'), 'dd') From Dual;


Output: 23-JUL-2003 00:00:00

Truncating To Sunday (The First Day of a Week)

Select TRUNC(TO_DATE('23/JUL/2003 06:30:00'), 'Day') From Dual;


Output: 20-JUL-2003 00:00:00 /* Sunday */

Select TRUNC(TO_DATE('26/JUL/2003 23:30:00'), 'Day') From Dual;


Output: 20-JUL-2003 00:00:00 /* Sunday */

Truncating To Hour

Select TRUNC(TO_DATE('26/JUL/2003 23:30:00'), 'hh24') From Dual;


Output: 26-JUL-2003 23:00:00

Select TRUNC(TO_DATE('26/JUL/2003 23:29:00'), 'hh24') From Dual;


Output: 26-JUL-2003 23:00:00

Truncating To Minute

Select TRUNC(TO_DATE('26/JUL/2003 12:15:30'), 'mi') From Dual;


Output: 26-JUL-2003 12:15:00

Select TRUNC(TO_DATE('26/JUL/2003 12:15:29'), 'mi') From Dual;


Output: 26-JUL-2003 12:15:00

GREATEST and LEAST Functions With Date


If Greatest and Least functions are used to compare two dates, ensure that
TO_DATE function is used with it as both Greatest and Least functions will treat
the input date as strings.

Date Calculations
Select Sysdate + 1 From Dual;
Output: Tomorrow’s date

Thampy Mathew 60
Oracle Complete – A Quick Reference
SQL
Select Sysdate - 1 From Dual;
Output: Yesterday’s date

Select Sysdate - Hiredate From EMP;


Output: Number of days of service.

Select (Sysdate – Hiredate) / 365 From EMP;


Output: Number of years of service.

Transormation Functions
DECODE (Value, If 1, Then 1, If 2. Then 2,……If n, Then n)
Select DECODE (Ename, NULL, ‘No Name’) From EMP;

TRANSLATE (String, Characters to be replaced, Replace with what characters )


Select REPLACE (‘abcXPORS’, ‘aXO’, ‘MNo’) From Dual;
Output: MbcNPoRS
Select REPLACE (‘Ename’, ‘S’, ‘T’) From EMP;
Select REPLACE (‘Ename’, ‘SM’, ‘T’) From EMP;

Converting Figures into Words


Select Sal To_Char(To_Date(Sal, ‘J’), ‘JSP’) From EMP;

Changing the Environmental Settings of a Session


Alter Session Set Date_Format = ‘DD-MON-YY’;
Alter Session Set Date_Format = ‘dd-mon-yy’;
Alter Session Set Date_Format = ‘Dd-Mon-YY’;
Alter Session Set Date_Format = ‘DD-MON-YYYY’;
Alter Session Set Date_Format = ‘dd-mon-yyyy’;
Alter Session Set Date_Format = ‘Dd-Mon-Yyyy’;

Alter Session Set Date_Format = ‘Dd-Mon-Yyyy-Day’;

Alter Session Set Date_Format = ‘DD-MON-YY HH:MI:SS’;


Alter Session Set Date_Format = ‘DD-MON-YY HH12:MI:SS’;
Alter Session Set Date_Format = ‘DD-MON-YY HH24:MI:SS’;

Thampy Mathew 61
Oracle Complete – A Quick Reference
SQL

Pseudocolumns
ROWID
ROWMUM
LEVEL
NEXTVAL
CURRVAL

ROWID
It is independent of tables. When a record is inserted into a table Oracle will attach a
ROWID to the Data Segment. A ROWID is constituted of 3 segments as follows.
ROWID will be unique for each record irrespective of the Table in which it belongs.

Segment Represents
1 Block (Table) – where the record is physically present
2 Data File Name – where the Data Segment is present
3 Row Number

Example:

AAAFBtAADAABNwAAA

AAAFBt - Block (Table) Name


AADAABNw - Data File (Data Segment) Name
AAA - Row Number

ROWMUM

Rownum is generated only when a select statement starts fetching records. The
ROWNUM values are never saved to the database.

Select Rownum, Ename from EMP where Rownum = 1 - (It will work)

Select Rownum, Ename from EMP where Rownum = 2 - (It will not work)

Select Rownum, Ename from EMP where Rownum < 1 - (It will work)

Select Rownum, Ename from EMP where Rownum > 1 - (It will work)

Thampy Mathew 62
Oracle Complete – A Quick Reference
SQL
LEVEL

It indicates the level of a hierarchy


It is used in TREE STRUCTURE Queries

(Refer TREE STRCTURE Queries)

NEXTVAL

This is used to fetch the next value of a Sequence.

CURRVAL

This is used to fetch the current value of a Sequence.

Queries
Simple Queries

Tables Used in Examples


The DEPT Table

Create Table DEPT


(DEPTNO NUMBER(2) Primary Key,
DNAME VARCHAR2(14),
LOC VARCHAR2(13));

The EMP Table

Create Table EMP


(EMPNO NUMBER(4) Primary Key,
ENAME VARCHAR2(10),
JOB VARCHAR2(9),
MGR NUMBER(4),
HIREDATE DATE
SAL NUMBER(7,2),
COMM NUMBER(7,2),
DEPTNO NUMBER(2) References DEPT(DEPTNO));

Thampy Mathew 63
Oracle Complete – A Quick Reference
SQL
Records in DEPT Table

DEPTNO DNAME LOC


------ -------------- ----------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON

Records in EMP Table

EMPNOENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------------------- ------- ----- --------- ------- ----- --------- ------------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7566 JONES MANAGER 7839 02-APR-81 2975 20
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7839 KING PRESIDENT 17-NOV-81 5000 10
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7900 JAMES CLERK 7698 03-DEC-81 950 30
7902 FORD ANALYST 7566 03-DEC-81 3000 20

Select * From EMP;

Output:
EMPNOENAME JOB MGR HIREDATE SAL COMM DEPTNO
--------------------- ------- ----- --------- ------- ----- --------- ------------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7566 JONES MANAGER 7839 02-APR-81 2975 20
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7839 KING PRESIDENT 17-NOV-81 5000 10
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7900 JAMES CLERK 7698 03-DEC-81 950 30
7902 FORD ANALYST 7566 03-DEC-81 3000 20

Thampy Mathew 64
Oracle Complete – A Quick Reference
SQL
Select Ename From EMP;

Output:
ENAME
-------
SMITH
ALLEN
JONES
MARTIN
BLAKE
CLARK
SCOTT
KING
TURNER
ADAMS
JAMES
FORD

Select Ename, Sal From EMP;

Output:
ENAME SAL
---------- ---------
SMITH 800
ALLEN 1600
JONES 2975
MARTIN 1250
BLAKE 2850
CLARK 2450
SCOTT 3000
KING 5000
TURNER 1500
ADAMS 1100
JAMES 950
FORD 3000

Changing the Order of Columns

Select Sal, Ename From Emp;

Output:
SAL ENAME
------ ----------
800 SMITH

Thampy Mathew 65
Oracle Complete – A Quick Reference
SQL
1600 ALLEN
2975 JONES
1250 MARTIN
2850 BLAKE
2450 CLARK
3000 SCOTT
5000 KING
1500 TURNER
1100 ADAMS
950 JAMES
3000 FORD

Conditional Output

Select Ename, Sal


From EMP
Where Ename = 'James';

Output:
no rows selected

Note:
The strings James and JAMES are different for SQL.

Select Ename, Sal


From EMP
Where Ename = 'JAMES';

Output:
ENAME SAL
---------- ---------
JAMES 950

Select Ename, Sal


From EMP
Where Ename = 'JA%';

Output:
no rows selected

Using LIKE

Select Ename, Sal


From EMP

Thampy Mathew 66
Oracle Complete – A Quick Reference
SQL
Where Ename Like 'JA%';

Output:
ENAME SAL
---------- ---------
JAMES 950

Select Ename, Sal


From EMP
Where Ename Like '%AR%';

Output:
ENAME SAL
---------- ---------
MARTIN 1250
CLARK 2450

Select Ename, Sal


From EMP
Where Ename Like '%ES';

Output:
ENAME SAL
---------- ---------
JONES 2975
JAMES 950

Select Ename, Sal


From EMP
Where Ename Like '%A%K%';

Output:
ENAME SAL
---------- ---------
BLAKE 2850
CLARK 2450

Using NOT LIKE

Select Ename, Sal


From EMP
Where Ename Not Like 'JAMES';

Thampy Mathew 67
Oracle Complete – A Quick Reference
SQL
Output:
ENAME SAL
---------- ---------
SMITH 800
ALLEN 1600
JONES 2975
MARTIN 1250
BLAKE 2850
CLARK 2450
SCOTT 3000
KING 5000
TURNER 1500
ADAMS 1100
FORD 3000

Notice that JAMES is excluded.

Select Ename, Sal


From EMP
Where Ename Not Like '%A%';

Output:
ENAME SAL
---------- ---------
SMITH 800
JONES 2975
SCOTT 3000
KING 5000
TURNER 1500
FORD 3000

Note:
No records selected where Ename having an A in it.

Using NOT EQUAL TO (<> or !=)

Select Ename, Sal


From EMP
Where Ename <> 'JAMES';

Output:
ENAME SAL
---------- ---------
SMITH 800
ALLEN 1600

Thampy Mathew 68
Oracle Complete – A Quick Reference
SQL
JONES 2975
MARTIN 1250
BLAKE 2850
CLARK 2450
SCOTT 3000
KING 5000
TURNER 1500
ADAMS 1100
FORD 3000

Note:
JAMES is excluded from the output.

Select Ename, Sal


From EMP
Where Sal > 2450;

Output:
ENAME SAL
---------- ---------
JONES 2975
BLAKE 2850
SCOTT 3000
KING 5000
FORD 3000

Note:
Record with Sal = 2450 is not included.

Select Ename, Sal


From EMP
Where Sal >= 2450;

Output:
ENAME SAL
---------- ---------
JONES 2975
BLAKE 2850
CLARK 2450
SCOTT 3000
KING 5000
FORD 3000

Note:
Record with Sal = 2450 is included.

Thampy Mathew 69
Oracle Complete – A Quick Reference
SQL
Select Ename, Sal
From EMP
Where Sal < 2450;

Output:
ENAME SAL
---------- ---------
SMITH 800
ALLEN 1600
MARTIN 1250
TURNER 1500
ADAMS 1100
JAMES 950

Note:
Record with Sal = 2450 is not included.

Select Ename, Sal


From EMP
Where Sal <= 2450;

Output:
ENAME SAL
---------- ---------
SMITH 800
ALLEN 1600
MARTIN 1250
CLARK 2450
TURNER 1500
ADAMS 1100
JAMES 950

Note:
Record with Sal = 2450 is included.

Using BETWEEN

Select Ename, Sal


From EMP
Where Sal Between 1250 And 2450;

Output:
ENAME SAL
---------- ---------
ALLEN 1600
MARTIN 1250

Thampy Mathew 70
Oracle Complete – A Quick Reference
SQL
CLARK 2450
TURNER 1500

Note:
Records with Sal = 1250 and 2450 are included.

BETWEEN will always be followed by AND.

Using NOT BETWEEN

Select Ename, Sal


From EMP
Where Sal Not Between 1250 And 2450;

Output:
ENAME SAL
---------- ---------
SMITH 800
JONES 2975
BLAKE 2850
SCOTT 3000
KING 5000
ADAMS 1100
JAMES 950
FORD 3000

Note:
Records with Sal = 1250 and 2450 are also excluded.

Replacing BETWEEN with >= and <=

Select Ename, Sal


From EMP
Where Sal >= 1250 And Sal <= 2450;

Output:
ENAME SAL
---------- ---------
ALLEN 1600
MARTIN 1250
CLARK 2450
TURNER 1500

Thampy Mathew 71
Oracle Complete – A Quick Reference
SQL
Using Aliases for Column Names

Select Ename Employee, Sal Salary, Sal * 2 Double


From EMP
Where Ename = 'SMITH';

Output:
EMPLOYEE SALARY DOUBLE
---------- --------- ---------
SMITH 800 1600

Note:
Notice that the column names are replaced with the aliases in the output.

Select Ename, Sal, '--------' Sign_Here


From EMP;

Output:
ENAME SAL SIGN_HERE
---------- --------- ------------
SMITH 800 ------------
ALLEN 1600 ------------
JONES 2975 ------------
MARTIN 1250 ------------
BLAKE 2850 ------------
CLARK 2450 ------------
SCOTT 3000 ------------
KING 5000 ------------
TURNER 1500 ------------
ADAMS 1100 ------------
JAMES 950 ------------
FORD 3000 ------------

Caution:
Do not use spaces in Aliases and do not insert coma between the field name and
the alias.

Taking User Input

Select Ename Employee, Sal Salary, Sal * 2 Double


From EMP

Thampy Mathew 72
Oracle Complete – A Quick Reference
SQL
Where Ename = '&Name';

Output:
Enter value for name: CLARK
old 2: From EMP Where Ename = '&Name'
new 2: From EMP Where Ename = 'CLARK'

EMPLOYEE SALARY DOUBLE


---------- --------- ---------
CLARK 2450 4900

Note:
When the query is executed, the system asked
Enter value for name:
The user entered the value CLARK
Then the output is shown.

Select Ename, Sal, Sal / 2 Half


From EMP
Where Ename = 'SMITH';

Output:
ENAME SAL HALF
---------- ------- ---------
SMITH 800 400

Multiple Conditions

Using AND

Select Ename, Sal


From EMP
Where Ename = 'SMITH'
And Sal = 900;

Output:
no rows selected

Select Ename, Sal


From EMP
Where Ename = 'SMITH'
And Sal = 800;

Thampy Mathew 73
Oracle Complete – A Quick Reference
SQL
Output:
ENAME SAL
---------- ---------
SMITH 800

Using OR

Select Ename, Sal


From EMP
Where Ename = 'SMITH'
Or Sal = 900;

Output:
ENAME SAL
---------- ---------
SMITH 800

Select Ename, Sal


From EMP
Where Ename = 'SMITH'
Or Sal = 2450;

Output:
ENAME SAL
---------- ---------
SMITH 800
CLARK 2450

Using IN

Select Ename, Hiredate


From EMP
Where Ename In ('SMITH', 'JONES', 'CLARK');

Output:
ENAME HIREDATE
--------- ---------
SMITH 17-DEC-80
JONES 02-APR-81
CLARK 09-JUN-81

Thampy Mathew 74
Oracle Complete – A Quick Reference
SQL
Using NOT IN

Select Ename, Hiredate


From EMP
Where Ename Not In ('SMITH', 'JONES', 'CLARK');

Output:
ENAME HIREDATE
---------- ---------
ALLEN 20-FEB-81
MARTIN 28-SEP-81
BLAKE 01-MAY-81
SCOTT 19-APR-87
KING 17-NOV-81
TURNER 08-SEP-81
ADAMS 23-MAY-87
JAMES 03-DEC-81
FORD 03-DEC-81

Note:
SMITH, JONES and CLARK are excluded.

Using ANY

Select Ename, Hiredate


From EMP
Where Ename = Any ('SMITH', 'JONES', 'CLARK');

Output:
ENAME HIREDATE
---------- ---------
SMITH 17-DEC-80
JONES 02-APR-81
CLARK 09-JUN-81

Select Ename, Sal


From EMP
Where Ename > Any (1500, 1700);

Output:
ENAME SAL
---------- ---------
ALLEN 1600
JONES 2975

Thampy Mathew 75
Oracle Complete – A Quick Reference
SQL
BLAKE 2850
CLARK 2450
SCOTT 3000
KING 5000
FORD 3000

Filtering Repeats Using UNIQUE

Select Ename, Distinct (Mgr)


From EMP;

Output:
ERROR Missing Expression.

Select Distinct (Mgr), Ename


From EMP;

Output:
MGR ENAME
---- -------
7566 FORD
7566 SCOTT
7698 ALLEN
7698 JAMES
7698 MARTIN
7698 TURNER
7788 ADAMS
7839 BLAKE
7839 CLARK
7839 JONES
7902 SMITH
KING

Select Distinct (Mgr)


From EMP;

Output:
MGR
-----
7566
7698
7788
7839
7902

Thampy Mathew 76
Oracle Complete – A Quick Reference
SQL
Managing NULLS

Select Ename, (Sal + Comm) Total


From EMP;

Output:
ENAME TOTAL
---------- ---------
SMITH
ALLEN 1900
JONES
MARTIN 2650
BLAKE
CLARK
SCOTT
KING
TURNER 1500
ADAMS
JAMES
FORD

Note:
When NULL is added to any value produces a NULL.

Select Ename, (Sal + NVL(Comm, 0)) Total


From EMP;

Output:
ENAME TOTAL
---------- ---------
SMITH 800
ALLEN 1900
JONES 2975
MARTIN 2650
BLAKE 2850
CLARK 2450
SCOTT 3000
KING 5000
TURNER 1500
ADAMS 1100
JAMES 950
FORD 3000

Thampy Mathew 77
Oracle Complete – A Quick Reference
SQL
Note:
The NULLs are substituted with 0 and added to Sal.

Formatting Dates

Select Ename, Hiredate, TO_CHAR (Hiredate, 'DD-MON-YYYY') Full_Year


From EMP;

Output:
ENAME HIREDATE FULL_YEAR
---------- --------- -----------
SMITH 17-DEC-80 17-DEC-1980
ALLEN 20-FEB-81 20-FEB-1981
JONES 02-APR-81 02-APR-1981
MARTIN 28-SEP-81 28-SEP-1981
BLAKE 01-MAY-81 01-MAY-1981
CLARK 09-JUN-81 09-JUN-1981
SCOTT 19-APR-87 19-APR-1987
KING 17-NOV-81 17-NOV-1981
TURNER 08-SEP-81 08-SEP-1981
ADAMS 23-MAY-87 23-MAY-1987
JAMES 03-DEC-81 03-DEC-1981
FORD 03-DEC-81 03-DEC-1981

Select Ename, Hiredate,


TO_CHAR (Hiredate, 'DD-MON-YYYY HH:MI:SS') DATE_WITH_TIME
From EMP;

Output:
ENAME HIREDATE DATE_WITH_TIME
---------- --------- --------------------
SMITH 17-DEC-80 17-DEC-1980 12:00:00
ALLEN 20-FEB-81 20-FEB-1981 12:00:00
JONES 02-APR-81 02-APR-1981 12:00:00
MARTIN 28-SEP-81 28-SEP-1981 12:00:00
BLAKE 01-MAY-81 01-MAY-1981 12:00:00
CLARK 09-JUN-81 09-JUN-1981 12:00:00
SCOTT 19-APR-87 19-APR-1987 12:00:00
KING 17-NOV-81 17-NOV-1981 12:00:00
TURNER 08-SEP-81 08-SEP-1981 12:00:00
ADAMS 23-MAY-87 23-MAY-1987 12:00:00
JAMES 03-DEC-81 03-DEC-1981 12:00:00
FORD 03-DEC-81 03-DEC-1981 12:00:00

Thampy Mathew 78
Oracle Complete – A Quick Reference
SQL
Select Ename, Hiredate,
TO_CHAR (Hiredate, 'DD-MON-YYYY HH12:MI:SS') TIME_IN_12HR_FORMAT
From EMP;

Output:
ENAME HIREDATE TIME_IN_12HR_FORMAT
---------- --------- --------------------
SMITH 17-DEC-80 17-DEC-1980 12:00:00
ALLEN 20-FEB-81 20-FEB-1981 12:00:00
JONES 02-APR-81 02-APR-1981 12:00:00
MARTIN 28-SEP-81 28-SEP-1981 12:00:00
BLAKE 01-MAY-81 01-MAY-1981 12:00:00
CLARK 09-JUN-81 09-JUN-1981 12:00:00
SCOTT 19-APR-87 19-APR-1987 12:00:00
KING 17-NOV-81 17-NOV-1981 12:00:00
TURNER 08-SEP-81 08-SEP-1981 12:00:00
ADAMS 23-MAY-87 23-MAY-1987 12:00:00
JAMES 03-DEC-81 03-DEC-1981 12:00:00
FORD 03-DEC-81 03-DEC-1981 12:00:00

Select Ename, Hiredate,


TO_CHAR (Hiredate, 'DD-MON-YYYY HH24:MI:SS') TIME_IN_24HR_FORMAT
From EMP;

Output:
ENAME HIREDATE TIME_IN_24HR_FORMAT
---------- --------- --------------------
SMITH 17-DEC-80 17-DEC-1980 12:00:00
ALLEN 20-FEB-81 20-FEB-1981 12:00:00
JONES 02-APR-81 02-APR-1981 12:00:00
MARTIN 28-SEP-81 28-SEP-1981 12:00:00
BLAKE 01-MAY-81 01-MAY-1981 12:00:00
CLARK 09-JUN-81 09-JUN-1981 12:00:00
SCOTT 19-APR-87 19-APR-1987 12:00:00
KING 17-NOV-81 17-NOV-1981 12:00:00
TURNER 08-SEP-81 08-SEP-1981 12:00:00
ADAMS 23-MAY-87 23-MAY-1987 12:00:00
JAMES 03-DEC-81 03-DEC-1981 12:00:00
FORD 03-DEC-81 03-DEC-1981 12:00:00

Thampy Mathew 79
Oracle Complete – A Quick Reference
SQL
Select Ename, Hiredate,
TO_CHAR (Hiredate, 'DD-MON-YYYY HH24:MI:SS pm')
TIME_IN_24HR_FORMAT
From EMP;

Output:
ENAME HIREDATE TIME_IN_12HR_FORMAT
---------- --------- --------------------
SMITH 17-DEC-80 17-DEC-1980 12:00:00 am
ALLEN 20-FEB-81 20-FEB-1981 12:00:00 am
JONES 02-APR-81 02-APR-1981 12:00:00 am
MARTIN 28-SEP-81 28-SEP-1981 12:00:00 am
BLAKE 01-MAY-81 01-MAY-1981 12:00:00 am
CLARK 09-JUN-81 09-JUN-1981 12:00:00 am
SCOTT 19-APR-87 19-APR-1987 12:00:00 am
KING 17-NOV-81 17-NOV-1981 12:00:00 am
TURNER 08-SEP-81 08-SEP-1981 12:00:00 am
ADAMS 23-MAY-87 23-MAY-1987 12:00:00 am
JAMES 03-DEC-81 03-DEC-1981 12:00:00 am
FORD 03-DEC-81 03-DEC-1981 12:00:00 am

Select Ename, Hiredate,


TO_CHAR (Hiredate, 'DD-MON-YYYY HH24:MI:SS am')
TIME_IN_24HR_FORMAT
From EMP;

Output:
ENAME HIREDATE TIME_IN_12HR_FORMAT
---------- --------- --------------------
SMITH 17-DEC-80 17-DEC-1980 12:00:00 am
ALLEN 20-FEB-81 20-FEB-1981 12:00:00 am
JONES 02-APR-81 02-APR-1981 12:00:00 am
MARTIN 28-SEP-81 28-SEP-1981 12:00:00 am
BLAKE 01-MAY-81 01-MAY-1981 12:00:00 am
CLARK 09-JUN-81 09-JUN-1981 12:00:00 am
SCOTT 19-APR-87 19-APR-1987 12:00:00 am
KING 17-NOV-81 17-NOV-1981 12:00:00 am
TURNER 08-SEP-81 08-SEP-1981 12:00:00 am
ADAMS 23-MAY-87 23-MAY-1987 12:00:00 am
JAMES 03-DEC-81 03-DEC-1981 12:00:00 am
FORD 03-DEC-81 03-DEC-1981 12:00:00 am

Thampy Mathew 80
Oracle Complete – A Quick Reference
SQL
Note:
Notice that with am and pm the Output is shown as am only because am is the
value present in the database.

Select Ename, Hiredate,


TO_CHAR (Hiredate, 'DD-MON-YYYY HH24:MI:SS A.M.')
TIME_IN_24HR_FORMAT
From EMP;

Output:
ENAME HIREDATE TIME_IN_12HR_FORMAT
---------- --------- --------------------
SMITH 17-DEC-80 17-DEC-1980 12:00:00 A.M.
ALLEN 20-FEB-81 20-FEB-1981 12:00:00 A.M.
JONES 02-APR-81 02-APR-1981 12:00:00 A.M.
MARTIN 28-SEP-81 28-SEP-1981 12:00:00 A.M.
BLAKE 01-MAY-81 01-MAY-1981 12:00:00 A.M.
CLARK 09-JUN-81 09-JUN-1981 12:00:00 A.M.
SCOTT 19-APR-87 19-APR-1987 12:00:00 A.M.
KING 17-NOV-81 17-NOV-1981 12:00:00 A.M.
TURNER 08-SEP-81 08-SEP-1981 12:00:00 A.M.
ADAMS 23-MAY-87 23-MAY-1987 12:00:00 A.M.
JAMES 03-DEC-81 03-DEC-1981 12:00:00 A.M.
FORD 03-DEC-81 03-DEC-1981 12:00:00 A.M.

Select Ename, Hiredate,


TO_CHAR (TO_DATE (Hiredate, 'DD-MON-YYYY'), 'YEAR') Year_In_Words
From EMP;

Output:
ENAME HIREDATE YEAR_IN_WORDS
---------- --------- --------------
SMITH 17-DEC-80 EIGHTY
ALLEN 20-FEB-81 EIGHTY-ONE
JONES 02-APR-81 EIGHTY-ONE
MARTIN 28-SEP-81 EIGHTY-ONE
BLAKE 01-MAY-81 EIGHTY-ONE
CLARK 09-JUN-81 EIGHTY-ONE
SCOTT 19-APR-87 EIGHTY-SEVEN
KING 17-NOV-81 EIGHTY-ONE
TURNER 08-SEP-81 EIGHTY-ONE
ADAMS 23-MAY-87 EIGHTY-SEVEN
JAMES 03-DEC-81 EIGHTY-ONE
FORD 03-DEC-81 EIGHTY-ONE

Thampy Mathew 81
Oracle Complete – A Quick Reference
SQL
Select Ename, Hiredate,
TO_CHAR (TO_DATE (Hiredate, 'DD-MON-YYYY'), 'Year') Year_In_Words
From EMP;

Output:
ENAME HIREDATE YEAR_IN_WORDS
---------- --------- -------------
SMITH 17-DEC-80 Eighty
ALLEN 20-FEB-81 Eighty-One
JONES 02-APR-81 Eighty-One
MARTIN 28-SEP-81 Eighty-One
BLAKE 01-MAY-81 Eighty-One
CLARK 09-JUN-81 Eighty-One
SCOTT 19-APR-87 Eighty-Seven
KING 17-NOV-81 Eighty-One
TURNER 08-SEP-81 Eighty-One
ADAMS 23-MAY-87 Eighty-Seven
JAMES 03-DEC-81 Eighty-One
FORD 03-DEC-81 Eighty-One

Select Ename, Hiredate,


TO_CHAR (TO_DATE (Hiredate, 'DD-MON-YYYY'), 'MONTH') Month
From EMP;

Output:
ENAME HIREDATE MONTH
---------- --------- ---------
SMITH 17-DEC-80 DECEMBER
ALLEN 20-FEB-81 FEBRUARY
JONES 02-APR-81 APRIL
MARTIN 28-SEP-81 SEPTEMBER
BLAKE 01-MAY-81 MAY
CLARK 09-JUN-81 JUNE
SCOTT 19-APR-87 APRIL
KING 17-NOV-81 NOVEMBER
TURNER 08-SEP-81 SEPTEMBER
ADAMS 23-MAY-87 MAY
JAMES 03-DEC-81 DECEMBER
FORD 03-DEC-81 DECEMBER

Thampy Mathew 82
Oracle Complete – A Quick Reference
SQL
Select Ename, Hiredate,
TO_CHAR (TO_DATE (Hiredate, 'DD-MON-YYYY'), 'Month') Month
From EMP;

Output:
ENAME HIREDATE MONTH
---------- --------- ---------
SMITH 17-DEC-80 December
ALLEN 20-FEB-81 February
JONES 02-APR-81 April
MARTIN 28-SEP-81 September
BLAKE 01-MAY-81 May
CLARK 09-JUN-81 June
SCOTT 19-APR-87 April
KING 17-NOV-81 November
TURNER 08-SEP-81 September
ADAMS 23-MAY-87 May
JAMES 03-DEC-81 December
FORD 03-DEC-81 December

Select Ename, Hiredate,


TO_CHAR (TO_DATE (Hiredate, 'DD-MON-YYYY'), 'DAY') Day
From EMP;

Output:
ENAME HIREDATE DAY
---------- --------- ---------
SMITH 17-DEC-80 SUNDAY
ALLEN 20-FEB-81 TUESDAY
JONES 02-APR-81 MONDAY
MARTIN 28-SEP-81 FRIDAY
BLAKE 01-MAY-81 TUESDAY
CLARK 09-JUN-81 SATURDAY
SCOTT 19-APR-87 THURSDAY
KING 17-NOV-81 SATURDAY
TURNER 08-SEP-81 SATURDAY
ADAMS 23-MAY-87 WEDNESDAY
JAMES 03-DEC-81 MONDAY
FORD 03-DEC-81 MONDAY

Select Ename, Hiredate,


TO_CHAR (TO_DATE (Hiredate, 'DD-MON-YYYY'), 'Day') Day
From EMP;

Thampy Mathew 83
Oracle Complete – A Quick Reference
SQL
Output:
ENAME HIREDATE DAY
---------- --------- ---------
SMITH 17-DEC-80 Sunday
ALLEN 20-FEB-81 Tuesday
JONES 02-APR-81 Monday
MARTIN 28-SEP-81 Friday
BLAKE 01-MAY-81 Tuesday
CLARK 09-JUN-81 Saturday
SCOTT 19-APR-87 Thursday
KING 17-NOV-81 Saturday
TURNER 08-SEP-81 Saturday
ADAMS 23-MAY-87 Wednesday
JAMES 03-DEC-81 Monday
FORD 03-DEC-81 Monday

Select Ename, Hiredate,


TO_CHAR (Hiredate, 'DdSPTH-Month-Year') Date_In_Words
From EMP;

Output:
ENAME HIREDATE DATE_IN_WORDS
---------- --------- --------------------------------------------
SMITH 17-DEC-80 Seventeenth-December -Nineteen Eighty
ALLEN 20-FEB-81 Twentieth-February -Nineteen Eighty-One
JONES 02-APR-81 Second-April -Nineteen Eighty-One
MARTIN 28-SEP-81 Twenty-Eighth-September-Nineteen Eighty-One
BLAKE 01-MAY-81 First-May -Nineteen Eighty-One
CLARK 09-JUN-81 Ninth-June -Nineteen Eighty-One
SCOTT 19-APR-87 Nineteenth-April -Nineteen Eighty-Seven
KING 17-NOV-81 Seventeenth-November -Nineteen Eighty-One
TURNER 08-SEP-81 Eighth-September-Nineteen Eighty-One
ADAMS 23-MAY-87 Twenty-Third-May -Nineteen Eighty-Seven
JAMES 03-DEC-81 Third-December -Nineteen Eighty-One
FORD 03-DEC-81 Third-December -Nineteen Eighty-One

Note:
There are unwanted spaces between month and year. The query given below will
remove those spaces.

Thampy Mathew 84
Oracle Complete – A Quick Reference
SQL
Select Ename, Hiredate,
TO_CHAR (Hiredate, 'DdSPTH-fmMonth-Year') Date_In_Words
From EMP;

Output:
ENAME HIREDATE DATE_IN_WORDS
---------- --------- --------------------------------------------
SMITH 17-DEC-80 Seventeenth-December-Nineteen Eighty
ALLEN 20-FEB-81 Twentieth-February-Nineteen Eighty-One
JONES 02-APR-81 Second-April-Nineteen Eighty-One
MARTIN 28-SEP-81 Twenty-Eighth-September-Nineteen Eighty-One
BLAKE 01-MAY-81 First-May-Nineteen Eighty-One
CLARK 09-JUN-81 Ninth-June-Nineteen Eighty-One
SCOTT 19-APR-87 Nineteenth-April-Nineteen Eighty-Seven
KING 17-NOV-81 Seventeenth-November-Nineteen Eighty-One
TURNER 08-SEP-81 Eighth-September-Nineteen Eighty-One
ADAMS 23-MAY-87 Twenty-Third-May-Nineteen Eighty-Seven
JAMES 03-DEC-81 Third-December-Nineteen Eighty-One
FORD 03-DEC-81 Third-December-Nineteen Eighty-One

Note:
The unwanted spaces between month and year are removed by using fmMonth in
the query.

Comparing Dates

Select Ename, Hiredate


From EMP
Where TO_CHAR (Hiredate) > TO_CHAR(TO_DATE('03-DEC-81'))

Output:
ENAME HIREDATE
---------- ---------
SMITH 17-DEC-80
ALLEN 20-FEB-81
MARTIN 28-SEP-81
CLARK 09-JUN-81
SCOTT 19-APR-87
KING 17-NOV-81
TURNER 08-SEP-81
ADAMS 23-MAY-87

Thampy Mathew 85
Oracle Complete – A Quick Reference
SQL
Using DECODE

Select Ename, Sal,


DECODE (Comm, Null, 'Null', Comm, 'Value Found') Comm
From EMP;

Output:
ENAME SAL COMM
---------- ------- -----------
SMITH 800 Null
ALLEN 1600 Value Found
JONES 2975 Null
MARTIN 1250 Value Found
BLAKE 2850 Null
CLARK 2450 Null
SCOTT 3000 Null
KING 5000 Null
TURNER 1500 Value Found
ADAMS 1100 Null
JAMES 950 Null
FORD 3000 Null

Select Ename, Sal,


DECODE (Comm, Null, 'Value Not Found', Comm, 'Value Found') Comm
From EMP;

Output:
ENAME SAL COMM
---------- ------- ---------------
SMITH 800 Value Not Found
ALLEN 1600 Value Found
JONES 2975 Value Not Found
MARTIN 1250 Value Found
BLAKE 2850 Value Not Found
CLARK 2450 Value Not Found
SCOTT 3000 Value Not Found
KING 5000 Value Not Found
TURNER 1500 Value Found
ADAMS 1100 Value Not Found
JAMES 950 Value Not Found
FORD 3000 Value Not Found

Thampy Mathew 86
Oracle Complete – A Quick Reference
SQL
Select Ename, Sal,
DECODE (Comm, Null, 'Value Not Found', 0, 'Value Zero') Comm
From EMP;

Output:
ENAME SAL COMM
---------- ------- ---------------
SMITH 800 Value Not Found
ALLEN 1600
JONES 2975 Value Not Found
MARTIN 1250
BLAKE 2850 Value Not Found
CLARK 2450 Value Not Found
SCOTT 3000 Value Not Found
KING 5000 Value Not Found
TURNER 1500 Value Zero
ADAMS 1100 Value Not Found
JAMES 950 Value Not Found
FORD 3000 Value Not Found

Select Ename, Sal,


DECODE (Comm, Null, 'Value Not Found', 0,
'Value Zero', Comm, 'Positive Value') Comm
From EMP;

Output:
ENAME SAL COMM
---------- ------- ---------------
SMITH 800 Value Not Found
ALLEN 1600 Positive Value
JONES 2975 Value Not Found
MARTIN 1250 Positive Value
BLAKE 2850 Value Not Found
CLARK 2450 Value Not Found
SCOTT 3000 Value Not Found
KING 5000 Value Not Found
TURNER 1500 Value Zero
ADAMS 1100 Value Not Found
JAMES 950 Value Not Found
FORD 3000 Value Not Found

Thampy Mathew 87
Oracle Complete – A Quick Reference
SQL
Using DECODE with MOD

Select Rownum, DECODE (MOD (Rownum, 5), 0, Rownum, NULL) Line,


Hiredate, Sal From EMP
Order By Hiredate;

Output:
ROWNUM LINE HIREDATE SAL
------- ------ -------- ---------
1 17-DEC-80 800
2 20-FEB-81 1600
3 02-APR-81 2975
5 5 01-MAY-81 2850
6 09-JUN-81 2450
9 08-SEP-81 1500
4 28-SEP-81 1250
8 17-NOV-81 5000
11 03-DEC-81 950
12 03-DEC-81 3000
7 19-APR-87 3000
10 10 23-MAY-87 1100

Classifying Salaries By Service Using DECODE and TRUNC

Select Ename,
TRUNC ((Sysdate - HireDate) / 365) Years,
DECODE (TRUNC ((Sysdate - HireDate) / 365), 0, Sal, NULL) As This_Year,
DECODE (TRUNC ((Sysdate - HireDate) / 365), 16, Sal, NULL) As Sixteen_Years,
DECODE (TRUNC ((Sysdate - HireDate) / 365), 21, Sal, NULL) As Twenty1Years,
DECODE (TRUNC ((Sysdate - HireDate) / 365), 22, Sal, NULL) As Twenty2Years
From EMP
Order By TRUNC ((Sysdate - HireDate) / 365);

Output:
ENAME YEARS THIS_YEAR SIXTEEN_YEARS 21YEARS 22YEARS
---------- -------- --------- ------------- ---------- ---------
---
SCOTT 16 3000
ADAMS 16 1100
MARTIN 21 1250
JAMES 21 950
KING 21 5000
TURNER 21 1500
FORD 21 3000

Thampy Mathew 88
Oracle Complete – A Quick Reference
SQL
SMITH 22 800
ALLEN 22 1600
CLARK 22 2450
BLAKE 22 2850
JONES 22 2975

Converting Figures into Words

Select Ename, Sal,


TO_CHAR (TO_DATE (Sal, 'J'), 'JSP') Salary_In_Words
From EMP;

Output:
ENAME SAL SALARY_IN_WORDS
---------- ------ --------------------------------------
SMITH 800 EIGHT HUNDRED
ALLEN 1600 ONE THOUSAND SIX HUNDRED
JONES 2975 TWO THOUSAND NINE HUNDRED SEVENTY-FIVE
MARTIN 1250 ONE THOUSAND TWO HUNDRED FIFTY
BLAKE 2850 TWO THOUSAND EIGHT HUNDRED FIFTY
CLARK 2450 TWO THOUSAND FOUR HUNDRED FIFTY
SCOTT 3000 THREE THOUSAND
KING 5000 FIVE THOUSAND
TURNER 1500 ONE THOUSAND FIVE HUNDRED
ADAMS 1100 ONE THOUSAND ONE HUNDRED
JAMES 950 NINE HUNDRED FIFTY
FORD 3000 THREE THOUSAND

Select Ename, Sal,


TO_CHAR (TO_DATE (Sal, 'J'), 'Jsp') Salary_In_Words
From EMP;

Output:
ENAME SAL SALARY_IN_WORDS
---------- ------ --------------------------------------
SMITH 800 Eight Hundred
ALLEN 1600 One Thousand Six Hundred
JONES 2975 Two Thousand Nine Hundred Seventy-Five
MARTIN 1250 One Thousand Two Hundred Fifty
BLAKE 2850 Two Thousand Eight Hundred Fifty
CLARK 2450 Two Thousand Four Hundred Fifty
SCOTT 3000 Three Thousand
KING 5000 Five Thousand
TURNER 1500 One Thousand Five Hundred

Thampy Mathew 89
Oracle Complete – A Quick Reference
SQL
ADAMS 1100 One Thousand One Hundred
JAMES 950 Nine Hundred Fifty
FORD 3000 Three Thousand

Concatenating Character Strings

Select Ename, 'Rs.'||Sal Salary,


'Rupees '||TO_CHAR (TO_DATE (Sal, 'J'), 'Jsp')||' Only' Salary_In_Words
From EMP;

Output:
NAME SALARY SALARY_IN_WORDS
----- ------- --------------------------------------------------
SMITH Rs.800 Rupees Eight Hundred Only
ALLEN Rs.1600 Rupees One Thousand Six Hundred Only
JONES Rs.2975 Rupees Two Thousand Nine Hundred Seventy-Five Only
MARTI Rs.1250 Rupees One Thousand Two Hundred Fifty Only
BLAKE Rs.2850 Rupees Two Thousand Eight Hundred Fifty Only
CLARK Rs.2450 Rupees Two Thousand Four Hundred Fifty Only
SCOTT Rs.3000 Rupees Three Thousand Only
KING Rs.5000 Rupees Five Thousand Only
TURNE Rs.1500 Rupees One Thousand Five Hundred Only
ADAMS Rs.1100 Rupees One Thousand One Hundred Only
JAMES Rs.950 Rupees Nine Hundred Fifty Only
FORD Rs.3000 Rupees Three Thousand Only

Sorting Records Using the ORDER BY Clause

Select Ename, Hiredate, Mgr


From EMP
ORDER BY Ename;

Output:
ENAME HIREDATE MGR
---------- --------- ---------
ADAMS 23-MAY-87 7788
ALLEN 20-FEB-81 7698
BLAKE 01-MAY-81 7839
CLARK 09-JUN-81 7839
FORD 03-DEC-81 7566
JAMES 03-DEC-81 7698
JONES 02-APR-81 7839
KING 17-NOV-81

Thampy Mathew 90
Oracle Complete – A Quick Reference
SQL
MARTIN 28-SEP-81 7698
SCOTT 19-APR-87 7566
SMITH 17-DEC-80 7902
TURNER 08-SEP-81 7698

Select Ename, Hiredate, Sal


From EMP
ORDER BY Mgr, Ename;

Output:
ENAME HIREDATE MGR
---------- --------- ---------
FORD 03-DEC-81 7566
SCOTT 19-APR-87 7566
ALLEN 20-FEB-81 7698
JAMES 03-DEC-81 7698
MARTIN 28-SEP-81 7698
TURNER 08-SEP-81 7698
ADAMS 23-MAY-87 7788
BLAKE 01-MAY-81 7839
CLARK 09-JUN-81 7839
JONES 02-APR-81 7839
SMITH 17-DEC-80 7902
KING 17-NOV-81

Using the GROUP BY Clause

Select Deptno, Count (Ename)


From EMP
GROUP BY Deptno;

Output:
DEPTNO COUNT(ENAME)
------- ------------
10 2
20 5
30 5

Using HAVING with GROUP BY

Select Deptno, Count (Ename)


From EMP
GROUP BY Deptno
HAVING Deptno > 10;

Thampy Mathew 91
Oracle Complete – A Quick Reference
SQL
Output:
DEPTNO COUNT(ENAME)
------ ------------
20 5
30 5

Note:
The HAVING Clause works very much like a WHERE clause except that its logic
is only related to the results of group functions, as opposed to columns or
expressions for individual rows, which can still be selected by a WHERE clause.

Select Deptno, Count (Ename) Tot_Staff, Sum (Sal) Tot_Pay


From EMP
GROUP BY Deptno
HAVING Deptno < 30

Output:
DEPTNO TOT_STAFF TOT_PAY
------ --------- ---------
10 2 7450
20 5 10875

Caution:
If a group function like SUM, COUNT, AVG etc. is used in the SELECT
statement, GROUP BY clause must be added.

Using ROLLUP, GROUPING, CUBE

Select DECODE (GROUPING (Deptno), 1, 'All Depts', Deptno),


Sum (Sal)
From EMP
Group By ROLLUP (Deptno);

Select DECODE (GROUPING (Deptno), 1, 'All Depts', Deptno),


Sum (Sal)
From EMP
Group By CUBE (Deptno);

Note:
The GROUPING function will return a value of 1 if the column's value is
generated by a ROLLUP. The DECODE function converts this into a value of
'All Depts'.

Thampy Mathew 92
Oracle Complete – A Quick Reference
SQL

Querying From Multiple Tables


Select D.Deptno, D.Loc, E.Ename, E.Sal
From Dept D, EMP E
Where D.Deptno = E.Deptno
Order By Deptno;

Output:
DEPTNO LOC ENAME SAL
----------- ------------- ---------- ---------
10 NEW YORK CLARK 2450
10 NEW YORK KING 5000
20 DALLAS SMITH 800
20 DALLAS SCOTT 3000
20 DALLAS JONES 2975
20 DALLAS ADAMS 1100
20 DALLAS FORD 3000
30 CHICAGO ALLEN 1600
30 CHICAGO MARTIN 1250
30 CHICAGO TURNER 1500
30 CHICAGO JAMES 950
30 CHICAGO BLAKE 2850

Note:
The above query does not show details of department number 40. This is because
deptno 40 is not present in the EMP table. So, If department 40 details with blank
employee details is to be displayed use outer join.

Outer Join

Select D.Deptno, D.Loc, E.Ename, E.Sal


From Dept D, EMP E
Where D.Deptno = E.Deptno (+)
Order By Deptno;

Output:
DEPTNO LOC ENAME SAL
----------- ------------- ---------- ---------
10 NEW YORK CLARK 2450
10 NEW YORK KING 5000
20 DALLAS SMITH 800
20 DALLAS SCOTT 3000

Thampy Mathew 93
Oracle Complete – A Quick Reference
SQL
20 DALLAS JONES 2975
20 DALLAS ADAMS 1100
20 DALLAS FORD 3000
30 CHICAGO ALLEN 1600
30 CHICAGO MARTIN 1250
30 CHICAGO TURNER 1500
30 CHICAGO JAMES 950
30 CHICAGO BLAKE 2850
40 BOSTON

Note:
The (+) inserted after E.Deptno in the Where clause of the query created an outer
join by which Deptno 40 and its Location are displayed with blank values for the
employees.

Self Join

Select A.Empno EmpNo, A.Ename Employee,


B.Empno EmpNo, B.Ename Manager
From EMP A, EMP.B
Where B.Empno = A.Mgr;

Output:
EMPNO EMPLOYEE EMPNO MANAGER
------ -------- ----- -------
7369 SMITH 7902 FORD
7499 ALLEN 7698 BLAKE
7566 JONES 7839 KING
7654 MARTIN 7698 BLAKE
7698 BLAKE 7839 KING
7782 CLARK 7839 KING
7788 SCOTT 7566 JONES
7844 TURNER 7698 BLAKE
7876 ADAMS 7788 SCOTT
7900 JAMES 7698 BLAKE
7902 FORD 7566 JONES

Correlated Subqueries

All Employees Woking in NEW YORK

Select E.Ename Name, D.Loc Location


From DEPT D, EMP E
Where E.Deptno = D.Deptno

Thampy Mathew 94
Oracle Complete – A Quick Reference
SQL
And E.Deptno =
(Select Deptno From Dept
Where Loc = 'NEW YORK');

Output:
NAME LOCATION
---------- ---------
CLARK NEW YORK
KING NEW YORK

Note:
There is no limit o the number of subqueries that can be used in a Query. Whe the
Query is executed last subquery will be executed first and its output will be used i
the second last sbquery and so on.

An Alternate to Subqueries.

Select DISTINCT E.Ename Name, D.Loc Location


From DEPT D, EMP E
Where
E.Deptno = D.Deptno
And D.Loc = 'NEW YORK';

Output:
NAME LOCATION
---------- ---------
CLARK NEW YORK
KING NEW YORK

A Possible MISTAKE.

Select DISTINCT E.Ename Name, D.Loc Location


From DEPT D, EMP E
Where E.Deptno =
(Select Deptno From Dept
Where Loc = 'NEW YORK');

Output:
NAME LOCATION
---------- --------
CLARK BOSTON
CLARK CHICAGO
CLARK DALLAS
CLARK NEW YORK

Thampy Mathew 95
Oracle Complete – A Quick Reference
SQL
KING BOSTON
KING CHICAGO
KING DALLAS
KING NEW YORK

Note:
E.Deptno = D.Deptno condition is removed in the above query due to which the
names are getting repeated with all the available depts. Note that the repetition
could not be stopped by the DISTINCT function used in the query.

Subquery Returns More Than One Value

Select DISTINCT E.Ename Name, D.Loc Location


From DEPT D, EMP E
Where E.Deptno = D.Deptno
And E.Deptno =
(Select Deptno From Dept
Where Loc = 'NEW YORK' OR Loc = 'DALLAS');

Output:
ERROR at line 4:
ORA-01427: single-row subquery returns more than one row

Note:
If the subquery returns more than one value, instead of = use IN as shown in the
following Query

Select DISTINCT E.Ename Name, D.Loc Location


From DEPT D, EMP E
Where E.Deptno = D.Deptno
And E.Deptno IN
(Select Deptno From Dept
Where Loc = 'NEW YORK' OR Loc = 'DALLAS');
Order By D.Loc

Output:
NAME LOCATION
---------- --------
ADAMS DALLAS
FORD DALLAS
JONES DALLAS
SCOTT DALLAS
SMITH DALLAS
CLARK NEW YORK

Thampy Mathew 96
Oracle Complete – A Quick Reference
SQL
KING NEW YORK

Using EXISTS in Subqueries

Note:
EXISTS is a test for existence. It is placed the way IN might be placed with a
subquery but differs in two ways:

 It does not match a column or columns.


 It is typically used only with correlated subqueries.

Select Deptno, Dname, Loc


From DEPT
Where EXISTS
(Select Deptno From EMP);

Output:
DEPTNO DNAME LOC
------ -------------- --------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON

Note:
The outer query selects record each time when the inner query returns at least one
record. The inner query output is not equated with the outer query.

Select D.Deptno, D.Dname, D.Loc


From DEPT D
Where EXISTS
(Select Deptno From EMP
Where Deptno = D.Deptno);

Output:
DEPTNO DNAME LOC
------ -------------- --------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO

Thampy Mathew 97
Oracle Complete – A Quick Reference
SQL
Note:
The department number (D.Deptno) of the outer query is equated with the
department number of the inner query by giving the condition Deptno = D.Deptno
in the inner query.

Select D.Deptno, D.Dname, D.Loc


From DEPT D
Where NOT EXISTS
(Select Deptno From EMP
Where Deptno = D.Deptno);

Output:
DEPTNO DNAME LOC
------ -------------- -------
40 OPERATIONS BOSTON

What is the Wrong With These Queries

Find the details of all departments that are present in the EMP table from dept
table.

Select D.Deptno, D.Dname, D.Loc


From DEPT D, EMP E
Where E.Deptno = D.Deptno

Output:
DEPTNO DNAME LOC
---- -------- --------
20 RESEARCH DALLAS
30 SALES CHICAGO
20 RESEARCH DALLAS
30 SALES CHICAGO
30 SALES CHICAGO
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
10 ACCOUNTING NEW YORK
30 SALES CHICAGO
20 RESEARCH DALLAS
30 SALES CHICAGO
20 RESEARCH DALLAS

Why the Deptnos are repeating. See the following query for answer.

Thampy Mathew 98
Oracle Complete – A Quick Reference
SQL
Select D.Deptno, D.Dname, D.Loc,
E.Ename
From DEPT D, EMP E
Where E.Deptno = D.Deptno;

Output:
DEPTNO DNAME LOC ENAME
---- -------------- ------------- ------
20 RESEARCH DALLAS SMITH
30 SALES CHICAGO ALLEN
20 RESEARCH DALLAS JONES
30 SALES CHICAGO MARTIN
30 SALES CHICAGO BLAKE
10 ACCOUNTING NEW YORK CLARK
20 RESEARCH DALLAS SCOTT
10 ACCOUNTING NEW YORK KING
30 SALES CHICAGO TURNER
20 RESEARCH DALLAS ADAMS
30 SALES CHICAGO JAMES
20 RESEARCH DALLAS FORD

For each name in EMP it selected one record from DEPT that met the condition
E.Deptno = D.Deptno

Add a DISTINCT to Stop the Repetition

Select DISTINCT D.Deptno, D.Dname, D.Loc


From DEPT D, EMP E
Where E.Deptno = D.Deptno

Output:
DEPTNO DNAME LOC
---- -------------- -------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO

Using Set Operators

Select Deptno From DEPT


UNION
(Select Deptno From EMP);

Thampy Mathew 99
Oracle Complete – A Quick Reference
SQL
Output:
DEPTNO
----
10
20
30
40

Note:
UNION avoids repetitions.

Select Deptno From DEPT


UNION ALL
(Select Deptno From EMP);

Output:
DEPTNO
----
10
20
30
40
20
30
20
30
30
10
20
10
30
20
30
20

Note:
UNION ALL combines all records.

Select Deptno From DEPT


UNION ALL
(Select DISTINCT Deptno From EMP);

Output:
DEPTNO
----
10

Thampy Mathew 100


Oracle Complete – A Quick Reference
SQL
20
30
40
10
20
30

Select Deptno From DEPT


INTERSECT
(Select Deptno From EMP);

Output:
DEPTNO
----
10
20
30

Note:
INTERSECT fetches only records common in both the tables.

Select Deptno From DEPT


MINUS
(Select Deptno From EMP);

Output:
DEPTNO
----
40

Note:
MINUS subtracts the records fetched by the inner query from the records fetched
by the outer query.

Select Deptno From EMP


MINUS
(Select Deptno From DEPT);

Output:
no rows selected

Restriction on UNION, INTERSECT and MINUS

Queries that use a UNION, INTERSECT or MINUS in there where clause must have the
same number and type of columns. in the select list. But an equivalent IN construction
does not have this limitation.

Thampy Mathew 101


Oracle Complete – A Quick Reference
SQL

Tree Structure Queries


The Rules

 The order of the clauses when using CONNECT BY is as follows.

Select
From
Where
Start With
Connect By
Order By

 PRIOR forces reporting to be from the root out toward the leaves (if the PRIOR
column is the parent) or from a leaf toward the root (if the PRIOR column is the
child)

 A WHERE clause eliminates individuals from the tree, but not their descendants
(or ancestors, if PRIOR is on the right side of the equal sign)

 A qualificatio in the CONNECT BY (particularly a NOT EQUAL) eliminates


both an individual and all the descendants (or ancestors, depending on how you
trace the tree.

 CONNECT BY cannot be used with a table join in the WHERE clause.

The queries are based on the following table.

Select * From Cattle;

OFFSPRING SEX COW BULL BIRTHDATE


--------- --- ------- -------- ---------
EVE F
ADAM M
BANDIT M
BETSY F EVE ADAM 02-JAN-00
POCO M EVE ADAM 15-JUL-00
GRETA F EVE BANDIT 12-MAR-01
MANDY F EVE POCO 22-AUG-02
CINDY F EVE POCO 09-FEB-03
NOVI F BETSY ADAM 30-MAR-03
GINNY F BETSY BANDIT 04-DEC-03
DUKE M MANDY BANDIT 24-JUL-04

Thampy Mathew 102


Oracle Complete – A Quick Reference
SQL
TEDDI F BETSY BANDIT 12-AUG-05
SUZY F GINNY DUKE 03-APR-06
PAULA F MANDY POCO 21-DEC-06
RUTH F GINNY DUKE 25-DEC-06
DELLA F SUZY BANDIT 21-OCT-08

Select Cow, Bull, LPAD (' ', 6 * (Level – 1), '-') || Offspring Offpring,
Sex, Birthdate
From Cattle
Start With Offspring = 'EVE'
Connect By Cow = PRIOR Offspring;

Output:
COW BULL OFSPRING SEX BIRTHDATE
----- ----- ----------------------------------------- ---- --------------
EVE F
EVE ADAM---------------BETSY F 02-JAN-00
BETSY ADAM---------------------------NOVI F 30-MAR-03
BETSY BANDIT -------------------------GINNY F 04-DEC-03
GINNY DUKE----------------------------------------SUZY F 03-APR-06
SUZY BANDIT -----------------------------------------DELLA F 11-OCT-08
GINY DUKE----------------------------------------RUTH F 25-DEC-06
BETSY BANDIT -------------------------TEDDI F 12-AUG-05
EVE ADAM---------------POCO M 15-JUL-00
EVE BANDIT ------------ GRETA F 12-MAR-01
EVE POCO---------------- MANDY F 22-AUG-02
MANDY BANDIT ------------------------DUKE M 24-DEC-06
MANDY POCO---------------------------- PAULA F 21-DEC-06
EVE POCO---------------CINDY F 09-FEB-03

Select Cow, Bull, LPAD (' ', 6 * (Level - 1)) || Offspring Offpring,
Sex, Birthdate
From Cattle
Start With Offspring = 'EVE'
Connect By Cow = PRIOR Offspring;

Output:
COW BULL OFSPRING SEX BIRTHDATE
----- ----- ----------------------------------------- ---- --------------
EVE F
EVE ADAM BETSY F 02-JAN-00
BETSY ADAM NOVI F 30-MAR-03
BETSY BANDIT GINNY F 04-DEC-03
GINNY DUKE SUZY F 03-APR-06
SUZY BANDIT DELLA F 11-OCT-08
GINY DUKE RUTH F 25-DEC-06
BETSY BANDIT TEDDI F 12-AUG-05
EVE ADAM POCO M 15-JUL-00
EVE BANDIT GRETA F 12-MAR-01
EVE POCO MANDY F 22-AUG-02
MANDY BANDIT DUKE M 24-DEC-06
MANDY POCO PAULA F 21-DEC-06
EVE POCO CINDY F 09-FEB-03

Thampy Mathew 103


Oracle Complete – A Quick Reference
SQL
Select Cow, Bull, LPAD (Offspring, 6 * (Level - 1), ‘ ‘) || Offspring Offpring,
Sex, Birthdate
From Cattle
Start With Offspring = 'EVE'
Connect By Cow = PRIOR Offspring;

Output:
COW BULL OFSPRING SEX BIRTHDATE
----- ----- ----------------------------------------- ---- --------------
EVE ADAM BETSY F 02-JAN-00
BETSY ADAM NOVI F 30-MAR-03
BETSY BANDIT GINNY F 04-DEC-03
GINNY DUKE SUZY F 03-APR-06
SUZY BANDIT DELLA F 11-OCT-08
GINY DUKE RUTH F 25-DEC-06
BETSY BANDIT TEDDI F 12-AUG-05
EVE ADAM POCO M 15-JUL-00
EVE BANDIT GRETA F 12-MAR-01
EVE POCO MANDY F 22-AUG-02
MANDY BANDIT DUKE M 24-DEC-06
MANDY POCO PAULA F 21-DEC-06
EVE POCO CINDY F 09-FEB-03

The line for EVE is not displayed as 6 * (Level – 1) produces a 0. (6 * (1 – 1) = 0)

Excluding Individuals

Select Cow, Bull, LPAD (' ', 6 * (Level - 1)) || Offspring Offpring,
Sex, Birthdate
From Cattle
Where Offsprng <> 'BETSY'
Start With Offspring = 'EVE'
Connect By Cow = PRIOR Offspring;

COW BULL OFSPRING SEX BIRTHDATE


------ ------ ------------------------------------------- ---- -------- ------------------
EVE F
BETSY ADAM NOVI F 30-MAR-03
BETSY BANDIT GINNY F 04-DEC-03
GINNY DUKE SUZY F 03-APR-06
SUZY BANDIT DELLA F 11-OCT-08
GINNY DUKE RUTH F 25-DEC-06
BETSY BANDIT TEDDI F 12-AUG-05
EVE ADAM POCO M 15-JUL-00
EVE BANDIT GRETA F 12-MAR-01
EVE POCI MANDY F 22-AUG-02
MANDY BANDIT DUKE M 24-JUL-04
MANDT POCO PAULA F 21-DEC-06
EVE POCO CINDY F 09-FEB-03

Thampy Mathew 104


Oracle Complete – A Quick Reference
SQL
Excluding individuals and Branches

Select Cow, Bull, LPAD (' ', 6 * (Level - 1)) || Offspring Offpring,
Sex, Birthdate
From Cattle
Start With Offspring = 'EVE'
Connect By Cow = PRIOR Offspring
And Offsprng <> 'BETSY';

Output:
COW BULL OFSPRING SEX BIRTHDATE
----- ----- ----------------------------------------- ---- --------------
EVE F
EVE ADAM POCO M 15-JUL-00
EVE BANDIT GRETA F 13-MAR-01
EVE POCO MANDY F 22-AUG-02
MANDY BANDIT DUKE M 24-JUL-04
MANDT POCO PAULA F 21-DEC-06
EVE POCO CINDY F 09-FEB-03

Select Cow, Bull, LPAD (' ', 6 * (Level - 1)) || Offspring Offpring,
Sex, Birthdate
From Cattle
Start With Offspring = 'EVE'
Connect By Cow = PRIOR Offspring
Order By Cow, Birthdate;

Output:
COW BULL OFSPRING SEX BIRTHDATE
----- ----- ----------------------------------------- ---- --------------
EVE F
BETSY ADAM NOVI F
BETSY BANDIT GINNY F
BETSY BANDIT TEDDI F
EVE ADAM BETSY F
EVE ADAM POCO M
EVE BANDIT GRETA F
EVE POCO MANDY F
EVE POCO CINDY F
GINNY DUKE SUZY F
GINNY DUKE RUTH F
MANDY BANDIT DUKE M
MANDY POCO PAULA F
SUZY BANDIT DELLA F

Thampy Mathew 105


Oracle Complete – A Quick Reference
SQL
Select Cow, Bull, LPAD (' ', 6 * (Level - 1)) || Offspring Offpring,
Sex, Birthdate
From Cattle
Start With Offspring = 'EVE'
Connect By Cow = PRIOR Offspring
Order By Birthdate;

Output:
COW BULL OFSPRING SEX BIRTHDATE
----- ----- ----------------------------------------- ---- --------------
EVE F
EVE ADAM BETSY F
EVE ADAM POCO M
EVE BANDIT GRETA F
EVE POCO MANDY F
EVE POCO CINDY F
BETSY ADAM NOVI F
BETSY BANDIT GINNY F
MANDY BANDIT DUKE M
BETSY BANDIT TEDDI F
GINNY DUKE SUZY F
MANDY POCO PAULA F
GINNY DUKE RUTH F
SUZY BANDIT DELLA F

Finding the Ancestors By Mother

Select Cow, Bull, LPAD(' ',6*(Level-1)) || Offspring Offpring,


Sex, Birthdate
From Cattle
Start With Offspring = 'DELLA'
Connect By Offspring = PRIOR Cow;

Output:
COW BULL OFSPRING SEX BIRTHDATE
----- ----- ----------------------------------------- ---- --------------
SUZY BANDIT DELLA F 11-OCT-08
GINNY DUKE SUZY F 03-APR-06
BETSY BANDIT GINNY F 04-DEC-03
EVE ADAM BETSY F 02-JAN-00
EVE F

The direction of display is not pleasant

Thampy Mathew 106


Oracle Complete – A Quick Reference
SQL
Let Us Improve It

Select Cow, Bull, LPAD(' ',6*(Level-1)) || Offspring Offpring,


Sex, Birthdate
From Cattle
Start With Offspring = 'DELLA'
Connect By Offspring = PRIOR Cow;
Order By Birthdate;

Output:
COW BULL OFSPRING SEX BIRTHDATE
----- ----- ----------------------------------------- ---- --------------
EVE F
EVE ADAM BETSY F 02-JAN-00
BETSY BANDIT GINNY F 04-DEC-03
GINNY DUKE SUZY F 03-APR-03
SUZY BANDIT DELLA F 11-OCT-08

The direction of display is better still not very pleasant

Let Us Correct It

Select Cow, Bull, LPAD (' ', 6 * (5 - Level)) || Offspring Offpring,


Sex, Birthdate
From Cattle
Start With Offspring = 'DELLA'
Connect By Offspring = PRIOR Cow;
Order By Birthdate;

Output:
COW BULL OFSPRING SEX BIRTHDATE
----- ----- ----------------------------------------- ---- --------------
EVE F
EVE ADAM BETSY F 02-JAN-00
BETSY BANDIT GINNY F 04-DEC-03
GINNY DUKE SUZY F 03-APR-06
SUZY BANDIT DELLA F 11-OCT-08

Now it is OK

Thampy Mathew 107


Oracle Complete – A Quick Reference
SQL
Finding the Ancestors By Father

Select Cow, Bull, LPAD (' ', 6 * (Level – 1)) || Offspring Offpring,
Sex, Birthdate
From Cattle
Start With Offspring = 'ADAM'
Connect By PRIOR Offspring = Bull;

Output:
COW BULL OFSPRING SEX BIRTHDATE
----- ----- ----------------------------------------- ---- --------------
ADAM M
EVE ADAM BETSY F 02-JAN-00
EVE ADAM POCO M 15-JUL-00
EVE POCO MANDY F 22-AUG-02
EVE POCO CINDY F 09-FEB-03
MANDY POCO PAULA F 21-DEC-06
BETSY ADAM NOVI F 30-MAR-03

Select Cow, Bull, LPAD (' ', 6 * (Level - 1)) || Offspring Offpring,
Sex, Birthdate
From Cattle
Start With Offspring = 'BANDIT'
Connect By PRIOR Offspring = Bull;

Output:
COW BULL OFSPRING SEX BIRTHDATE
----- ----- ----------------------------------------- ---- --------------
BANDIT M
EVE BANDIT GRETA F
BETSY BANDIT GINNY F
MANDY BANDIT DUKE M
GINNY DUKE SUZY F
GINNY DUKE RUTH F
BETSY BANDIT TEDDI F
SUZY BANDIT DELLA F

Thampy Mathew 108


Oracle Complete – A Quick Reference
SQL

Accessing Remote Database


Creating a Database Link
Create (Public) Database Link <DB_LINK Name>
Connect To <Username> Identified By <Password>
Using <Connect String> ;

Create (Public) Database Link <DB_LINK Name>


Connect To Current_User
Using <Connect String> ;

The specific syntax to use when creating a database link depends upon two criteria;

 The Public or Private status of the database link


 The use of default or explicit logins for the remote database

Note:
To create a database link, CREATE DATABASE LINK system privilege. The
account to which you will be connecting in the remote database must have CREATE
SESSION privilege.

Public Vs Private Database Link

A public database link is available to all users in a database. By contrast, a private


database link is only available to the user who created it. It is not possible for one user
to grant access on a private database link to another user. The database link must
either be public (available to all users) or private.

Creating Connect String


Net8 uses service names to identify remote connections. The connection details for these
service names are contained in files that are distributed to each host in the network. When
a service name is encountered Oracle checks the local Net8 configuration file (called
tnsnames.ora) to determine which protocol, host name and database name to use during
the connection.

When using Net8, you must know the name of the service that ponts to the remote
database. For example, if the name HQ specifies the connection parameters for the

Thampy Mathew 109


Oracle Complete – A Quick Reference
SQL
database you need, then HQ should be used as the connect string in the Create Database
Link command.

Syntax:

Create Database Link DB1_DB2


Connect to current_User
Using ‘HQ’ ;

When this link is used, Oracle checks the tnsnames.ora file on the local host to determine
which database to connect to. Whe it attempts to log in to that database, it uses the
current_user’s username and password.

The tnsnames.ora files for a network of databases should be coordinated by the DBAs for
those databases. A typical entry in the tnsnames.ora file (for a network using the TCP/IP
protocol) is shown in the following listing.

HQ = (DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL – TCP)
(HOST = host1)
(PORT = 1521)
)
)
(CONNECT DATA =
(SERVICE_NAME – HQ.host 1)
)
)

In this listing he HQ service name is mapped to a connect description that tells database
which protocol to use (TCP/IP), and which host (host1) and database (HQ) to connect to.

Connecting to a Remote Database


SQL> <Username> / <Password>@<Database Name>
SQL> Scott / Tiger@HQ

This command will directly log in the user scott to the HQ database.

Create Table EMP1


As
Select * From EMP@DB1_DB2;

Thampy Mathew 110


Oracle Complete – A Quick Reference
SQL
If there are too many records in EMP table, the table creation may fail if there is no
sufficient space available in the rollback segment to maintain image of the pulled data till
it is committed.

To overcome the above problem you can use the SQLPLUS Copy command.

set copycommit 1
set arraysize 1000

copy from scott/tiger@HQ


to scott/tiger@HQ
create EMP1 –
using –
select * from EMP

Explanation:

arraysize : determines the number of records to be pulled in a batch.


Copycommit : determines the number of batches to be committed at one time.

Except for he last line, each line in the copy command must be terminated with a dash (-),
since this is an sqlplus command.

The copy command can be used within or between databases. Although it allows you to
select which columns to copy it works best when all the columns of a table are being
chosen.

If the current account is to be the destination of the copied data, then the word to plus the
local username, password and connect string are not necessary.

Data Options Within the Copy Command

APPEND : Inserts the rows into the destination table. Automatically creates the table
if it does not exist.

CREATE : Creates the table and then inserts the rows.

INSERT : Inserts the rows into the destination table if it exists; otherwise, returns
an error. When using INSERT, all columns must be specified in the using
subquery.

REPLACE : drops the existing destination table and replace it with a new table
containing the copied data.

Thampy Mathew 111


Oracle Complete – A Quick Reference
SQL

Users And User Accesses


Creating a User

Syntax:

Create User <User Name>/ Identified By <Password>;

Alter User <User Name>/ Identified By <New Password>;

Example:

Create User thampy/ Identified By mathew;

Password Management

Changing The password


Alter User thampy/ Identified By consultant; OR
Type only password at the SQL prompt. Then the system will ask for the old password, if
entered correctly it will ask for the new password.

SQL>password
Changing password for scott
Old password: <enter>
New password: <enter>
Retype new password: <enter>

The expiration characteristics of our pass word is determined by the profile assigned to
your account. A profile can enforce he following.

 The ‘lifetime of your password, which determines how frequently you must
change your password.

 The grace period following your password’s ‘expiration date’ during which you
can change your password.

 The number of consecutive failed connect attempts allowed before the account is
automatically ‘locked’.

Thampy Mathew 112


Oracle Complete – A Quick Reference
SQL
 The number of days the account will remain locked.

 The number of days that must pass before you can reuse a password.

 The number of password changes that must pass before you can reuse a password.

Dropping a User
Syntax:

Drop User <User Name> [Cascade] ;

The cascade option drops the user along with all the objects owned by him and
invalidates views, synonyms, procedures, functions or packages that refer to the objects
in the dropped user’s schema. If you don’t use cascade option and there are still objects
owned by the user, the user will not be dropped and instead returns an error message.

Three Standard Roles

The CONNECT Role


The RESOURCE Role
The DBA Role

Granting Privileges

What User’s Can Grant

The privileges a user can grant includes:

 On the user’s tables, views and snapshots (materialized vieas):


INSERT
UPDATE (all or specific columns)
DELETE
SELECT

The INSERT, UPDATE and DELETE privileges can only be granted on


snapshots (materialized views) if they are updateable.

 On tables you can also grant:


ALTER (table – all or specific columns or sequence)
REFERENCES
INDEX (columns in a table)
ALL (of the items previously listed)

Thampy Mathew 113


Oracle Complete – A Quick Reference
SQL
 On procedures, functions, packages, abstract datatypes, libraries, indextypes and
operators:
EXECUTE

 On sequences:
SELECT
ALTER

 On directories (for BFILE LOB datatypes:


READ

The privileges granted must be one of the object privileges (ALL, ALTER, DELETE,
EXECUTE, INDEX, INSERT, READ, REFERENCES, SELECT or UPDATE)

Create User thampy Identified By mathew;

Connect thampy/Mathew;

Create Table EMP1


(Empno Number Primary Key,
Ename Varchar2(20),
Sal Number,
Comm Number,
Deptno Number References DEPT (Deptno));

Create User john Identified By mathew;

Grant Select On EMP1 to john;

Connect john/mathew;

Select * From EMP1;

ERROR at line1: ORA-00942: table or view does not exist.

Select * From thampy.EMP1;

The records of EMP1 will be displayed.

Delete From EMP1;

ERROR at line1: ORA-00942: insufficient privileges.

Create View EMP1 As


Select * From thampy.EMP1;

Thampy Mathew 114


Oracle Complete – A Quick Reference
SQL
Select * From EMP1;

The records of EMP1 will be displayed.


Drop View EMP1;

Create Synonym EMP1 For thampy.EMP1;

Select * From EMP1;

The records of EMP1 will be displayed.

Revoking Privileges

Revoke Select On EMP1 From john;

Revoke All On EMP1 From john;

Passing Privileges
Connect john/mathew;

Create User james Identified By thomas;

Grant Select On EMP1 to james;

ERROR at line1:
ORA-00942: grant option does not exist for thampy.EMP1.

Connect thampy/mathew;

Grant Select On EMP1 to john With Grant Option;

Connect john/mathew;

Grant Select On EMP1 to james;

Grant succeeded

Connect james/thomas;

Select * From EMP1;

Thampy Mathew 115


Oracle Complete – A Quick Reference
SQL

Creating a Role
Syntax:

Create Role <Role Name>;

Example:

Create Role CLERK;


Create Role MANAGER;

Granting Privileges to a Role

Grant Select On EMP1 To CLERK;


Grant CREATE SESSION EMP1 To CLERK;
Grant CREATE SESSION, CREATE DATABSE LINK To MANAGER;

Granting a Role to Another Role Or Users


Grant CLERK To MANAGER;

Grant CLERK To john;


Grant MANAGER To thampy With Admin Option;

The admin option authorizes thampy to grant the MANAGER role to other users or roles.

Adding a Password to a Role


Alter Role MANAGER Identified By secret

Any time a user tries to activate the role MANAGER, the password will be required. If,
however, the role is setup as a default role for the user, then no password will be required
for that role when the user logs in.

Roles can be tied to operating system privileges as well. If this capability is available on
your operating system, then you use the identified externally clause of the alter role
command. When the role is enabled Oracle will check the operating system to verify your
access.

Thampy Mathew 116


Oracle Complete – A Quick Reference
SQL
Alter Role MANAGER Identified Externally;

Setting a Default Role For a User


Alter User john
Default Role CLERK;

Alter User thampy


Default Role MANAGER;

Removing Password From a Role

Alter Role MANAGER Not Identified;

Enabling and Disabling Roles In a Session


To enable a nondefault role in your session, use the set role command as shown below.

Set Role CLERK;

You may also use the all and all except clauses that are available in the alter user
command.

Set Role All;


Set Role All Except CLERK;

If a role has a password associated with it you must specify the password via the
identified by clause.

Set Role MANAGER Identified By secret;

To disable a role in your session use set role none command.

Set Role None;

Revoking Privileges From a Role

Revoke SELECT On EMP1 From CLERK;

Dropping a Role

Thampy Mathew 117


Oracle Complete – A Quick Reference
SQL

Drop Role CLERK;


Drop Role MANAGER;

Granting Update to Specific Columns

Grant Update (Empno, Ename) On EMP1 To john;

Security By User

Connect thampy/Mathew;
Create View YOURSAL As
Select Ename, Sal From EMP1
Where SUBSTR (Ename, 1, INSTR (ENAME, ‘ ‘) – 1) = User;

Select * From YOURSAL;

Only user thampy’s details will be displayed.

Grant SELECT On YOURSAL To john;

Connect john/Mathew;

Select * From YOURSAL;

Only user john’s details will be displayed.

Granting Access to the Public

Grant Public Synonym EMP1 For thampy.EMP1;

Grant SELECT On EMP1 To Public;

Granting Resources
Grant CONNECT To thampy;
Grant CONNECT, RESOURCE To Thampy;

Granting Limited Resources

Thampy Mathew 118


Oracle Complete – A Quick Reference
SQL
Alter User john
Quota 100M On USERS;

SQL*Loader
Create a Table

Create Table EMP1


(Empno Number Primary Key,
Ename Varchar2(10),
Sal Number,
Deptno Number References Dept(Deptno),
Active Char(1));

Create an Excel File

1001 THAMPY 7500


1002 MATHEW 8000
1003 SUJA 5500 10
1004 ANNIE 7000 20
1005 JOHN 7500 30
1001 ALLEN 8000 20
1006 SUMAN 7600 50

Note:
1. No Deptno is entered for 1st and 2nd record that references another table.

2. The Deptno 50 entered for the 7th record is not present in the Master table
(DEPT)

3. The Empno of the 6th record (ALLEN) is a repeat.

Create a .csv File

Save the above file as follows to create a csv file.

File Name: UPLOAD.csv


File Type: CSV (Coma delimited)

Create a Text File From The csv File With Extension .dat

Open this file with Notepad and Save As "UPLOAD.dat". Do remember to use double
quotes before and after the file name as "UPLOAD.dat"

Thampy Mathew 119


Oracle Complete – A Quick Reference
SQL
If the text file is opened it will look like:

1001,THAMPY,7500,
1002,MATHEW,8000,
1003,SUJA,5500,10
1004,ANNIE,7000,20
1005,JOHN,7500,30
1001,ALLEN,8000,20
1006,SUMAN,7600,50

Create a Control File

LOAD DATA
INFILE 'D:\UPLOAD.dat'
APPEND
INTO TABLE EMP1
FIELDS TERMINATED BY ","
(Empno, Ename, Sal, Deptno, Avtive constant 'Y')

Note:
1. The dat file with path must be enclosed in single quotes.

2. The order of the field names specified in the control file must correspond to
the order of columns in the dat file.

3. You can send constant values to the table in such cases do not include the
field values in the dat file, instead, specify the constant value in the control
file as it is shown for the field ‘Active’. (Active constant ‘Y’). A value of Y
will be inserted to all to all the rows for the field ‘Active’.

Open The Operating System Command Prompt

Wndows NT
Start --> Run
cmd

Unix
Start --> run
telnet <IP Address>

Invoke SQL*LOADER

sqlldr <User>/<Password> Control = <Control File Name With Path> enter

Thampy Mathew 120


Oracle Complete – A Quick Reference
SQL
OR

sqlldr80 <User>/<Password> Control = <Control File Name With Path> enter

Thampy Mathew 121


Oracle Complete – A Quick Reference
SQL
Note:
Sqlldr or Sqlldr80 is to be used depends on the name that is given for the
SQL*LOADER executable in your system.

When Finished Query the EMP1 Table

Select * From EMP1;

EMPNO ENAME SAL DEPTNO ACTIVE


----- ---------- ------ --------- ----------
1003 SUJA 5500 10 Y
1004 ANNIE 7000 20 Y
1005 JOHN 7500 30 Y
1001 ALLEN 8000 20 Y

Analysis:

When the SQL*Loader runs it will automatically creates the following two files.
A bad file with the same name of the data file with extension .bad
This file will show the uninserted rcords.

A log file with the same name of the control file with extension .log
This fle will write the log of the executon of SQl*Loader

Rows 1001,THAMPY,7500, and 1002,MATHEW,8000, are rejected as no instruction


was written SQL*Loader when it finds a coma at the end of a row.

Row 1006,SUMAN,7600,50 is rejected as this record violates the referential integrity


constraint defined for the field Deptno that refers Dept(Deptno). There is no deptno 50 in
Dept(deptno)

Row 1001,ALLEN,8000,20 was actually violating the primary key constraint on Empno
as the value 1001 is a repeat. It is accepted as the first record with Empno 1001 is
rejected due to some other reason.

Content of UPLOAD.bad
1001,THAMPY,7500,
1002,MATHEW,8000,
1006,SUMAN,7600,50

Thampy Mathew 122


Oracle Complete – A Quick Reference
SQL

Content of UPLOAD.log
SQL*Loader: Release 8.0.3.0.0 - Production on Mon Jul 28 19:13:9 2003

(c) Copyright 1997 Oracle Corporation. All rights reserved.

Control File: UPLOAD1.ctl


Data File: D:\UPLOAD.dat
Bad File: UPLOAD.bad
Discard File: none specified

(Allow all discards)

Number to load: ALL


Number to skip: 0
Errors allowed: 50
Bind array: 64 rows, maximum of 65536 bytes
Continuation: none specified
Path used: Conventional

Table EMP1, loaded from every logical record.


Insert option in effect for this table: APPEND

Column Name Position Len Term Encl Datatype


------------------ ---------- ----- ---- ---- ------------------
EMPNO FIRST * , CHARACTER
ENAME NEXT * , CHARACTER
SAL NEXT * , CHARACTER
DEPTNO NEXT * , CHARACTER

ACTIVE CONSTANT 'Y'

Record 1: Rejected - Error on table EMP1, column DEPTNO.


Column not found before end of logical record (use TRAILING NULLCOLS)
Record 2: Rejected - Error on table EMP1, column DEPTNO.
Column not found before end of logical record (use TRAILING NULLCOLS)
Record 7: Rejected - Error on table EMP1.
ORA-02291: integrity constraint (SCOTT.SYS_C005433) violated - parent key not
found

Table EMP1:
4 Rows successfully loaded.

Thampy Mathew 123


Oracle Complete – A Quick Reference
SQL
3 Rows not loaded due to data errors.
0 Rows not loaded because all WHEN clauses were failed.
0 Rows not loaded because all fields were null.

Space allocated for bind array: 50816 bytes(64 rows)


Space allocated for memory besides bind array: 0 bytes

Total logical records skipped:0


Total logical records read: 7
Total logical records rejected:3
Total logical records discarded: 0

Run began on Mon Jul 28 19:13:09 2003


Run ended on Mon Jul 28 19:13:12 2003

Elapsed time was: 00:00:02.82


CPU time was: 00:00:00.24

Rewrite the Control File As Follows

LOAD DATA
INFILE 'D:\UPLOAD.dat'
APPEND
INTO TABLE EMP1
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
TRAILING NULLCOLS
(Empno, Ename, Sal, Deptno, Active constant 'Y')

Note:
We have added he following two lines in the control file.
OPTIONALLY ENCLOSED BY '"'
TRAILING NULLCOLS

TRAILING NULLCOLS tells SQL*Loader to insert a null in the next column if


any row ends with a coma.

Run SQL*Loader Again

EMPNO ENAME SAL DEPTNO ACTIVE


-------- ---------- ------ ------------ ----------
1001 THAMPY 7500 Y
1002 MATHEW 8000 Y

Thampy Mathew 124


Oracle Complete – A Quick Reference
SQL
1003 SUJA 5500 10 Y
1004 ANNIE 7000 20 Y
1005 JOHN 7500 30 Y

Analysis:

UPLOAD.bad
1001,ALLEN,8000,20
1006,SUMAN,7600,50

Note:
The first record is not inserted because it violates the primary key constraint of the
table.

The second record is not inserted because in violates the referential integrity
constraint of the table.

The above given two reasons can be seen in the log file.

UPLOAD.log
SQL*Loader: Release 8.0.3.0.0 - Production on Mon Jul 28 20:0:34 2003

(c) Copyright 1997 Oracle Corporation. All rights reserved.

Control File: UPLOAD1.ctl


Data File: D:\UPLOAD.dat
Bad File: UPLOAD.bad
Discard File: none specified

(Allow all discards)

Number to load: ALL


Number to skip: 0
Errors allowed: 50
Bind array: 64 rows, maximum of 65536 bytes
Continuation: none specified
Path used: Conventional

Table EMP1, loaded from every logical record.


Insert option in effect for this table: APPEND
TRAILING NULLCOLS option in effect

Column Name Position Len Term Encl Datatype


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

Thampy Mathew 125


Oracle Complete – A Quick Reference
SQL
EMPNO FIRST * , O(") CHARACTER
ENAME NEXT * , O(") CHARACTER
SAL NEXT * , O(") CHARACTER
DEPTNO NEXT * , O(") CHARACTER

ACTIVE CONSTANT 'Y'

Record 6: Rejected - Error on table EMP1.


ORA-00001: unique constraint (SCOTT.SYS_C005432) violated

Record 7: Rejected - Error on table EMP1.


ORA-02291: integrity constraint (SCOTT.SYS_C005433) violated - parent key not
found

Table EMP1:
5 Rows successfully loaded.
2 Rows not loaded due to data errors.
0 Rows not loaded because all WHEN clauses were failed.
0 Rows not loaded because all fields were null.

Space allocated for bind array: 50816 bytes(64 rows)


Space allocated for memory besides bind array: 0 bytes

Total logical records skipped: 0


Total logical records read: 7
Total logical records rejected: 2
Total logical records discarded: 0

Run began on Mon Jul 28 20:00:34 2003


Run ended on Mon Jul 28 20:00:36 2003

Elapsed time was: 00:00:01.59


CPU time was: 00:00:00.17

The Options Available For Loading

APPEND : Use to add rows to the table

INSERT : Use to add rows to an empty table. If the table is not empty, the load will
abort with an error.

REPLACE : Use to empty the table and then add the new rows. The user must have
delete privilege on the table.

TRUNCATE : Delete and commit the table first and then load the rows into it.

Thampy Mathew 126


Oracle Complete – A Quick Reference
SQL

LOAD DATA
INFILE 'D:\UPLOAD.dat'
[APPEND] [INSERT] [REPLACE] [TRUNCATE]
INTO TABLE EMP1
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
TRAILING NULLCOLS
(Empno, Ename, Sal, Deptno, Active constant 'Y')

SQLLDR Key Word Description


Userid User name and password for the load separated by a slash

Control Name of the control file

Log Name of the log file

Bad Name of the bad file


Discard Name of the discard file

Discardmax Maximum number of records to discard before stopping the


load The default is to allow all discards.

Skip Number of logical rows in the input file o skip before


starting to load data. Usually used during reloads from the
same input file foloowing a partial load. The default is 0.

Load Number of logical rows o load. The default is all.

Errors Number of errors to allow. The default is 50.

Rows Number of rows to commit at a time. Use this parameter to


break up the transaction size during the load.The default for
conventional path loads is 64; the default for direct path
load is all rows.

Bindsize Size of conventional path binary array, in bytes. The


default is operating-system dependent.

Silent Suppress messages during the load.

Direct Use Direct Path loading. The default is FALSE.

Parfile The name of the parameter file that contains additional load
parameter specifications.

Thampy Mathew 127


Oracle Complete – A Quick Reference
SQL
Parallel Perform parallel loading. The default is FALSE.

File File to allocate extents from (for parallel loading)

Skip_Unusable_Indexes Allows load into tables that have indexes in unusable states.
The default is FALSE.

Skip_Index_Maintenance Stops index maintenance for Direct Path loads, leaving


them in unusable states. The default is FALSE.
Example:

sqlldr scott/tiger@db1
control = D:\UPLOAD.ctl
log = D:\UPLOAD_LOG.log
bad = D:\UPLOAD_BAD.bad
discard = D:\UPLOAD_DISCARD
skip = 1

Using SQL*Loader in Oracle Application Interface Tables


Create a Data File
1. Create the data file in Excel

2. Copy only the data (with no extra row or column) and Paste Special… Values to a
new file. This is to avoid junk character creations in the table.

3. Save the file as CSV (Coma delimted) with .csv extension. Ensure that the file
name with extension is enclosed in double quotes while saving.

4. Open the csv file with notepad.

5. Save the notepad file with .dat extension. Ensure that the file name with extension
is enclosed in double quotes while saving.

Create a Control File


6. Write the required script (refer below) in Notepad and save it with .ctl extension.
Ensure that the file name with extension is enclosed in double quotes while
saving.

Transfer the Data and Control Files to the Required Server Directory
7. Open the ftp prompt. (Start  Run [ftp <IP Address>] Enter
Connect to the required database for which type the:

Thampy Mathew 128


Oracle Complete – A Quick Reference
SQL
User/Password@<Connect String of the Required Database>

8. Change the local machine directory o the directory where the Data and Control
files are currently available. (lcd C:\Upload\EAM)

9. Change the Server directory to the directory in which you want to keep the Data
and Control files. (cd /apps2/oraprdt/uploads/Asset_Group)

10. Change the transfer mode to ASCII. (Simply type ASCII at the ftp prompt)

11. Transfer the Data file from the client machine to the server. (put <File
Name>.dat)

12. Transfer the Control file from the client machine to the server. (put <File
Name>.ctl)

Open the Operating System Command Prompt


13. Start  Run
telnet <IP Address) Enter
Connect to the required database for which type the:
User/Password@<Connect String of the Required Database>

Run SQL*Loader
14. sqlldr [sqlldr80] <username>/<password>@<connect string>
control = <control file name>.ctl

The loading starts now.

A Typical Control File Used to Load Asset Groups.

LOAD INFILE '/apps2/oraprdt/uploads/Asset_Group/1EIM_Asset_Groups_All.dat'


INSERT INTO TABLE MTL_SYSTEM_ITEMS_INTERFACE
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
TRAILING NULLCOLS

(
PROCESS_FLAG constant 1,
TRANSACTION_TYPE constant 'CREATE',
SET_PROCESS_ID constant 1,

SEGMENT1,
DESCRIPTION,
start_auto_serial_number,

Thampy Mathew 129


Oracle Complete – A Quick Reference
SQL
PRIMARY_UNIT_OF_MEASURE constant 'EACH',
ORGANIZATION_ID constant 120,
ALLOWED_UNITS_LOOKUP_CODE constant 3,
ITEM_TYPE constant 'AG',
INVENTORY_ITEM_STATUS_CODE constant 'Active',
INVENTORY_ITEM_FLAG constant 'Y',
STOCK_ENABLED_FLAG constant 'N',
MTL_TRANSACTIONS_ENABLED_FLAG constant 'N',
SERIAL_NUMBER_CONTROL_CODE constant 2,
Auto_serial_Alpha_prefix constant 'AG',
EFFECTIVITY_CONTROL constant 2,
EAM_ITEM_TYPE constant 1,
COSTING_ENABLED_FLAG constant 'N',
PURCHASING_ITEM_FLAG constant 'N',
CUSTOMER_ORDER_FLAG constant 'N',
INVOICEABLE_ITEM_FLAG constant 'N',

LAST_UPDATED_BY constant 0,
LAST_UPDATE_DATE sysdate,
LAST_UPDATE_LOGIN constant 0,
CREATION_DATE sysdate,
CREATED_BY constant 0
)

Thampy Mathew 130


Oracle Complete – A Quick Reference
SQL

Object Relational Database


Creating Abstract Data Types
Create Or Replace Type ADDRESS_TY As Object
(Street Varchar2(50),
City Varchar2(25),
State Varchar2(15),
Zip Number);
/

Create Or Replace Type PERSON_TY As Object


(Name Varchar2(25),
Address ADDRESS_TY);
/

Creating Tables With Abstract Data Types


Create Table CUSTOMER
(Customer_ID Number,
Person PERSON_TY);

Inserting Values Into a Table With Abstract Data Type

Insert Into CUSTOMER Values


(1, PERSON_TY ('JOHN',
ADDRESS_TY ('First Street', 'Bombay', 'MH', 401202)));

Updating a Table With Abstract Data Type

Update Customer C
Set C.Person.Address.State = 'KERALA'
Where C.Person.Address.State = 'KR'

Alias must be used.

Deleting From a Table With Abstract Data Type

Delete From Customer C


Where C.Person.Address.State = 'KERALA'

Thampy Mathew 131


Oracle Complete – A Quick Reference
SQL
Alias must be used.

Retrieving Information From Table With Abstract Data Type

Select C.Person.Name,
C.Person.Address.City
From Customer C
Where C.Person.Address.Zip Like '401%'

Output:
PERSON.NAME PERSON.ADDRESS.CITY
------------------- -----------------------------
JOHN Bombay

Creating a View From a Table With Abstract Data Type

Create Or Replace View CUSTOMER_OV (Customer_ID, Person) As


Select C.Customer_ID,
Person_TY (C.Person.Name,
Address_TY (C.Person.Address.Street,
C.Person.Address.City,
C.Person.Address.State,
C.Person.Address.Zip))
From Customer C
Where C.Person.Address.State = 'KR'

Thampy Mathew 132

You might also like