Sei sulla pagina 1di 143

FIRST STEPS TOWARDS ORACLE 10g

SOME THINGS WHAT WE S HOULD CONSIDER :


As per Oracle database is a collection of data in one or more files.
The databas e can contain Physical and Logical structure.
The Course of developing an application consists of

Creating structures (Tables & Indexes)


Creating Synonyms for the object names.
View objects in different dat abases
Restricting Access to the objects.

External Tables can be accessed for files outside the database, as if the rows in the files
were rows in the table.
An Oracle Instance Comprises of

A memory area called System Global Area (SGA )


Background processes whic h interact between the SGA and the database files
on disk.
The Oracle Read Application Cluster (RA C) can make more than one instance to
use the same database.

Database as per Oracle :


With in the Oracle database, the basic structure is a table.
The different tables supported by Oracle Database are..
1)
2)
3)
4)
5)
6)
7)
8)
9)

Relational Tables
Object Relational Tables
Index Organized Tables
External Tables
Partitioned Tables
Materialized Views
Temporary Tables
Clustered Tables
Dropped Tables

The Access to the data in the tables is tuned by indexes, they are
1)
2)
3)
4)
5)
6)

B+ Tree Index es
Bitmap Indexes
Reverse Key Indexes
Function Based Indexes
Partitioned Index es
Text Indexes

ORACLE STYLE FOR DATA STORAGE :


All the logical structures in the database must be stored in the database.
Oracle maintains a data dictionary, which records META DA TA about object.
The OB JECTS which need physical storage space, are allocated space within a
Tablespace.

Oragle 10 g Material

Table Spaces :
It consist of one or more data files
A data file can be a part of one and only one table space
As per 10g minimum table space is created are

SYSTEM and SYSAUX : which are used to support its internal


management needs

In 10g a bigfile tablespace can be created , which can grow to the size of tera bytes
The Oracle managed files concept can be used to simplify the creation and maintenance
of data files
Temporay Tablespace :
The actual table space is permanent , but the segments saved in the table space are
temporary
It is used to support sorting operations such as index creation and joint processing.
Tables can be either Dictionary Managed / Logically Managed
Oracle maintains a Bitmap in each dat a file of the table space to trace space availability
AUTOMATED STORAGE MANAGEMENT (ASM) :
It automates the layout of datafiles and other operating system level files , used by the
database
It is done by distributing the files across all available disks.
It supports multiplexing features, minimizing the possibility of data data loss
As new disks are added , the database files are automatically redistribut ed access all
disks in the defined groups for optimal performance
AUTOMATIC UNDO MANAGEMENT :

The transaction are support ed by dynamically creating and managing undo segments
It helps in maintaining prior images of the changed Blocks and Rows
The UNDO segments are managed directly without the intervention of the DBA
Flashback version Queries can be executed to see the different versions of a row as it
changed during a specified time interval.

DROPPED DATA :

The Recycle Bin concept was introduced with Oracle Database 10g
This concept impacts the space requirements for the table spaces and datafiles
This architecture greatly simplifies rec overies of accidentally dropped tables
The concept may considerably increase the space used in the database
The PURGE Command is used to remove old ent ries from the recycle bin

PROGRAMMATICAL STRUCTURES IN ORACLE :


1)

PL/SQL :
It is the most critical component of all the application implementations
The component can be used to create stored proc edures and functions
Using this component the stored procedures and functions can be collected into single
unit called packages
Using the sam e component the Dat abase trigger can also be designed.

Oragle 10 g Material

2)

DYNAMIC SQL :
Using this concept SQL can be generat ed at runtime and pass it to procedures which
execute it.

3)

SQL * PLUS :
It provides simple interface to the Oracle database.
It supports Rudimentary Reporting and is the best tool for scripting.
It provides consistent interface for
1.
2.

4)

Retrieving data from data dictionary.


Creating database objects.

JAV A & JDBC :


It supports JAVA and JDB C and help in using JAVA in the place of PL/SQL.
JAVA based stored procedures can be written.

5)

XML :
Oracles XML interfaces and XML types can be used to support inserting and ret rieving of
data via XML.

6)

Object Oriented SQL & PL/SQL :

7)

Oracle can be used to create and access object oriented structures, including user defined
data types, methods, large objects object tables nested tables.
Data Pump :
Data Pump import and Data Pump Export, enhance the manageability and performanc e.
Data Pump can be used to quickly extract data and move it to different databases whi le
altering the schema and changing the rows.

8)

SQL * LOADER :
It is used to load flat files quickly into Oracle Tables.
A single flat file can be loaded into multiple tables during the same load, and loads can be
parallel zed.

9)

External Programs and Procedures :


SQL can be embedded with in external programs.
Procedural Libraries can be created and can be linked later to Oracle.

10 ) UTL MAIL :
It is a package introduced in Oracle 10g.
It allows a PL/SQL application developer to see e-mails without having to know how to use
the underlying SMTP Protocal stack.

Oragle 10 g Material

TYP ES OF EDITIONS :
1)

Enterpri se Edi tion :


It contains all features and is the rich extensible version of the Oracle databse.
It includes features such as Flash Back Database.
The licensed functionalities that are supported are :

Oracle Spatial
Oracle OLAP
Oracle Label Security
Oracle Data Mining

2) Standard Edition :
It provides some subset features of Enterprise Edition.
It includes features that are needed by a small business entity .
3) Personal Edition :
It allows for the development of applications which run on either the standard or Enterprise
Edition.
The Edition is not suitable for Production Environment.
DATABAS E MANAGEMENT SYSTEMS :
DBMS is a program which takes care of

Storing of Information.
Retrieving of Information.
Modification of Information.
Deletion of Information.

Type of Databases
** Hierarchical

** Network

** Relational

** Object Relational

** Object Oriented

RELATI ONAL MODELS :


The Model was first outlined by Dr. E. F. Codd in 1970.
The components of Relational Model are :

Collection of objects or relations that store the data.


A set of operations that can act on the relations to produc e other relations.
Data integrity for accuracy and consistency

A Relational dat abas e uses relations or two dimensional tables to store information.

Oragle 10 g Material

DATA MODELS :
The Data Models help in exploring ideas and improve the understanding of the database design.
PURPOS E OF DATA MODELS :
** Communicate

** Categoriz e

** Describe ** Specify

** Evolve

** Analyze

** Imitate

** Investigate

OBJECTIV E OF THE MODELS :


To produce a model that fits a multitude of uses
Should be understood by an end user.
Should contain sufficient detail for a developer to build the dat abase system
RELATI ONAL DATABAS E PROP ERTI ES :

It can be accessed and modified by executing Structured Query Language statements.


It contains a collection of tables with no physical pointers.
It uses a set of operators.
We need not specify the access route to the tables
There is no need to identify how the data is arranged physically.

COMMUNICATING WITH RDBMS :


The Structured Query Language is used to Communicate wit h RDBMS.
STRUCTURED QUERY LANGUAGE :

It
It
It
It

allows the user to communicate as the server


is Efficient
is easy to learn and use
is functionally complete, by allowing the use to define, retrieve and manipulat e the dat a.

ABOUT ORACLE 8 :
It is the first object capable database.
It provides a new engine which supports

Object oriented programming


Complex data types
Complex business objects
Full compatibility with the relational concepts.

It provides OLTP applications, with sharing of runtime dat a structures, large buffer caches and
deferrable constrains.
It supports Client Server and Web based application whic h are distributed and multitired.
It can scale tens and thousands of concurrent users.

Oragle 10 g Material

ABOUT ORACLE 8i :

It is the database of Internet Computing.


It provides advanced tools to manage all types of data in Web Sites.
The Internet File System ( IFS) combines the power for ease of use a file system.
End users can easily access files and folders in ORA CLE IFS via a variety of protocols.
It enables the users to web-enable their multimedia data
It provides full, native int egration with Microsoft Transaction Server (MTS ).
It provides high performance Internet platform for e -commerce and data warehousing.
The core pieces of Oracle Internet Platform are :

Browser bas ed clients to process presentation.


Application servers to execute business logic and serve presentation logic to
browser based clients.

Databases to execute database intensive business logic and serve data.

ENTITY RELATIONS HIP MODEL :


In an effective system data is divided into discrete categories or entities.
An ER Model is an illustration of various entities in a business and the relationships between
them.
It is built during the analysis phase of the System Developing Life Cycle.
ER Model separates the information required & the business from the activities performed.
ER MODEL BENEFITS :

It documents information for the organization in a clear, precise format.


Provides a clear picture of the scope of the information requirement.
Provides an easily understood pictorial map for the database design
It offers an effective framework for integrating multiple application.

KEY COMP ONENTS IN DIA ER MODEL :


ENTITY : It is a thing of significance about which the information need to be known.
ATTRIBUTES : It is something that describes or qualifies an entity.
** Each attribute may be mandatory or optional.
RELATI ONAL DATABAS E TERMI NOLOGY :
ROW OR TUPLE :
It represents all data required for a particular instance in an entity.
Each row is an entity is uniquely identified by declaring it as PRIMARY KEY or UNIQUE .
The order of the rows is not significant, while retrieving the data.
COLUMN OR ATTRIBUTE :
It represents one kind of data in a table
The column order is not significant when storing the data.

Oragle 10 g Material

A FIELD :
It can be found at the Intersection of a row and a column.
A Field can have only one value, or may not have a value at all, the absence of value in
Oracle is repres ented as NULL.
RELATI NG MULTIPLE TABLES :

Each table contains data that describes exactly only one entity.
Date about different entities is stored in different tables.
RDBMS enables the dat a in one table to be related to another table by using the foreign keys.
A Foreign Key is a column or a set of Column that refer to a Primary Key in the same table or
another table.

RATIONAL DATABAS E PROP ERTI ES :


Should not specify the access rout e to the tables, and should not reveal the physical arrange.
The Database is accessed using Structured Query Language ( SQL )
The language is a collection of set of operators.
STRUCTURED QUERY LANGUAGE STATEMENTS :
ORCLE SQL Compiles with industry accepted standards.
The different categories into which the SQL statements fall are

Data Retrieval Statements :


SELECT
Data Manipulation Language Statement ( DML )
INSE RT

ALTER
DROP
TRUNCA TE

Transaction Control Language Statement ( TCL )


COMMIT

DELETE

Data Definition Language Statement (DDL )


CREA TE
RENAME

UPDATE

ROLLBACK

SAVEPOINT

Data Control Language ( DCL )


GRA NT

REVOKE

ABOUT THE SQL BUFFER :

All Commands of SQL are typed at the SQL prompt.


Only one SQL Statement is managed in the SQL Buffer.
The Current SQL statement replaces the previous SQL statement in the Buffer.
The SQL statement can be divided int o different lines within the SQL Buffer.
Only one line i.e., the current line can be active at a time in the SQL Buffer.
At SQL prompt, editing is possible only in the current SQL Buffer line.

Oragle 10 g Material

E very statement of SQL should be terminated Using ;


One SQL statement can contains only one.
To run the previous or current SQL statement in the Buffer type / at SQL prompt.
To open the SQL Editor type ed at SQL prompt.

CREATING AND MANAGI NG TABLES :


DATABAS E OBJECTS :
A Oracle dat abase can contain multiple data structures.
The different Database objects in Oracle are :
TABLE :

Used to store date, Basic Unit

VIEW

Logically represents subsets of data from one or more tables.

SEQUENCE : Used to Generate Primary Key values.


INDEX : It is used to improve the performance of some queries.
SYNONYM : Used to give alternate names to objects.

Tables in ORACLE 8 / 9 / 10 :
Tables can be crated at any time, even when the users are using the dat abase.
Size of the table need not be specified.
The structure of the table can be modified online.
Rules to Create A Table :
The user should have permission or CREA TE TABLE command, and storage area.
The Table name should begin with a letter and can be 1 30 characters long.
Names can contain :
** A Z

** a - z

** 0 9

** - , $ , #

Names can not be duplicated for another object in the same ORACLE Server.
Names cannot be oracle servers reserved word
Names are not case sensitive
Create Table Statement :
Syntax :
SQL > CREA TE Table < Table_Name >
(
Column_Name1 < Data type > (Width),
Column_Name2 < Data type > (Width),
:
:
Column_Namen < Data type > (Width)
);

Oragle 10 g Material

Building Blocks of SQL Statements :


* Data types

* Literals

* Pseudo Columns * Comments

* Format Models

* Nulls

* Database Objects

* Schema Object Names and Qualifiers


* Syntax for Schema objects and parts of SQL Statements.
Data Types in Oracle :

Each value in ORACLE is manipulated by a date type.


The data types value associates fixed set of properties with the value.
The values of one data type are different from another dat a type.
The data type defines the domain of values that each column can contain.
The Built-in data types of ORA CLE are Categorized as

CHA RACTE R DA TA TYPES


NUMBE R DA TA TYPES
LONG AND RAW DA TA TYPES
DA TE TIME DA TA TYPES
LARGE OB JECT DA TA TYPES
ROWID DA TA TYPES

Character Data Types :


They store character data which can be Alphanumaric dat a
The Information can be

Words
Free Form Text
Database Character set
National Character set

They are less restrictive than other data types an have very few properties
The data is stored in strings with byte values
The information can belong to either

7 list ASCII Character set


EBCDIC

ORA CLE supports both single byte & multi byte character sets.
The different character data types are :

CHAR

NCHA R

VARCHAR2

NVARCHA R2

CHAR DATATYP E :

It specifies fixed length character string.


The size should be specified.
If the data is less than the original specified size, blank pads are applied
The default length is 1 Byte and the Maximum is 2000 Bytes.
The size of a character can range from 1 Byte to 4 Byte s depending on the database
character set.

Oragle 10 g Material

NCHAR DATATYP E :

It is first time defined in ORA CLE 9i, and contains Unicode data only.
The columns maximum length is determined by the National Character set definition.
The Maximum size allowed is 2000 Byte s and size has to be specified.
If the data is shorter than the actual size then the blank pads are applied.

Varchar Datatype :
It specifies the variable length character string.
The Minimum size is 1 Byte and the Maximum size is 4000 Byte s.
It occupies only that space for which the data is supplied.
Nvarchar Datatype :
It is first time defined in ORA CLE 9i.
It is defined for Unicode only date.
The minimum for the size is 1 Byte and maximum is 4000 Byte s.
NUMBER DATATYP ES :
Number Data Type :
It stores zero, positive and negative fixed and floating point numbers.
The range of magnitude is
1.0 * 10

-130

to 9.9 ..9 * 10

125

The general declaration is


NUMBER ( p , s )
P It specifies the precision, i.e., the total number of digits ( 1 to 38 )
S it specifies the scale, i.e., the number digits to the right of the decimal
point. It can range from 84 to 127.
Float Data Type :
It specifies to have a decimal point any where from the first to the last digit, or can have no
decimal point at all.
The scale value is not applicable to floating point numbers, as the number of digits that can
appear after the decimal point is not restricted.
Syntax :
Float It specifies a floating point number with decimal precision 38 or binary
precision of 126.
Float (B) It specified a floating point number with binary precision b.
The precision can range from 1 to 126.
To convert from binary to decimal precision multiply b by 0.30103.
To convert from decimal to binary precision multiply the decimal precision by
3.32193.
The maximum of 126 digits of binary precision is roughly equivalent to 38 digits of decimal
precision.

10

Oragle 10 g Material

Long & Raw Data Types :


Long Data Type :

This datatype stores variable lengt h charcgter strings.


It is used to store very lengt hy text strings
The length of LONG values may be limited by the memory available on the computer.
LONG columns can be referenced in
** SELECT Lists

** SET Clauses of UPDA TE statements

** VALUES clauses of INSE RT statements.


Restrictions :

A single table can contain only one LONG column.


Object types cannot be created on LONG attribut e.
LONG columns cannot appear in WHE RE clauses or in Integrity Constraints.
Indexes cannot be created on LONG Columns
LONG can be returned through a functions, but not through a stored procedure.
It can be declared in a PL/SQL unit but cannot be referenc ed in SQL.

DATE & TIMME DATA TYP ES :


Date Data Type :
It is used to store data and time information.
The dates can be specified as literals, using the Gregorian Calender.
The information revealed by date is :
* Century

* Year

* Month

* Date

* Hour

* Minute

* Second

The default date format in ORACLE is DD-MON-YY, and is specified in


NLS DATE FORMA T.
The default time accepted by ORA CLE dat e is 12 : 00 : 00 AM ( Midnight )
The default date accepted by ORACLE data is the First day of the Current Month.
The Date range provided by Oracle is
JANUARY 1, 4712 B C to DECEMBE R 31, 9999 AD.
Timestamp Data Type :
It is an extension of the DA TE data type.
It stores
* Day

* Month

* Minute

* Second

* Year

11

* Hour

Oragle 10 g Material

Syntax : TIMES TAMP [ { Fractional Seconds Precision } ]


Fractional Seconds Precision optionally specifies the number of digits in the
fractional part of the SECOND datetime field.
It can be a number in the range of 0 9 , with default as 6.
Raw & Long Raw Data Types :

RAW and LONG RAW data types are intended for storage of binary dat a or Byte Strings.
RAW and LONG RAW are variable length dat a types
They are mostly used to store graphics, sounds documents etc.
The ORACLE converts the RAW & LONG RAW data int o Hexadecimal form.
Each Hexadecimal character represents four bits of RAW data.

Large Object ( LOB ) Data Type s :


The Built in LOB data types are
* BLOB

* CLOB

* NCLOB

These data types are stored inernally.


The Bfile is an LOB which is stored externally
The LOB data types can store large and unstructured data like Text, Image, Video and
Spatial data.
The maximum size is upto 4 GB
LOB columns contain LOB locators, which can refer to out-of-line or in-line LOB values.
LOBs selection actually returns the LOBs locator.

BFILE Data Type :

It enables access to binary file LOBs whic h are stored in the file systems outside ORA CLE.
A BFILE column or the attributes stores the BFILE locator.
The BFILE locator maintains the directory alias and the filename.
The Binary File LOBs do not participate in transactions and are not recoverable.
The maximum size is 4 GB.

BLOG Data Type :


It stored unstructured Binary Large Objects
They are Bit streams with no character set semantics.
They are provided with full transactional support.
CLOB Data Type :
It stores single byte and multi byte character data
Both fixed width and variable width character sets are supported
They are provided with full transactional support.
NCLOB Data Type :
It stores Unicode data using the National Character set.

12

Oragle 10 g Material

ROWID Data Type :


Each row in the dat abas e has as address.
The rows address can be queried using the pseudo column ROWID.
ROWIDs efficiently support partitioned tables and Indexes.
Example :
SQL> Create Table Students
(
StuId
Number (6),
Fname
Varchar2(30),
Lname
Varchar2(30),
DOB
Date,
DOJ
Date,
Fees
Number(7,2),
Gender
Varchar2(1)
);
SQL > Create Table LabSpecification
(
ProdId
Number(6),
ProdPhoto
BLOB,
ProdGraphic
BFILE,
ProdDesc
LONG
);

Populating the Data into Tables :


INSERT Statement :
The INSERT statement is used to add rows to a
Table
Views Base Tables
A partition of a Partition Table.
A subpartition of a Composite_P artitioned Table
An object table
An object views base Table.
Insertion of data into a table can be executed in two ways.
o
o

Conventional INSERT
Direct path INSERT

In Conventional Insert statement, ORA CLE reuses free space in the table into which the data in
being inserted and maint ains referential integrity constraints.
In Direct-path insert , ORACLE appends the inserted data after existing data in the Table, the f ree
space is not reused.

13

Oragle 10 g Material

Syntax :
INSERT INTO < TABLE-NAME > ( COL1, COL2, .. )
VALUES ( VALUE1, VALUE2,....) ;

Examples:
INSERTING DATA INTO ALL COLUMNS OF A TABLE :
SQL> INSE RT INTO S TUDE NTS
VALUES (123, SAMPATH, KUMAR, 29 -JA N-80, 30-MA R-95, 25000,M) ;
In this case the values should be provided to all the columns that exist inside the table.
The order in which the values are declared in the values clause should follow the same order as
that of the original table order.
The char, varchar and data type data should be declared in single quotes.

INSERTING DATA INTO THE REQUIRED COLUMNS:


SQL> INSE RT INTO S TUDE NTS (Studno, Fname, Lname, Doj, Gender)
VALUES (1235,Raj, Kumar, 20-Feb-85, M) ;
In this case the order of the columns declared in the SELE CT list need not be the same order as
that of the original table.
The data values in the values clause should match with that of SELE CT list.
The columns for which the data is not supplied are filled with NULL values.
If the columns that were not supplied with data are declared with NOT NULL Constraints then the
INSE RT Statement is Rejected.
INSERTING NULL VALUES :
NULL Values can be ins erted in two ways
1.
2.

IMPLICIT
E XPLICT

Omit the column from the list.


Specify the NULL Keyword.
Specify Empty String , only for character strings and dates.

The targeted column should not be set as NOT NULL Constraint.

SQL> INSE RT INTO S TUDE NTS (StudNo, Fname, Lname, DOB, DOJ, Fees, Gender)
VALUES (1234,Kris hna, NULL, 28 -FEB-04, NULL, M) ;
INSERTING SPECIAL VALUES :
SYSDATE FUNCTION
It is a Pseudo column provided by the oracle.
The function returns the current date & time.
SQL>

INSE RT INTO Students (StudNo, Fname, DOJ, Fees, Gender)


Values (1234, Mohan, Sysdate, 25000,M) ;

14

Oragle 10 g Material

USER FUNCTION :
It is special function, which rec ords the current USER Name.
SQL> INSERT INTO Students (StudNO, Fname, Lname, DOJ, DOB, Fees)
Values (1234, Suresh, User, Sysdate, 25-jan-80, 30000) ;
SUBSTITUTION VARI ABLES :
These variables are used to stored values temporarily.
The values can be stored temporarily through
1. Single Ampersand (&)
2. Double Ampersand (&& )
3. DEFINE and ACCEP T Commands
The Single Ampersand substitution variable applies for each instanc e when the SQL statem ent is
create or executed.
The Double Ampersand substitution variables applied for all instances until that SQL statement is
existing.
USING SINGLE AMP ERS AND SUBSTITUTION VARTIABLE :
SQL> INSE RT INTO Students (StudID, Fname, LName, Dob, Fees)
VALUES (&StudNo, Name, &Last Name, Date of Birth, 25000) ;

USING DOUBLE AMP ERS AND SUBSTITUTION VARIABLE :


SQL> INSE RT INTO Students (StudNo, Fname, Lname, Dob, Doj, Fees, Gender)
Values (&StudNo, &FirstName, & LastName, Dob, Sysdate,
&&Fees, &Gender) ;
DEFINING CUSTOMI ED P ROMPTS :

Using the A CCEP T Command of SQL *Plus, the prompts can be customized.
ACCEP T Command stores the values in a variable.
PROMP T Command displays the Customized text.
After creating a script using the substitutions variable to a file it can called with A CCEP T and
PROMP T with greater meaning.

EXAMPLE:
ACCEP T Stud_id PROMP T Please Enter the Student Number:
ACCEP T Fir_name PROMP T Please Ent er the First Name:
ACCEP T Cou_fees PROMP T Please Enter the Course Fees:
SQL> INSE RT INTO Students (StudNo, Fname, Fees)
VALUES (&Stud_id ,&Fir_name, &Cou_fees) ;
EXAMPLE:
ACCEP T Department_Id PROMP T Please Enter the Department Number:
ACCEP T Department_Name PROMP T Please Enter the Department Name:
ACCEP T Location PROMP T Please E nter the Location:

15

Oragle 10 g Material

SQL> INSERT INTO DEP T (Deptno, Dname, Loc)


VALUES (&Dapartment_Id, &Department_Name, &Location ) ;
CREATING AN SQL SCRIPT FILE:
The SAVE Command is used to store the current cont ents of the SQL Buffer
Steps:
1.
2.
3.

At SQL prompt type the full name of the path where the file has to be created.
Give the name of the file with . sql extension.
If the file has to be replaced with the same existing name then use REPLA CE
ALL clause.

EXAMPLE:
SQL> SAVE D:\My Dir\SQLscript\Insert prompt.sql
SQL> SAVE D:\My Dir\SQLscript\Insert prompt.sql REPLACE ALL
QUERYI NG THE DATA FROM TABLES :
QUERY: It is an operation that retrieves data from from one or more tables or views.
SELECT STATEMENT:
The SELECT statement is used to retrieve dat a from one or more tables , object tables , views,
object views or management views.

PREREQUISITES :
The user must have the SELE CT privileges on the specified object.
The SELECT A NY TABLE allows to select the data from any recognized object.
CAP ABILITI ES IF SQK SEKECT STATEMENT :
The SELECT statement can be used to select or Retrieve data from the object using any one of
the following criteria.
o

SELECTION :

PROJECTION :

It chooses the rows in a table that are expected to return by a query.

It chooses the columns in a table that are expected to ret urn by a query.

JOIN :

It chooses the data in from one or more numbers of tables by creating a link
between them.

16

Oragle 10 g Material

Basi c SELECT Syntax :


SELECT [ DISTINCT ] { * , Column [ Alias ] , .. } From Table ;
SELECT Identifies Columns, FROM Identifies Tables .
SELECT Specifies a list of Column ( one / more )
DISTINCE Suppresses Duplicates
* Select all Columns.
COLUMN Selects the Named Column.
Alias Gives selected columns different columns.
FROM Table Specifies the table containing the columns.

WRITING SQL STATEMENTS TO S ELECT OR RETRIV E DATA FROM TABLES :


The Sample Tables Used :
Table 1 :

EMP
Column Name
Data Type
-----------------------------------------------------Empno
Ename
Deptno
Job
Sal
Comm
Mgr
Hiredate

Table 2 :

NUMBER
VARCHAR
NUMBER
VARCHAR
NUMBER
NUMBER
NUMBER
DATE

DEPT
Column Name
Data Type
-----------------------------------------------------Deptno
Dname
Loc

NUMBER
VARCHAR
VARCHAR

Table 3 : SALGRADE
Column Name
Data Type
-----------------------------------------------------Hi sal
Losal
Grade

NUMBER
NUMBER
NUMBER

17

Oragle 10 g Material

Retrieving Data from All Columns :


Sql > Select * from Emp;
Sql > Select * from Dept;
Sql > Select * from Salgrade;
In this the * is a projection operator.
It projects data from all the columns existing in the table with all records.
The data is displayed in a table format.
Retrieving Data from Specific Columns :
Sql > Select empno, ename, sal from emp;
Sql > Select ename, job, sal, deptno form emp;
Sql > Select deptno, dname, loc from dept;
Sql > Select Hisal, Losal, Grade from Salgrade;
Sql > Select empno, ename, sal , hiredate from emp;

The column names need not be in the same order as table.


The columns should be separat ed using comma.
The column nam es can be separated onto different lines within the SQL Buffer.
The casing of column names is not important.

Column Heading Defaults :


The default justification of the data after it is retrieved from the table is ..
LEFT Date and Character Data
RIGHT Numeric Data
The default display of the data is always is UPPER Casing.
The character and date column headings can be truncated, But numb ers cannot be
truncated.
Applying Arithmetical Operations in Select Statements :
Arithmetic Expressions can be implemented through SELE CT statement.
Arithmetic Expressions can be implemented to
o
o
o

Modify the way the data is displayed.


Perform calculations.
Implement WHAT IF Scenarios.

An Arithmetic Expression can cont ain


o
o
o

Simple Column names


Constant numeric values
Arithmetic operators.

18

Oragle 10 g Material

ARITHMETI C OP ERATORS :
The Arithmetic operators can be used to create expressions on NUMBER and DA TE data.
The Arithmetic operators supported are ..
o

Addition

Subtraction

Multiply

Divide

The Arithmetic operators can be used in any clause of a SQL statement. Except the FROM
clause.
SQL * Plus ignores Back Spaces before and after the Arit hmetic operator.
Sql > Select empno, ename, sal, sal + 500 from emp;
Sql > Select empno, ename, sal, sal 1000 from emp;
Operator Precedence :
Multiplication and Division take priority over addition and subt ractions ( * / + - )
Operators of the same priority are evaluat ed from left to right.
To prioritize evaluation and to increase clarity parent hesis can be implemented.
Sql > Select empno, ename, sal, ( 12 * sal ) + 100 from Emp;
Sql > Select empno, ename, sal, 12 * ( sal + 500 ) from Emp;
Handling Null Values :
NULL : It is a value which is
Unavailable
Unassigned
Unknown
Inapplicable
A NULL is not same as zero or blank space.
If a row lacks the data for a particular column, than that value is said to be NULL or to contain
NULL.
Sql > Select ename, job, sal, comm From Emp ;
If any column value is an Arithmetic expression is NULL, the overall result is also NULL.
The above situation is termed as NULL propagation and has to be handled very carefully.
Sql > Select ename, job, sal, comm, 12 * Sal + comm From Emp ;
Sql > Select ename, job, sal, comm, 12 * sal + comm from Emp ;

19

Oragle 10 g Material

NVL Function :
The NV L function is used to convert a NULL value to an actual value.
Syntax :
NVL ( Expr1 , Expr2 )

Expr1 : is the source value or expression that may contain NULL.


Expr2 : is the target value for converting NULL.

NVL Function can be used to convert any data type, the return value is always the same as the
data type of Expr1.
The Data types of the Sourc e and Destination must match
o
o
o

NVL ( Comm , 0 )
NVL ( Hiredate , 01-JUN-99)
NVL ( Job , Not Assigned)

Sql > Select Ename, Sal, Comm, Sal + NVL ( Comm, 0 ) From Emp;
Sql > Select Ename, Sal, Comm, ( Sal * 12 ) + NVL (Comm , 0 ) From Emp;
Sql > Select Ename, Sal, Comm, ( Sal + 500 ) + NVL ( Comm , 0 ) From Emp;

Working with Aliase s :


An Alias is an alternate name given for any Oracle Object.
Aliases is Oracle are of two types
** Column Alias

** Table Alias

Column Alias Renames a Column Heading


The Column alias is specified in the SELECT list by declari ng the Alias after the Column Name by
using the space separator.
ALIAS Headings appear is UPPER Casing by default.
The Alias should be declared in double quotes if it is against the specifications of Naming
Conversions.
The AS keyword can be used between the Column Name and Alias.
An alias effectively renames the SELE CT list item for the duration of the query.
An alias cannot be used, any where in the SELECT list for operational purpose.
Sql > Select Empno Numbers,
Ename Name,
Sal Basic Salary,
Job Designation
From Emp;
Sql> Select

Dept no AS
Dname AS
Loc
AS
From Dept;

Department Id ,
Department Name ,
Place

20

Oragle 10 g Material

Sql> Select

Hisal As
Losal As
Grade
From Salgrade ;

Maximum Range ,
Minimum Range ,

LITERALS IN ORACLE :
A Literal and a Constant value are synonyms to one another and refer to a fix ed data value.
The types of Literals recognized by Oracle are
o
o
o
o

Text Literals
Integer Literals
Number Literals
Interval Literals

Text Literals :
It specifies a text or character literal.
It is used to specify values whenever text or CHAR appear in
** Expression

** Condition

** SQL Function

** SQL Statements.

It should be enclosed in single quotes


They have properties of both CHAR and VARCHAR2 data types.
A text literal can have a maximum length of 4000 Bytes.
Ex :

mployee Information
Managers Specification
N n char Literal

Using Literal Character Strings :

A literal that is declared in a SELECT list can be a character, a Number, or a Date.


A literal is not a column name or a column alias.
A literal is printed for each row, that is retrieved by the SELE CT statement.
Literal strings of Free-Form test can be included in the query as per the requirement.
Date and character literals must be enclos ed within the single quotation marks
Literals increase the readability of the output.
Sql > Select Ename | | : | | Month Salary = | | Sal As Salaries From Emp ;
Sql > Select The Designation of | | Ename | | is | | Job As Designation From
Emp;
Sql > Select The Annual Salary of | | Ename | | is | | Sal * 12 As
Annual_Salary From Emp ;
Sql > Select Dname | | Department is Located at | | Loc From Dept ;
Sql > Select Ename | | Joined the Organization on | | Hiredat e From Emp ;
Sql > Select Ename | | Works in Department Number | | Deptno | | as
| | Job From Emp ;

21

Oragle 10 g Material

Applying Concatenation Operator :


The Concatenation operator links columns to other columns, Arithmetic expressions, or constant
values.
Columns on either side of the operator are combined to make a single output column.
The resultant column is treated as an character expression.
The Concatenation operator is represented in Oracle by double pipe symbol ( | | )
Sql > Select Empno || Ename || , Designation is || Job Employees Information
From Emp ;
Sql > Select The Basic Salary of || Ename || is Rs || Sal Employee From Emp ;

Eliminating the Duplicate Rows from the Output :

Until it is instructed SQL * Plus displays the results of a query wit hout eliminating duplic ate rows.
To eliminate the duplicate rows in the result, the DIS TINCT keyword is used.
Multiple columns can be declared after the DIS TINCT qualifier.
The DIS TINCT qualifier affects all the selected columns, and represents a distinct combination of
the columns.
Sql > Select DISTINCT Deptno From Emp ;
Sql > Select DISTINCT Job , Deptno From Emp ;
Sql > Select DISTINCT Deptno , Job From Emp ;

Filtering of Records :
The number of rows returned by a query can be limited using the WHERE clause.
A WHERE Clause contains a condition that must be met and should directly follow the From
Claus e.
Syntax :
SELECT [ Distinct ] { * | Column [ alias ] , .} From Table [ WHERE Condition(s) ] ;
The WHERE clause can compares
**
**
**
**

Values in Columns
Literal Values
Arithmetic Expressions
Functions

The components of WHE RE clause are


** Column Name
** Comparison Operat or
** Column Name, constant or list of values.
The Character strings and dates should be enclosed in single quotation marks.
Character values are case sensitive and Date values are format sensitive (DD-MON-YY)
The Comparison operat or are used in conditions that compare one expression to another.

22

Oragle 10 g Material

The different comparison operat ors are


** =

** < > , ! = , ^ = , ** > ** <

** > =

** < =

The format of the WHERE clause is WHERE Expr operator value.


Examples :
Sql > Select Ename, Sal, Job From Emp Where Job = MANAGE R
Sql > Select Ename, Hiredate , Deptno, Sal From Emp Where Deptno = 10 ;
Sql > Select Empno, Ename, Sal From Emp Where Sal > = 3000 ;
Sql > Select Ename || Joined on || Hiredat e Employees Joining Dates
From Emp Where Hiredate = 01 JA N 95 ;
Sql > Select Ename || Works in Department || Deptno Employ ees and
Deaprtments From Emp Where Deptno < > 20 ;
Sql > Select Ename, Sal, Deptno, Job From Emp Whe re Job < > CLERK ;
Sql > Select Ename Name , Sal Basic , Sal * 12 Annual From Emp
Where Sal * 12 > 6000 ;
Logical Operators :
The Logical operators combine the results of two components conditions to produce a single
result.
The Logical operators provided by Oracle are
**

AND

**

OR

**

NOT

AND Operator :
It Returns TRUE if both or all component conditions are TRUE.
It Returns FALSE if either is FALSE, else returns unknown.
Truth Table :
AND

TRUE

FALS E

NULL

TRUE

NULL

FALS E

NULL

NULL

NULL

Sql > Select Empno, Ename, Job, Sal From Emp Where Sal > = 1100 AND
Job = CLE RK ;
Sql > Select Empno, Ename , Job , Sal From Emp Where Deptno = 10
AND Job = MANAGE R ;
Sql > Select Ename, Sal , Job From Emp Where Sal > = 1500 AND Sal > 5000 ;

23

Oragle 10 g Material

Sql > Select Ename, Sal, Job From Emp Where ( Sal > = 1500 A ND Sal < = 5000 )
AND Job = MANAGE R ;
OR Operator :
It returns TRUE if either component conditions is TRUE
It returns FALSE if both are FALSE, else returns unknown
Truth Table :
OR

TRUE

FALS E

NULL

TRUE

FALS E

NULL

NULL

NULL

NULL

Sql > Select Empno, Ename, Job, Sal From Emp Where S al > = 1100 OR
Job = CLERK ;
Sql > Select Empno, Ename, Job, Sal From Emp Where Deptno = 10
OR Job = MANAGE R ;
Sql > Select Ename, Sal, Job From Emp Where Sal > = 1500 OR Sal > = 5000 ;
Sql > Select Ename, Sal, Job, Deptno From Emp Where Dept no = 10 OR Deptno = 20 ;
Sql > Select Ename, Sal, Job From Emp Where Job = CLE RK OR Job=MANAGE R ;
Sql > Select Ename, Sal, Job From Emp Where ( Sal < = 2500 OR Sal > = 5000 ) OR
Job = MANAGER ;
NOT Operator :
It returns TRUE if the following condition is FALSE.
It returns FALSE if the following condition is TRUE.
If the condition is Unknown, it returns Unk nown.
Truth Table :
TRUE
NOT

FALS E

NULL

NULL

Combination of AND and OR Operators :


Sql > Select Empno, Ename, Job, Sal From Emp Where ( Sal > 1100 OR Job=CLE RK )
AND Deptno = 20 ;
Sql > Select Empno, Ename, Job, Sal From Emp Where ( Deptno = 10 A ND
Job = MANAGER ) OR Sal > = 3000 ;

24

Oragle 10 g Material

Not Operator Examples :


Sql > Select Ename, Sal, Job From Emp Where NOT Job = MANAGE R ;
Sql > Select Ename, Sal, Job From Emp Where NOT Sal > 5000 ;
Sql > Select Ename, Sal, Job From Emp Where NOT Sal < 5000 ;
Sql > Select Ename, Sal, Hiredate From Emp Where Not Hiredate=20-FEB -81 ;
Sql > Select Ename, Job, Sal, Deptno From Emp Where NOT
Job = SALESMAN AND Deptno = 30 ;
Some Things To Note .
Sql > Select Ename, Sal, Job From Emp Where Job > MANAGE R ;
Sql > Select Ename, Sal, Job From Emp Where Job < MANAGE R ;
Sql > Select Ename, Sal, Hiredate From Emp Where Hiredate > 20-FEB -1981 ;
Sql > Select Ename, Sal, Hiredate From Emp Where Hiredate < 20-FEB -1981 ;
Sql > Select Ename, Sal, Hiredate From Emp Where Hiredate<>20 -FEB-1981 ;
Sql > Select Ename, Sal, Hiredate From Emp Where Job < > CLERK ;
Sql > Select Ename, Sal, Comm From Emp Where Comm is NULL ;
Sql > Select Ename, Sal, Job From Emp Where NOT Job > MANAGE R ;
Sql > Select Ename, Sal, Hiredate From Emp Where NOT
Hiredate = 17-DEC-1980 ;
Sql > Select Ename, Sal, Hiredate From Emp Where NOT
Hiredate > 17-DEC-1980 ;
Rules of Precedence :
The default Precedence order is
** All Comparison Operators
** NOT Operator
** AND Operator
** OR Operator
The Prec edence can be controlled using parenthesis.

25

Oragle 10 g Material

SQL * PLUS Operators :


BETWEEN . AND . ;
o
o
o

NOT BETWEEN .. AND .

This Operator is used to display rows based on a range of values.


The declared range is inclusive
The lower limit should be declared first.

Sql > Select Ename, Sal, Job From Emp Where Sal Between 1000 AND 1500 ;
Sql > Select Ename, Sal, Job From Emp Where Sal NOT Between 1000 AND 1500 ;
Sql > Select Ename, Sal, Job From Emp Where Job Between MANAGE R AND
SALESMAN ;
Sql > Select Ename, Sal, Job From Emp Where Job NOT Between MANAGE R AND
SALESMAN ;
Sql > Select Ename, Sal, Job, Hiredate From Emp Where Hiredate Between
17-FEB -1981 A ND 20-JUN-1983 ;
Sql > Select Ename, Sal, Job, Hiredate From Emp Where Hiredate NOT B etween
17-FEB -1981 A ND 20-JUN-1983 ;
IN Operator ; NOT IN Operator :
The Operator is used to test for values in a specified list.
The Operator can be used upon any datatype.
Sql > Select Ename, Sal, Job From Emp Where Ename IN( FORD, ALLEN ) ;
Sql > Select Ename , Sal, Job From Emp Where Ename NOT IN( FORD , ALLE N ) ;
Sql > Select Ename, Sal, Deptno From Emp Where Dept no IN( 10 , 30 ) ;
Sql > Select Ename, Sal, Deptno From Emp Where Dept no NOT IN( 10 , 30 ) ;
Sql > Select Ename, Sal, Hiredate From Emp Where
Hiredate IN( 20-FE IB-1981 , 09-JUN-1981 ) ;
Sql > Select Ename, Sal, Hiredate From Emp Where
Hiredate NOT IN( 20-FEIB -1981 , 09-JUN-1981 ) ;
IS NULL Operator ; IS NOT NULL Operator :
The Operator tests for NULL values
lt is the only operator that can be sued to test for NULLs.
NULL means the value is unavailable, Unassigned, Unknown, or inapplicable.
Sql > Select Ename, Deptno, Comm From Emp Where Comm IS NULL ;
Sql > Select Ename, Deptno, Job From Emp Where Mgr IS NULL ;

26

Oragle 10 g Material

Sql > Select Ename, Deptno, Comm From Emp Where Comm IS NOT NULL ;
Sql > Select Ename, Deptno, Comm From Emp Where Mgr IS NOT NULL ;
LIKE Operator ;

NOT LIKE Operator :

The LIKE Operat or is used to searc h to search for a matching character.


The character pattern matching operation is referred as a wild card search
The available wild cards in Oracle are
% Used to represent any sequenc e of Zero or more characters.
/ Represents any single character, only at that position only.
The Wild Card symbols can be used in any combination with literal characters.
For finding exact match for % and the ESCAPE option has to be used, which is \ symbol
with ESCAPE Option.
Sql > Select Ename, Job From Emp Where Ename LIKE S% ;
Sql > Select Ename, Job From Emp Where Ename NOT LIKE S% ;
Sql > Select Ename, Job From Emp Where Ename LIKE _A% ;
Sql > Select Ename Job From Emp Where Ename NOT LIKE _A% ;
Sql > Select Ename Sal From Emp Where Ename = SM% ;
Sql > Select Ename, Sal From Emp Where SM% LIKE Ename ;
Sql > Select Ename, Hiredate From Emp Where Hiredate LIKE % -FEB-1981 ;
Sql > Select Ename, Hiredate From Emp Where Hiredate LIKE 03 -%-1981 ;
Sql > Select * From Dept Where Dname LIKE %\_% ESCAPE \ ;

Ordering Information :
The Order of rows returned in a query result is undefined.
The ORDE R BY Clause can be us ed to sort the rows
The ORDE R BY Clause should be the last clause in the order of all clauses in the SELE CT
statement.
An expression or an alias can be specified to sort.
Default ordering of Data is Ascending
** Numbers

1 999

** Dates

Earliest Late st

** Strings

A Z ; NULLS Last.

27

Oragle 10 g Material

Syntax :
SELECT Expr From Table Name [ WHERE Condition(s) ]
[ ORDE R BY { Column, Expr } [ ASC / DESC ] ] ;
The default ordering upon a column is Ascending, to change the default ordering DESC should
be used after the column name.
Sorting can be implemented on column aliases, and can also be implemented upon multiple
columns.
The controversy of sorting is broken only when there arises a conflict of consistency upon the
data in a column.
Sql > Select Ename, Job, Deptno, Hiredate From Emp ORDER BY Hiredate ;
Sql > Select Ename, Job, Deptno, Hiredate From Emp ORDER BY Hiredate DES C ;
Sql > Select Ename, Job, Sal From Emp Where Job = MANAGE R ORDER BY Sal ;
Sql > Select Ename, Job, Sal From Emp Where Sal > = 2500 ORDER BY Job,
Ename DESC ;
Sql > Select Empno, Ename, Sal, Sal * 12 Annsal From Emp ORDER BY Annsal ;
Sql > Select Empno, Ename, Sal From Emp ORDER BY Deptno, Sal, Hiredate ;
Sql > Select Empno, Ename, Sal From Emp Where Sal > = 2000 ORDE R BY Hiredate,
Sal DESC ;
The single row functions can appear in
**
**
**
**

SELECT List
WHERE List
START W ITH Claus e
CONNE CT BY Clause

The types of single row functions are


** CHA RACTE R

** NUMBE R

** DATE

** CONVE RSION

Multiple Row Functions :


These functions manipulate groups of rows to give one result per group of rows .
Single Row Functions :
They are used to manipulate data items.
They accept one or more arguments and return one value for each row returned by the query.
An argument can be :
**
**
**
**

User Supplied Constant.


Variable Value.
Column Name.
Expression.

28

Oragle 10 g Material

Syntax :
Func_Name ( Column / Expr, [ Arg1, Arg2, ] )
Single Row Functions Features :

Acts on each row returned in the Query.


Return one result per row
May return a dat a value of a different type than that referenced
May expert one or more arguments.
Can be used in SELECT, WHE RE and ORDER BY Clauses.
Can be nested.

Specification Behavior of Functions :


Character Functions : Accept Character input and can return both Character and
Number Values.
Number Functions : Accept Numeric input and return Numeric Values.
Date Functions

: Operate on values of date data type, can return bot h Date and
Number.
Conversion Function : Covert a value from one data type to another.
General Functions

** NVL Operat es on NULL Values.


** DECODE Operates on any data type and can return any dat a type.
Character Functions :

They are functions that return character values, unless stated.


They return the data type VARCHA R2, limited to a length of 4000 Bytes
If the return value length exceeds, then the ret urn value is truncated, without an error.
The functions are categorized as
** CHA RACTE R MANIPULA TION FUNCTIONS.
** CASE CONVE RS ION FUNCTIONS.

Character Manipulation Functions :


Lower Function :
It converts Alpha character values to lower case
The return value has the same dat a type as argument char type ( CHA R or VARCHAR2 )
Syntax : LOWER ( Column / Expression )
Sql > Select LOWER( ORA CLE CORPORA TION ) From Dual ;
Sql > Select Ename, LOWER ( MY INFORMA TION ) From Emp;
Sql > Select Ename, LOWER ( Ename ) From Emp Where Job = MANAGE R ;

29

Oragle 10 g Material

Sql > Select The || Ename || s Designation is || Job From Emp


Where LOWER ( Job ) = manager ;
Upper Function :
It Converts the Alpha character values to Upper Case.
The return value has the same dat a type as the argument char.
Syntax :

UPPER ( Column / Expression )

Sql > Select Upper ( Oracle Corporation ) From Dual ;


Sql > Select Ename, Upper ( My Information ) From Dual ;
Sql > Select Ename, Lower ( Ename ), Upper ( Ename ) From Emp
Where Job = MANAGER ;
Sql > Select Ename, Job From Emp Where Job = Upper ( Manager ) ;
Sql > Select Ename, Job, Sal, Sal * 12 From Emp Where Job =
Upper ( Lower ( MANGE R ) ) ;
Sql > Select The || Ename || s Designation is || Lower ( Job ) Where
Job = Upper ( manager ) Order By Sal ;
Sql > Select Upper ( The || Ename || s Basic Salary is Rupees || Sal )
Em
ployee Salaries From Emp Where Job In( MA NAGER ,
Upper ( clerk ) ) Order By Sal Desc ;
INITCAP Function :
It converts the Alpha character values to Uppercase for the first letter of each word, keeping all
other letters in Lower case.
Words are delimited by White spaces or characters that are not alphanumeric.
Syntax :

INITCAP ( Column / Expression )

Sql > Select Initcap ( oracle corporation ) From Dual ;


Sql > Select The Job Title for || Initcap ( E name ) || is || lower ( Job ) Det ails
From Emp;
Sql > Select Ename, Upper ( Ename ) , Lower ( Ename ) , Initcap ( Ename ) From Emp ;
Sql > Select Empno, Initcap ( Ename ), Deptno From Emp Where
Ename = Upper ( blake ) ;
CONCAT Function :
It Concatenates the first characters value to the second charactger value. Only two parameters
accept .
It return the character data type.

30

Oragle 10 g Material

Syntax :

CONCAT ( Column1 / Expr1, Column2 / Expr2 )

Sql > Select Concat ( Oracle , Corporation ) From Dual ;


Sql > Select Ename, Job, Concat ( Ename, Job ) From Emp Where Deptno = 10 ;
Sql > Select Concat ( The Employee Name is , Initcap ( Ename ) ) As
Employee Names From Emp Where Deptno in( 10, 30 ) ;
Sql > Select Concat ( Concat ( Initcap ( Ename ), is a ) , Job ) Job From Emp
Where Dept no in( 10, 20 ) ;
SUB STRING Function :
Returns specified characters form character value, starting from a specified position
m , to n characters long.
Points to Remember .
o
o
o
o
o

If m is 0 , it is treated as 1.
If m is positive, Oracle counts from the beginning of char to find the first character.
If m is Negative, Oracle counts backwards from the end of the Character.
If n is Omitted , Oracle returns all characters to the end of Char.
If n is less than 1 or 0 , A NULL is returned.

Floating point numbers passed as arguments to Substr are automatically converted to Integers.
Syntax : SUBSTR ( Col / Expr, m, n )
Sql > Select Substr ( ABCDEFGH , 3, 4 ) From Dual ;
Sql > Select Substr ( ABCDEFGH , -5, 4 ) From Dual ;
Sql > Select Substr ( ABCDEFGH , 0 ,4 ) From Dual ;
Sql > Select Substr ( ABCDEFGH , 4 ) From Dual ;
Sql > Select Substr ( ABCDEFGH, 4, 0 ) From Dual ;
Sql > Select Substr ( ABCDEFGH, 4 , -2 ) From Dual ;
Sql > Select Ename, Job From Emp Where Substr ( Job, 4, 3 ) = Upper( age ) ;
Sql > Select Concat ( Initcap ( Ename ) ,
Concat ( is a , Concat ( Initcap (S ubstr ( Job, 1, 3 ) ), Eater. ) ) )
From Emp Where Substr ( Job , 4, 3 ) = Upper ( Age ) ;

LENGTH Function :
Returns the number of characters in a value.
If the char has data type CHA R, the length includes all trailing blanks.
If the char is NULL , it return NULL .

31

Oragle 10 g Material

Syntax :

LENGTH ( Column / Expression )

Sql > Select Length ( ORA CLE) From Dual ;


Sql > Select Length ( Ename ) || Characters exit in || Initcap ( Ename ) || s Name.
As Names and Lengths From Emp ;
Sql > Select Initcap( Ename ) , Job from Emp Where Length ( Job ) = 7 ;
Sql > Select Inticap ( Ename ) , Job From Emp Where Substr ( Job, 4, Lengt h (
Substr ( Job, 4, 3 ) ) ) = AGE ;
INSTRING Function :
It returns the numeric position of a named character.
Syntax : INSTR ( Column / Expression, Char , n, m )
Searches for Column / Expression beginning with its n th character for the m th occurrenc e of
char2, and returns the position of the character in char1, that is the first character of this
occurrence.
n can be positive or negative, if negative searches backward from the end of column /
Expression.
The value of m should be positive .
The default values of bot h m and n are 1.
The return value is relative to the beginning of char1 regardless o f the value of n, and is
expressed in characters.
If the search is unsuccessful, the return value is zero.
Sql > Select Instr ( String , r) From Dual ;
Sql > Select Instr ( CORP ORA TE FOOR, OR, 3, 2 ) From Dual ;
Sql > Select Instr ( CORP ORA TE FLOOR, OR, -3, 2 ) From Dual ;
Sql > Select Job, Instr ( Job, A, 1, 2) From Emp Where Job = MANAGER ;
Sql > Select Job, Instr ( Job, A, 2, 2 ) From Emp Where Job = MANA GER ;
Sql > Select Job, Instr ( Job, A, 3, 2 ) From Emp Where Job = MANA GER ;
Sql > Select Job, Instr ( Job, A, 2 ) From Emp Where Job = MANAGER ;

LPAD Function :
Pads the character value right justified to al total width of n character positions.
The default padding character is space.
Syntax : LPAD ( Char1, n, Char 2 )
Sql > Select Lpad ( Page 1, 15, *. ) From Dual ;

32

Oragle 10 g Material

Sql > Select Lpad ( Page 1, 15) From Dual ;


Sql > Select Ename, Lpad (E name, 10, - ) from Emp Where Sal > = 2500 ;
RPAD Function :
Pads the character value left justified to a total width of n character positions.
The Default padding character is space.
Syntax : RPAD ( Char1, n, Char 2 )
Sql > Select Rpad ( Page 1 , 15, *. ) From Dual ;
Sql > Select Rpad ( Page 1 , 15 ) From Dual ;
Sql > Select Ename, Rpad(Ename, 10, - ) From Emp Where Sal > = 2500 ;
Sql > Select Ename, Lpad ( Ename, 10, - ) , Rpad ( Ename, 10, - ) From Emp ;
Sql > Select Ename, Lpad ( Rpad ( Ename, 10, - ), 15, - ) From Emp ;
LTRIM Function :
It enables to trim heading characters from a character string.
All the leftmost characters that appear in the set are removed.
Syntax :

LTRIM ( Char, set )

Sql > Select Ltrim ( xyzXxyLAS T WORD, xy ) From Dual ;


Sql > Select Job, Ltrim ( Job ) From Emp Where Job Like MA NAGE R ;
RTRIM Function :
It enables the trimming of trailing characters from a character String.
All the right most characters that appear in the set are removed.
Syntax :

RTRIM ( Char, set )

Sql > Select Rtrim ( BROWNINGyx Xxy, xy ) From Dual ;


Sql > Select Rtrim ( Job, ER ) , Job From Emp Where Ltrim ( Job , MAN ) Like GE R ;
TRIM Function ( 8 i )

It enables to trim heading or trailing characters or bot h from a character string.


If Leading is specified concentrates on leading characters.
If Trailing is specified concentrates on trailing characters.
If Both or none is specified concentrat es both on leading and trailing.
Returns the varchar2 type.
Syntax : TRIM ( Leading / Trailing / Both, Trim character From Trim source )
Sql > Select Trim ( S From MITHSS ) From Dual ;
Sql > Select Trim ( S From SSMITH ) From Dual ;

33

Oragle 10 g Material

Sql > Select Trim ( S From SSMITHSS ) From Dual ;


Sql > Select Trim ( Trailing S From SSMITHSS ) From Dual ;
Sql > Select Trim ( Leading S From SSMITHSS ) From Dual ;
Sql > Select Trim ( Both S From SSMITHSS ) From dual ;
REPLACE Function :
It returns the every Occurrence of search string replaced by the replacement string.
If the replacement string is omitted or null, all occurrences of search string are removed.
It substitutes one string for anot her as well as to remove character strings.
Syntax : REPLACE ( Char, Search_Str, Replace_Str )
Sql > Select Replace ( Jack and Jue , J, BL) From Dual ;
Sql > Select Ename, Replace(Job, MAN, DAM ) From Emp Where Job = MANAGER ;
Sql > Select Job, Replace ( Job, P ) From Emp Where Job = PRESIDENT ;
Sql > Select Job, Replace ( Job, MAN, E XE CUTIVE ) From Emp Where
Job = SALES MAN ;

TRANS LATE Function :


Used to Translate Character by character in a String .
Syntax :

TRANS LATE ( char, From, To )

It returns a char with all occurrences of each character in From replaced by its corresponding
character in To .
Characters in char that are not in From are not replaced.
The argument From can contain more characters than To.
If the extra characters appear in Char, they are removed from the ret urn value.
Sql > Select Job, Translate ( Job, P, ) From Emp Where Job = PRESIDE NT ;
Sql > Select Job, Translate ( Job, MN, DM ) From Emp Where Job = MANAGE R ;
Sql > Select Job, Translate ( Job, A, O ) From Emp Where Job = SALESMAN ;
CHR Function :
It returns a character having the binary equivalent to n .
It returns the equivalent for n in database character set or national character set.
Syntax : CHR ( n )

CHR ( n Using NCHAR_CS )

Sql > Select Chr ( 67 ) || Chr (65 ) || Chr ( 84 ) Sample From Dual ;
Sql > Select Chr ( 16705 Using NCHAR_CS ) From Dual ;

34

Oragle 10 g Material

ASCII Function :
It returns the decimal representation in the character database set of the first characters of the
Char.
Syntax :

ASCII ( Char )

Sql > Select Ascii ( A ) , Ascii ( APPLE) From Dual ;


NUMBER Functions :
These functions accept numeric input and ret urn numeric values.
Many functions return values that are accurate to 38 decimal digits.
ROUND Function :
Syntax : ROUND ( n, m )

It returns n rounded to n places right of the decimal point.


If m is omitted, n is rounded to 0, places
m can be negative, and rounds off the digits to the left of the decimal point.
M must be an integer.
Sql > Select Round ( 15.193, 1 ) From Dual ;
Sql > Select Round ( 15.193, -1 ) From Dual ;
Sql > Select Round ( 45923, 2 ) , Round ( 45.923, 0 ) , Round ( 45, 923, -1 ) From Dual ;

TRUNCATE Function :
Syntax : TRUNC ( n, m )
It returns n trunc ated to m decimal places.
If m is omitted, n is truncated to 0 places.
n can be negative to truncate m digits left to the decimal point.
Sql > Select Trunc ( 15.79, 1) From Dual ;
Sql > Select Trunc ( 15.79, -1 ) From Dual ;
Sql > Select Trunc ( 45.923, 2 ) , Trunc ( 42.923 ), Trunc ( 45.923, -1 ) From Dual ;
CEIL Function :
Syntax : CEIL ( n )
Returns the smallest integer great er than or equal to n .
The adjustment is done to the highest nearest decimal value.
Sql > Select Ceil ( 15.7 ) From Dual ;
Sql > Select Ceil ( 14.27 ) , Ceil ( 14.2 ) , Ceil ( 14 ) From Dual ;

35

Oragle 10 g Material

FLOOR Function :
Syntax : FLOOR ( n )
Returns the largest integer less than or Equal than n .
The adjustment is done to the lowest nearest decimal values.
Sql > Select Floor ( 15.7 ) From Dual ;
Sql > Select Floor ( 14.27 ) , Floor ( 14.2 ) , Floor ( 14 ) From Dual ;
MODULUS Function :
Syntax : MOD ( m, n )
It returns remainder m divided by n .
It returns m if n is 0.
Sql > Select Mod ( 11, 4 ) , Mod ( 10 , 2 ) From Dual ;
POWER Function :
Syntax : POWER ( m, n )
Returns m raised to the nth power.
The base m and the exponent n can be any numbers.
If m is negative, n must be an integer
Sql > Select Power ( 3, 2 ), Power ( -3, 2 ) From Dual ;
Sql > Select Power ( 3, -2 ) , Power ( -3, -2 ) From Dual ;
Sql > Select Power ( -3. 5, -2 ), Power ( 3, -2.5 ) From Dual ;
Sql > Select Power ( -3. 5, 2.5 ) , Power ( 3.5, -2.5 ) From Dual ;
SQUARE ROOT Function :
Syntax : SQRT ( n )
It returns square root of n.
The value of n cannot be negative
SQRT returns a real result.
Sql > Select Sqrt ( 25 ) From Dual ;
ABSOLUTE Function :
Syntax : ABS ( n )
It returns the abs olute value of n.
Sql > Select Abs ( -15 ) From Dual ;

36

Oragle 10 g Material

Sql > Select Sal, Comm, Sal Comm, Abs ( Sal Comm ) From Emp
Where Comm = 1400 ;
SIGN Function :
Syntax :

It
If
If
If

SIGN ( n )

returns the SIGN, specific ation of a number.


n < 0 , return 1
n = 0 , return 0
n > 0, return 1

Sql > Select Sign ( -15 ), Sign ( 15 ) , Sign ( 0 ) From Dual ;


Sql > Select Sal, Comm, Sign( Sal Comm ) From Emp Where Sign( Sal Comm ) = -1

WORKING WITH DATES :

Oracle stores dates in an int ernal numeric format.


The dates in Oracle range from January 1, 4712 BC to December 31, 9999 AD.
The default display and input format for any date is DD-MON-YY.
The numeric format repres ents
** Century

** Year

** Minutes

** Seconds

** Month

** Day ** Hours

SYSDATE :
It is a date function that ret urns current date and time .
SYSDATE is generally selected upon a DUMMY Table.
Sql > Select SYSDATE From Dual ;
Date Arithmetic :
As database stores dates as numbers, Arithmetic operations can be implemented.
Number constants can be added or subtracted upon dates.
The operations that can be applied are
o
o
o
o

Date
Date
Date
Date

+ Number Date ; Adds number of days to a date


- Number Date : Subtracts Number of days from a date.
Date Number of days ; Subtracts one date from another.
+ Number / 24 Date ; Adds Number of Hours to a date.

Sql > Select Sysdate, Sysdate + 3 From Dual ;


Sql > Select Sysdate, Sysdte 3 , Sysdate +_ 72 / 24 From Dual ;
Sql > Select Ename, Hiredate, Hiredate + 3 From Emp ;
Sql > Select Ename, Hiredate, Hiredate 3 From Emp ;
Sql > Select Ename, Hidrdate, Sysdate Hiredate From Emp ;

37

Oragle 10 g Material

Sql > Select Ename, ( Sysdate Hiredate ) / 7 Weeks From Emp Where Deptno = 10 ;

DATE Functions :
Add_Months Function :
Syntax : ADD_MONTHS ( D, n )
It returns the dat e d plus n months
The argumennt n can be any integer
Sql > Select Sysdate , Add_mont hs ( Sysdate, 2 ) From Dual ;
Sql > Select Sal,l Hiredate, Add_months ( Hiredate, 2 ) From Emp Where
Dept no = 20 ;
Months_Between Function :
Syntax : Months_Between ( D1, D2 )
It returns number of months bet ween dates d1 and d2.
If d1 is later than d2, the result is Positive, else Negative.
If d1 is and d2 are either the same days of the months or both last days of the months,
the result is always an integer.
Sql > Select Empno, Hiredate, Mont hs_Between ( Sysdate , Hiredate ) From Emp
Where Months_Bet ween ( Sysdate, Hiredate ) < 2000 ;
Sql > Select Ename, Months_Between ( Sysdate , Hiredate ) From Emp ;
Next_Day Function:
Syntax : Next_day( d, Char )
It returns the dat e of the first week day named by char, that is later than the date d.
The CHAR must be a day of the week in the sessions date language.
The day of the week can be full name or the abbreviation.
Sql > Select Sysdate, Next_day ( Sysdate, WED ) From Dual ;
Sql > Select Sal, Hiredate, Next_day ( Hiredate, MONDAY ) From Dual ;
Last_Day Function :
Syntax : Last_day ( d )
It returns the dat e of the last day of the month that contains d.
Mostly used to determine how many days are left in the current month .
Sql > Select Sysdate, Last_day ( Sysdate ) Last, Last_day ( Sysdate ) Sysdate
Daysleft From Dual ;
Rounding of Date s :

38

Oragle 10 g Material

Syntax : Round ( Date, Format )


Returns Dat e rounded to the Unit specified by the format.
If format is omitted, Date is rounded to the nearest day.
Sql > Select Round ( Sysdate , DAY ) From Dual ;
Sql > Select Round ( Sysdate, MONTH ) From Dual ;
Sql > Select Round ( Sysdate , YEAR ) From Dual ;
Truncating Dates :
Syntax : Trunc ( Date, Format )
Return Date with the time portion of the day truncated to the specified unit.
If format is omitted, date is truncated to the nearest day.
Sql > Select Round ( Sysdate, DAY ) , Trunc ( Sysdate, DAY ) From Dual ;
Sql > Select Round ( Sysdate, MONTH ), Trunc ( Sysdate, MONTH ) From Dual ;
Sql > Select Round ( Sysdate, YEAR ) , Trunc ( Sysdate, YEAR ) From Dual ;
Conversion Functions :
The Conversion functions convert a value from one data type to another .
The Data type conversion in Oracle is of two types
** Implicit Data type Conversion
** Explicit Data type Conversion
Implicit Data type Conversion :
Implicit Data type Conversions work according to the conversion specified by Oracle.
The assignment succeeds if the Oracle serves can convert the datatype of the value.
CHA R to NUMBER Conversions succeed only if the character strings represents a valid
NUMBE R.
CHA R to DA TE Conversions succeed only if the character strings represent the default
format DD-MON-YY.
IN ASSIGNMENTS

IN EXPRESSIONS

* Varchar2 / Char Number

* Varchar2/ Char Number

* Varchar2 / Char Date

* Varchar2 / Char Date

* Number Varchar2
* Date Varchar2
Explicit Data type Conversion :
SQL provides three functions to convert a value from one data type to another.

39

Oragle 10 g Material

The Functions are

* To_Char

For Conversion to Characters

* To_Date

For Conversion to Dates

* To_Number

For Conversion to Numbers

To_Char Conversion Function :


This function can be used in two different flavors
To_Char ( Number Conversion )
To_Char ( Date Concersion )
To_Char ( Number Conversion ) :
Syntax : To_char ( Number , fmt, nlsparms )
o
o
o

Converts number of number data type to a value of Varchar2 dat a type.


Fmt is the optional number format, that can be used.
The nlsparms specifies the characters returned by the number format elemtns.

To_Char ( Date Conversion ) :


Syntax : To_Char ( Date, fmt, nlsparams )
Converts Date of DA TE data type to a value of Varchar2 data type in the format
specified.
Fmt is the optional date format, that can be used.
The nlsparams specifies the language in which month and day names and
abbreviations are returned.
Formatting Models :
A formatting model is a character literal that describes the format of DA TE or Number data stored
in a character string.
D 99D99 :
o
o
o

It returns the specified position of the decimal character.


The default decimal delimites is a period ( . )
Only one decimal character can be specified in a number format model.

Sql > Select To_char ( 1234, 99999D99 ) From Dual ;


Sql > Select To_char ( 1234, 999D99 ) From Dual ;
EEEE 9.9EEEE :
o

Returns a value using scientific not ation.

Sql > Select To_char ( 1234 , 9.9EEEE ) , To_char ( 1234, 9.99EEEE ) From Dual ;
G 9G999 :

40

Oragle 10 g Material

o
o

Returns the specified position of the group separat or


Multiple group separators can be specified.

Sql > Select To_char ( 1234567, 99G99G999 ) From Dual ;


Sql > Select Sal, To_char ( Sal, 99G999D99 ) From Emp ;
L L999 :
o

Returns the specified position of the local currency symbol.

Sql > Select To_char ( 1234, L9999) From Dual ;


Sql > Select Sal, To_char ( Sal, L999999 ) Currency From Emp Where Deptno = 10 ;
Sql > Select Sal, To_char ( Sal, L99G999D99, NLS_CURRENCY = IndRupees )
Salary From Emp Where Deptno = 20 ;
MI 9999MI :
o
o
o

Returns Negative value with a trailing minus sign ( - ).


Return Positive value with a trailing blank.
MI format should be declared as trailing argument only.

Sql > Select To_char ( -10000, L99G999D99MI ) From Dual ;


Sql > Select Sal, Comm, Comm_sal, To_char ( Comm Sal , L99999MI ) From Emp
Where Dept no in(10, 20, 30 ) ;
PR 9999PR :
o
o

Returns Negative value in < angle Brackets >


It can appear only as trailing declaration.

Sql > Select To_char ( -1000 , L99G999D99P R ) From Dual ;


Sql > Select Sal, Comm, Comm Sal , To_char ( Comm Sal , L99999PR ) From Emp
RN Returns a value as Roman Number in Upper Case
rn Returns a value as Roman Number in Lower Case
The Value can be an integer between 1 and 9999.
Sql > Select To_char ( 1000 , RN ) , To_char ( 1000, rn ) From Dual ;
Sql > Select Sal, To_char ( Sal, Rn ) , To_char ( S al, rn ) From Emp ;
S 99999 :
o
o

Returns negative value with a leading minus sign


Returns positive value with a leading plus sign

9999S :
o

Returns negative value with trailing minus sign.

41

Oragle 10 g Material

Returns positive value with a trailing plus sign.

S can appear as first or last Value.

Sql > Select To_char ( 1000, S9999 ), To_char ( -1000, S9999 ) From Dual ;
Sql > Select to_char ( 1000, 9999S ) , To_char ( -1000, 9999S ) From Dual ;
Sql > Select Sal, To_char ( Sal, S99999 ) , To_char ( Sal, 99999S ) From Emp ;
Sql > Select Sal, Comm, To_char ( Comm - Sal, S99999 ) , To_char ( Comm Sal ,
99999S) From Emp ;
X XXXX :
xxxx :
o
o
o

Returns the hexadecimal value of the specified number of digits.


If the number is not an integer, Orcle rounds it to an integer.
Accepts only positive values or 0.

Sql > Select To_char(1000, XXXX) From Dual ;


Sql > Select Sal, To_char ( Sal, XXXXX ) From Emp ;
, ( Comma ) 9,999 :
o
o

Returns a comma in the specified position.


Multiple commas can be specified.

Sql > Select To_char ( 10000, 99,999D99 ) From Dual ;


Sql > Select Sal, To_char ( Sal, 99,999D99 ) From Emp ;
. ( Period ) 99.99 :
o
o

Returns a decimal point, at the specified position.


Only one period can be specified in a number format model.

Sql > Select To_char ( 10000, L99, 999. 99 ) from Dual ;


Sql > Select To_char ( Sal, L99,999.99 ) From Emp ;
$ $9999 :
o

Returns value with a leading Dollar Sign.

Sql > Select To_char ( 10000, $99, 999. 99 ) From Dual ;


Sql > Select Sal, To_char ( Sal, $99,999.99 ) From Emp ;
0 ( Zero ) 0999 :
o

Returns leading Zeros.

42

Oragle 10 g Material

9990 :
Returns Trailing Zeros.
Sql > Select To_char ( 1000, 0999999 ) , To_char ( 1000, 09999990 ) From Dual ;
Sql > Select Sal, To_char( Sal, $099,999.99 ) From Emp ;
9 9999 :
o

Return value with a specified number of digits with a leading space when positive or
leading minus when negative.

Sql > Select To_char ( 1000 600 , 99999 ) , To_char( 600 1000 , 99999 )
From Dual ;
Sql > Select To_char ( 20.25 20, 99999 ) From Dual ;
C C9999 :
o

Returns specified position of the IS O Currency Symbol.

Sql > Select To_char ( 1000, C9999.99 ) From Dual ;


Sql > Select Sal, To_char ( Sal, C9999. 99 ) From Emp ;

Date Format Models :


The Date format models can be used in the To_char function to translat e a DA TE value from
original format to user Format .
The total length of a dat e format model cannot exceed 22 characters.
Date Format Elements :
A date format model is composed of one or more date format elements.
o

For input format models, format items cannot appear twice, and format items that
represent similar information cannot be combined.
Capit alization in a spelled out word, abbreviation, or Roman numeral follows capitalizati on in the
corresponding format element.
Punctuation such as hyphens, slashes, commas, periods and colons.
AD or A.D. / BC or B. C. :
o

Indicates AD / BC with or Without periods.

Sql > Select To_char ( Sysdate, AD) From Dual ;


Sql > Select To_char ( Sysdate, B.C.) , To_char ( Sysdate, A.D. ) From Dual ;

43

Oragle 10 g Material

Sql > Select Sal, Hiredate, To_c har ( Hiredate, A.D. ) From Emp ;
AM or A.M. / PM or P.M. :
o

It indicates Meridian Indicator with or without periods.

Sql > Select To_char ( Sysdate, A.M. ) , To_char ( Sysdate, PM) From Dual ;
Sql > Select Sal, Hiredate, To_c har ( Hiredate, AM ) From Emp ;
CC / SCC :
o

Indicates the century , S prefixes BC date with

Sql > Select To_char ( Sysdate, SCC-AD ) From Dual ;


Sql > Select Sal, Hiredate, To_c har ( Hiredate , SCC-A D) From Emp ;
D Day of the Week ( 1 7 )
Sql > Select To_char ( Sysdate, D ) From Dual ;
Sql > Select Hiredate, To_char ( Hiredate, D ) From Emp ;
Day Indicates spelled name of the Week Day.
o

Pads to a length of 9 Characters.

Sql > Select To_char ( Sysdate, DAY ) From Dual ;


Sql > Select Sal, Hiredate, To_c har ( Hiredate, DAY) From Emp Where
To_char ( Hiredate, DAY) = WEDNES DAY ;
DD It Indicates The Day of the Month ( 1 31 )
Sql > Select To_char(Sysdate,DD-DAY) from Dual ;
Sql > Select Hiredate, To_char ( Hiredate,DD -DAY ) From Emp ;
Sql > Select Hiredate, To_char ( Hiredate, DD-DAY ) From Emp Where
To_char ( HireDate. DD-DAY) = 03-WEDNESDAY ;
*DAY Specifies in Upper Casing.
*DAY Specifies in Initcap Casing.
*DAY Specifies in Lower Casing.
DDD It indicates the Day of the Year ( 1 366 )
Sql > Select Sysdate , To_char(Sysdate, DDD ) From Dual ;
Sql > Select Ename, Hiredate , To_char ( Hiredate, DDD ) From Emp
Where To_char ( Hiredate, DAY ) = WEDNESDAY ;
DY It indicates the abbreviated name of the day.

44

Oragle 10 g Material

Sql > Select Sysdate , To_char (Sysdate, D-DY-DAY ) From Dual ;


Sql > Select Ename, Hiredate, To_char ( Hiredate, D-DY-DAY ) from Emp
Where Dept no in( 10 , 20 ) ;
IW Specifies the week of the year ( 1 - 52 or 1 53 )based on the ISO Standard.
Sql > Select Sysdate, Hiredate, To_char ( Sysdate, IW ) From Dual ;
Sql > Select Ename, Hiredate, To_char ( Hiredate, I W ) From Dual ;
IYYY Specifies 4 Digit year based on the IS O Standard .
IYY
IY
Sql > Select Sysdate, To_char ( Sysdate, IYYY ) From Dual ;
Sql > Select Ename, Hiredate, To_char ( Hiredate, IYYY ) From Emp Where
To_char ( Hiredate, DAY ) = WEDNESDAY ) ;
YYYY / SYYYY Returns Four Digit year, S Prefixes BC dates with .
YYY / YY / Y
Y , YYY Returns year with comma in this position.
Sql > Select Sysdate, To_char ( Sysdate, YYYY ) Four, To_c har ( Sys date, YYY )
Three , To_char ( Sysdate, Y,YYY ) Comma From Dual ;
Sql > Select Ename, Hiredate, To_char ( Hiredate, YYYY ) From Emp
Where Dept no = 20 ;
YEAR / SYEAR Returns the spelled out year.
Sql > Select Sysdate, To_char ( Sysdate, YEAR ) From Dual ;
Sql > Select Ename, Hiredate, To_char ( Hiredate, YEAR ) From Emp ;
W Specified the week of the Month ( 1 5 ). Week starts on the first day of the
Month and ends on the seventh.
Sql > Select Sysdate, To_char ( Sysdate, W ) From Dual ;
Sql > Select Ename, Hiredate, To_char ( Hiredate, W) From Emp ;
WW Specifies the week of the Year ( 1 53 ) . Week 1 Starts on the first day of the year and
continues to the sevent h day of the year.
Sql > Select Sysdate, To_char ( Sysdate, WW ) From Dual ;
Sql > Select Ename, Hiredate, to_char ( Hiredat e, WW ) From Emp ;
Q Returns the Quarter of the Year.
Sql > Select Sysdate, To_char ( Sysdate, Q ) From Dual ;

45

Oragle 10 g Material

Sql > Select Ename, Hiredate, To_char ( Hiredate, Q ) From Emp Where
To_char ( Hiredate, Q ) = 4 ;
J Returns the JULIA N DAY.
i. It is the Number of days since January 1, 4712 BC.
ii. Numbers specified with J must be int egers.
Sql > Select Sysdate, To_char ( Sysdate, J ) From Dual ;
Sql > Select Ename, To_char ( Hiredate, J-DDD-DD-DD ) From Emp ;
MM returns the digit numeric abbreviation of the Month.
Sql > Select Sysdate, To_char ( Sysdate, MM-YYYY ) From Dual ;
Sql > Select Ename, Hiredate, To_char ( Hi redate, MM-YYYY ) From Emp Where
To_char ( Hiredate , MM ) = 12 ;
MON Returns the Abbreviated Name of the Month.
Sql > Select Sysdate, To_char ( Sysdate, MM-MON ) From Dual ;
MONTH Spells the Name of the Month, padded to a length of 9 c haracters .
Sql > Select Sysdate, To_char ( Sysdate, MON -MONTH ) From Dual ;
Sql > Select Enbame, Hiredate, To_char ( Hiredate, MONTH, YYYY ) From Emp ;
HH / HH12 Returns the Hour of the day in twelve hour clock mode.
Sql > Select Sysdate, To_char (Sysdate, HH ), To_char (Sysdat e, HH12, AM )
From Dual ;
Sql > Select Ename, Hiredate , To_c har ( Hiredate, HH12 : AM ) From Emp ;
HH24 Returns the Hour of the day in twenty four hour clock mode . ( 0 23 )
Sql > Select Sysdate, To_char ( Sysdate, HH24 ) From Dual ;
MI Returns the Minutes from the given date ( 0 53 ) .
Sql > Select Sysdate, To_char ( Sysdaste, MI ), To_char ( Sysdate, HH:MI ) From Dual;
Sql > Select Ename, Sal, To_char ( Hiredate, HH:MI ) From Emp Where Job=CLE RK ;
RM

Returns the Roman Numeral Month ( I XII ) .

Sql > Select Sysdate, To_char ( Sysdate, RM ) , To_char ( Sysdate,


DD-RM-YY ) From Dual ;
Sql > Select Ename, Sal,. To_char ( Hiredat e, DD -RM-YY ) From Emp ;
SS Returns Seconds from the given date ( 0 59 )
Sql > Select Sysdate, To_char ( Sysdate, SS ), To_char ( Sysdate, HH:MI:SS )

46

Oragle 10 g Material

From Dual ;
Sql > Select Sysdate, To_char ( Sysdate, DD-MONTH-YYYY, HH:MI:SS A.M. )
From Dual ;
Sql > Select Ename, Sal, Hiredate, To_c har ( Hiredate, HH24:MI:SS ) From Emp
Where Dept no In( 10, 30 ) ;
SSSS Display Seconds past Midnight ( 0 86399 ) .
Sql > Select Sysdate, To_char ( Sysdate, SSSS ) From Dual ;
Sql > Select Ename, Hiredate, To_char ( Hiredate, DD-MM-YY, HH:MI:SS, SSSS )
From Emp ;
The Punctuation marks that can be used in Date formats are
- ;

/ ;

! ;

. ;

; ;

: ;

text

RR Date Format Element :


The RR date Format element is similar to the YY date format element.
The RR format element provides additional flexibility for storing date values in other
Cent uries.
The RR date format element allows to store the date to the previous as well as the next
Cent uries .
If the Last 2 Digits of The Current Year are :
0 - 49
0 - 49

50 - 99

50 - 99

Returns date is in the


Current Century.

The return date is in the


Preceding Century .

The return date is in


the next Century

The return date is in the


Current Cent ury .

Date Format Element Suffixes :


o

TH Specifies the Ordinal Number


TH

Ex : DDTH 20

Sql > Select Sysdate, To_char ( Sysdate, DDTH, MONTH, YYYY ) From Dual ;
Sql > Select Ename, Sal, Hiredate, To_c har ( Hiredate, DDTH, MONTH, YYYY )
From Emp ;
o

SP Spells Numbers.
Ex : DDSP TWENTY

Sql > Select Sysdate, To_char ( Sysdate, DDSP , MONTH, YYYY ) From Dual ;
Sql > Select Ename, Sal, To_char ( Hiredat e, DDSP, MONTH, YYYY ) From Emp ;

47

Oragle 10 g Material

Spelled, Ordinal Number


Ex : DDSP TH TWENTIE TH

Sql > Select Sysdate, To_char ( Sysdate, DDSP TH, MONTH, YYYY ) From Dual ;
Sql > Select Ename, Sal, To_char ( Hiredat e, DDSP TH, MONTH, YYYY ) From Emp ;
Sql > Select Sysdate, To_char ( Sysdate, DDSP TH MONTH YYYYSP ) From Dual ;
Date Format Elements Re strictions :
o
o

The suffixes when added to date ret urn value always in English.
Date suffixes are valid only on output, henc e cannot be used to insert a date int o the
database.

Format Model Modifiers :


o

FM Fill Mode , It suppresses blank padding in the return value of the


To_char Function.

FX Format Exact , It specifies exact matching for the character argument


and date format model.

Sql > Select Sysdate, To_char ( Sysdate, DDSP TH MONTH YYYYSP ) ,


To_char ( Sysdate, FMDDSP TH MONTH YYYYSP ) From Dual ;
TO_NUMBER Function :
Syntax : To_Number ( Char, fmt, nlsparam )
o

It Converts a char, value of CHA R or VA RCHAR2 dat a type containing a Number in the
format specified by the optional format model fmt, to a value of NUMBER data type .

Sql > Select To_number ( $10,000.00, L99,999.99 ) From Dual ;


Sql > Select To_number ( $1,000.00, L9,999. 99 ) + 500 From Dual ;
TO_DATE Function :
Syntax : To_Date ( Char, fmt, nlsparam )
o
o

Converts char of CHAR or VARCHA R2 datatype to a Value of DA TE data type .


The fmt is a date format specifying the format of char.

Sql > Select Ename, Hiredate, ADD_MONTHS ( To_char ( 17 -DE C-1980,


DD-MON-YY ) , 3 ) From Emp Where Hiredat e = 17-DEC-1980 ;
Specificational Examples :

48

Oragle 10 g Material

Sql > Select To_char ( ADD_MONTHS ( Hiredate, 1 ), DD-MON-YYYY )


NE XT MONTH From Emp Where Ename = SMITH ;
Sql > Select Concat ( Concat ( Ename, is a), Job ) Designation From Emp
Where Empno = 7900 ;
Sql > Select Trunc ( To_Date ( 27-OCT-92 , DD-MON-YY ), YEAR ) NEW YEAR
From Dual ;
Sql > Select To_char ( ADD_MONTHS ( LAS T_DAY ( Hiredate ) , 5 ), DD -MON-YYYY )
FIVE MONTHS From Emp Where Ename = MARTIN ;
Sql > Select Months_Between ( To_Date ( 02-02-1995 , MM-DD-YYYY ),
To_Date ( 01-01-1995, MM-DD-YYYY ) ) MONTHS From Dual ;
Sql > Select Next_Day ( 15-MAR-98, TUESDAY ) Next Day From Dual ;
Sql > Select Ename, NVL ( To_Char ( Comm) , Not Applicable ) Commission
From Emp Where Dept no = 30 ;
Sql > Select Round ( To_Date ( 27-OCT-92 , YEAR ) New Year From Dual ;
Sql > Select To_Char ( Hiredate , MONTH DD YYYY ) From Emp Where
Ename = BLAKE ;
Sql > Select Ename, To_char ( Hiredate, fm Month DD, YY YY ) , Hiredate From
Emp Where Deptno = 20 ;
Sql > Select To_char ( To_Date ( 27-OCT-98, DD-MON-RR ), YYYY ) Year
From Dual ;
Sql > Select To_char ( To_Date ( 27-OCT-17, DD-MON-RR ), YYYY ) Year
From Dual ;
o

Assumption : Queries Issued between 1950 1999.

Sql > Select To_char ( To_Date ( 27-OCT-98, DD-MON-RR ), YYYY ) Year


From Dual ;
Sql > Select To_char ( To_Date ( 27-OCT-17, DD-MON-RR ) , YYYY ) Year
From Dual ;
o

Assumption : Queries Issued between 2000 2049

Sql > Select To_char ( Sysdate, fm DDTH ) || of || To_char ( Sysdate, Month )


, || To_char ( Sysdate, YYYY ) Idea From Dual ;
Sql > Select To_char ( Sysdate, fmDay ) || s Special ) MENU From Dual ;
Sql > Select Ename, Job, NV L ( To_char ( Mgr ), Supreme A uthority ) Managers
From Emp Order By Sal Desc ;
Aggregate or Group Functions :
o
o

These functions return a single row based on groups of rows.


These functions can appear in SELECT lists and HAV ING clauses.

49

Oragle 10 g Material

o
o

These functions operate on sets of rows to give one result per group.
The sets may be the whole table or the table split into groups.

Guidelines to use Group Functions :


o
o

DIS TINCT makes the function consider only non duplicat e values.
ALL makes the function to consider every value including duplicates.
Syntax : Group_Function_Name ( Distinct / ALL / n )

o
o
o
o

The data types for arguments may CHA R, VARCHAR, NUMBE R OR DA TE.
All group functions except COUNT( * ) ignore NULL values. To substitute a value for
NULL values, use the NVL function.
When a group function is declared in a SELECT list , no single row columns should be
declared.
When a group function is declared in a SELECT list, other columns can be declared, but
they should be grouped columns, and all the non functional columns should be declared
into a GROUP BY clause.

Average Function :
Syntax : AVG ( DIS TINCT / ALL / n )
o
o

It returns the A verage Value of n.


It ignores NULL values.

Sql > Select AVG ( Sal ) , AVG ( DIS TINCT Sal ) From Emp ;
Sql > Select AVG ( Comm ) , AVG ( DIS TINCT AVG ) From Emp ;
SUM Function :
Syntax : SUM ( DIS TINCT / ALL / n )
o It returns the Sum of the values of n.
o It ignores NULL values.
o
Sql > Select Sum ( Sal ), Sum ( DIS TINCT Sal ) From Emp ;
Sql > Select Sum ( Comm ) , Sum ( DIS TINCT Comm ) From Emp ;
MAXimum Function :
Syntax : MAX ( DIS TINCT / ALL / n )
o
o

It ignores the Maximum value of n.


It ignores NULL values.

Sql > Select Max ( Sal ), Max ( DISTINCT Sal ) From Emp ;
Sql > Select Max ( Comm ) , Max ( DIS TINCT Comm ) From Emp ;

50

Oragle 10 g Material

MINimum Function :
Syntax : MIN ( DIS TINCT / ALL / n )
o
o

It returns the Minimum value of the n.


It ignores NULL values.

Sql > Select Min ( Sal ) , Min ( DISTINCT Sal ) From Emp ;
Sql > Select Min ( Comm ), Min ( DIS TINCT Comm ) From Emp ;
Standard Deviation Function :
Syntax : STDDEV ( DIS TINCT / ALL / n )
o
o

It returns the Standard Deviation of the n.


It ignores NULL Values.

Sql > Select Stddev ( Sal ) , Stddev ( DIS TINCT Sal ) From Emp ;
Sql > Select Stddev ( Comm ), Stddev ( DIS TINCT Comm ) From Emp ;
Variance Function :
Syntax : VARIANCE ( DIS TINCT / ALL / n )
o
o

It returns the Variance of N.


It ignores the NULL values.

Sql > Select Variance ( Sal ) , Variance ( Distinct Sal ) From Emp ;
Sql > Select Variance ( Comm ), Variance ( DIS TINCT Comm ) From Emp ;
COUNT Function :
Syntax : COUNT ( * / DIS TINCT / ALL / n )
o
o
o
o

It returns the number of rows in the query.


N evaluates to something other than NULL.
It * is used returns all rows, including duplicat ed and NULLs.
It can be used to specify the count of all rows or only distinct values of n.

Sql > Select Count ( * ) From Emp ;


Sql > Select Count ( Job ) , Count ( DIS TINCT Job ) From Emp ;
Sql > Select Count ( Sal ) , Count ( Comm ) From Emp ;
Sql > Select Count ( Empno ) , Count ( DIS TINCT Mgr ) From Emp ;

51

Oragle 10 g Material

Creating Groups of Data :


o

The Group By Clause is used to decide the rows in a table into groups.

Syntax :

Select Column, Grp_Fun ( Column )


From Table
Where Condition
GROUP BY Grp_By_Expr
Order By Column ;

Guidelines to Use Group By Clause :


If the Group function is included in a SELECT clause, we should not use individual results
columns.
The Extra not group functional columns should be declared in the GROUP BY Clause.
USING WHE RE Clause, rows can be pre excluded before dividing them into groups.
Column Aliases cannot be used in Group By Clause.
By default, rows are sorted by ascending order of the columns inc luded in the Group By
List.
The column applied upon GROUP BY Clause need not be part of SELECT list.
Sql > Select Deptno, A vg( Sal ) From Emp Group By Deptno ;
Sql > Select Deptno, A vg ( Sal ) From Emp Group By Deptno Order by A vg ( Sal ) ;
Sql > Select Deptno, Min ( Sal ) , Max ( Sal ) From Emp Group By Deptno ;
Sql > Select Deptno, Job, Sum ( Sal ) From Emp Group By Deptno, Job ;
The Above specification falls under the principle of Groups within Groups.
Sql > Select Deptno, Min ( Sal ) , Max ( Sal ) From Emp Where Job = CLE RK
Group By Deptno ;
Sql > Select Deptno, Sum ( Sal ), A vg ( Sal ) From Emp Where Job = CLE RK
Group By Deptno ;
Excluding Groups of Results :
o

Having Clause :

It is used to specify which groups are to be displayed.

Syntax :

SELECT Column, Group_Function


From Table
[ WHERE Condition ]
[ GROUP BY Group_By_Expr ]
[ HAVI NG Group_Condition ]
[ ORDER BY Column_Name / Alias ] ;

Steps Perform s By Having Clause :

52

Oragle 10 g Material

o
o
o

Rows are Grouped


The Group Function is applied to the group.
The Groups that match the criteria in the HAV ING Clause are displayed.

The HAV ING Clause can precede Group By Clause, But it is more logical to declare it
before Group By.
Group By Claus e can be us ed, without a Group Function in the SELECT list.
If rows are restricted based on the result of a group function, we must have a Group By
Claus e as well as the Having Claus e.

Sql > Select Deptno, A vg ( Sal )_From Emp Group By Deptno Having
Max ( Sal ) > 2900 ;
Sql > Select Job, Sum ( Sal ) Payroll From Emp Where Job NOT LIKE SALES%
Group By Job Having Sum ( Sal ) > 5000 Order By Sum ( sal ) ;
Sql > Select Deptno, Min ( Sal ), Max ( Sal ) From Emp Where Job = CLE RK
Group By Deptno Having Min ( Sal ) < 1000 ;
Sql > Select Deptno, Sum ( Sal ) From Emp Group By Deptno Having
Count ( Deptno ) > 3 ;
Sql > Select Deptno, A vg ( Sal ) , Sum ( Sal ), Max ( Sal ), Min ( Sal ) From Emp
Group By Dept no Having Count ( * ) > 3 ;
Sql > Select Deptno, A vg ( Sal ) Sum ( Sal ) From Emp Group By Deptno
Having A vg ( Sal ) > 2500 ;
Sql > Select Deptno, Job, Sum ( Sal ) , A vg ( Sal ) From Emp Group By Deptno, Job
Having A vg ( Sal ) > 2500 ;
Nesting of Group Functions :
o

Group functions can be nested to a depth of two.

Sql > Select Max ( Avg ( Sal ) ) From Emp Group By Dept no ;
Sql > Select Max ( Sum ( Sal ) ) , Min ( Sum ( Sal ) ) From Emp Group By Deptno ;
Sql > Select Max ( Sum ( Sal ) ) , Min ( Avg ( Sal ) ) From Emp Group By Job ;
Miscellaneous Functions :
o

GREATEST Function :
Syntax : GREATEST ( Expr1, Expr2, .)

Returns the greatest of the list of Expr.


All Exprs after the first are implicitly converted to the dat a type of the first Expr,
before the comparison.
Oracle compares the Exprs using Non padded comparison semantics.
Character comparison is based on the value of the character in the data base
character list.

Sql > Select Greatest ( HARRY , HARRIOT ) From Dual ;

53

Oragle 10 g Material

Sql > Select Greatest ( 1000, 2000, 200 ) From Dual ;


Sql > Select Greatest ( 10-JUL-05, 20-JUL-05 ) From Dual ;
o

LEAST Function :
Syntax :

LEAST ( Expr1, Expr2, ..)

It returns the Least of the List of Exprs.


All Exprs after the first are implicitly converted to the dat a type of the first expr
before the comparison .

Sql > Select Least ( HARRY , HARRIOT ) From Dual ;


Sql > Select Least ( 1000, 2000, 200 ) From Dual ;
Sql > Select Least ( 10-JUL-05, 20-JUL-05 ) From Dual ;
o

USER Function :
Syntax : USER

It returns the Current Oracle users within the VA RCHAR2 data type.
The function cannot be used in the condition of the CHECK Constraint .

Sql > Select User From Dual ;

UID Function :
Syntax : UID

It returns an integer that uniquely identifies the Current User.

Sql > Select Uid From Dual ;


Sql > Select User, Uid From Dual ;
o

USERENV Function :
Syntax :

USERENV ( Option )

Returns information of VARCHAR2 data type above the current session .

The Values in Option are


ISDBA Returns TRUE if DBA Role is Enabled.
LANGUAGE Returns the Language and territory used in Current Session .
TERMINAL Returns the OS identifier for the Current Sessions Terminal .
SESSIONI D Returns the Auditing Session identifier.
ENTRYID Returns the available auditing entry identifier.

54

Oragle 10 g Material

LANG Returns the ISD abbreviation for the language name.


INSTANCE Returns the instance identification number o f the
Current Instance.
CLIENT_INFO Returns upto 64 Bytes of User Session Information .
Sql > Select UserEnv ( LANGUA GE ) From Dual ;
o

VISIZE Function :
Syntax :

VSIZE ( Expr )

It returns the Number of bytes in the internal representation of Expr.


If Expr is NULL, Function returns NULL .
Sql > Select Ename, Vsize ( Ename ) From Emp ;

SOUNDEX Function :
Syntax : SOUNDEX (CHAR )
It returns a character string containing the phonetic representation of char.
It allows comparison of words that are spelled differently, but sound alike in enlish.

Sql > Select Ename From Emp Where Soundes ( Ename ) = Soundex ( SMITH) ;
Sql > Select Ename, Job From Emp Where Soundes ( Job ) = Soundex ( CLERK ) ;
DATA INTEGRITY IN DATA BASES :

Data Integrity :
It is a state in which all the date values stored in the data base are collect.
Enforcing Data Integrity ensures the quality of the data in the data base.
CATEGORIES OF DATA INTIGRITY :
Enti ty Integrity :
It defines a row as a UNIQUE entity for a particular table
Entity integrity enforces the integrity of the identifies columns, or the P RIMA RY KEY of
a table.
Domain Integrity :
Domain Integrity validates the entries for a given column.
It can enforced through.
Restricting type ( Data Types )
By Format ( CHECK Constraint )
By Range of Possible Values ( FORE IGN KEY, CHECK, DEFA ULT, NOT NULL )

55

Oragle 10 g Material

Referential Integrity :
It preserves the defined relationship between tables when records are ent ered or deleted.
It ensures that key values are consistent across tables.
When referential integrity is enforced, it prevents from ..
* Adding records to a related table if there is no associated record in the
Primary Table.
* Changing values in a Primary Table that res ult in Orphaned records in a
related table.
* Deleting records from a Primary Table if there are matching related records.

User_Defined Integrity :
It allows to define specific business rules that do not fall into any one of the other int egrity
categories.
CONSTRAINTS :
Constraints are used to define an Integrity Constraint, as rule that restricts the values in a
data base.
As per Oracle these are Six Types of Constraints :
1)

A NOT NULL Constraint

2)

A UNIQUE Constraint

3)

A PRIMARY KEY Constraint

4)

A FOREIGN KEY Constraint

5)

A CHECK Constraint

6)

A REF Constraint

In Oracle Constraints can be declared in two different styles.


1)

Column Level : They are declared as part of the definition of an individual


column or attribute. The style is called as INLINE specification.

2)

Table Level : They are declared as part of the table definition. The style is
called as OUT_OF_LINE specification.

Note : NOT NULL Constraint should be declared as INLINE only.


The Constraint Clause can appear in ..
o

CREA TE Table

ALTE R Table

56

Oragle 10 g Material

CREA TE View

ALTE R View

Oracle does not support Constraints on Columns or attributes whose type is .


o

USER_DEFINED OB JECT

NES TED TABLES

VARRAY

REF

LOB

Exceptions :
o
o

NOT NULL Constraint are supported for a column or attributes whose type is
USER_DEFINED object VARRAY, REF, LOB .
NOT NULL, FOREIGN KEY, and REF Constraints are supported on a column of
type REF.

NOT NULL Constraints :


A NOT NULL Constraint prohibits a column from containing NULLs .
NOT NULL should be defined using only INLINE specification or only at COLUMN Level
The default if not specified is NULL .
To satisfy a NOT NULL constraint, every row in the table must contain a value for the
column.
Restrictions :
NULL or NOT NULL Cannot be specified in a view constraint.
NULL or NOT NULL cannot be specified for an attribute of an object.
Example :
Sql > Create Table Students
(
StudNo Number ( 6 ) Constraint Studno_NN NOT NULL,
StudName Varc har2 ( 25 ) Constraint StudName_NN NOT NULL,
CourseName Varchar2( 25 ) Constraint CourseName_NN NOT NULL,
JoinDate Dat e Constraint Jdate_NN NOT NULL
) ;

UNIQUE Constraints :
The UNIQUE Constraint designates a column as a UNIQUE Key.

57

Oragle 10 g Material

A composite UNIQUE key designates a combination of columns as the UNIQUE Key.


A composite UNIQUE key is always declared at the table level or out of line.
To satisfy a UNIQUE constraint, no two rows in the table can have the same value for the
UNIQUE key.
UNIQUE key made up of a single column can contain NULLs.
Oracle creates an Index implicitly on the UNIQUE key column.
Restrictions :
A Table or View can have only one UNIQUE Key.
UNIQUE key cannot be implemented on columns having
o

LOB * LONG * LONG RAW * VARRAY * NESTED TABLE

OBJECT * BFILE

* REF * TIMES TAMP WITH TIME ZONE .

A composite UNIQUE key cannot have more than 32 columns


Same column or combination of columns cannot be designated as both PRIMARY KEY
and UNIQUE KEY.
We cannot specify a UNIQUE key when creating a subtable or subview in an Inheritance
hierarchy.
The UNIQUE key can be specified only for the top level ( Root ) table or View.
Example :
SQL >
(

Create table Promotions1


Promo_ID
PromoName
PromoCategory
PromoCost
PromoB egDate
PromoE ndDate

Number ( 6 ) Constraint Promo_ID_UNQ UNIQUE ,


Varchar2( 20 ) ,
Varchar2 ( 15 ) ,
Number ( 10 , 2 ) ,
Date ,
Date

) ;
SQL > Create table Promotions2
(
Promo_ID
PromoName
PromoCategory
PromoCost
PromoB egDate
PromoE ndDate

Number ( 6 )
Varchar2( 20 ) ,
Varchar2 ( 15 ) ,
Number ( 10 , 2 ) ,
Date ,
Date ,

Constraint Promo_ID_UNQ UNIQUE ( PromoID)


) ;
SQL > Create table WareHouse
(
WareHouseID
WareHouseName
Area
Dock Type
WaterAccess

Number ( 6 ) ,
Varchar2( 30 ) ,
Number ( 4 ) ,
Varchar2( 100 ) ,
Varchar2( 10 ) ,

58

Oragle 10 g Material

RailAccess
Parking
Vclearance

Varchar2( 10 ) ,
Varchar2( 10 ) ,
Number ( 4 ) ,

Constraint WareHouse_UNQ UNIQUE ( WareHouseID,


WaareHouseName )
) ;
PRIMARY KEY Constraints :
A Primary Key constraint designates a column as the Primary Key of a table or View.
A COMPOS ITE PRIMARY KEY designates a combination of columns as the PRIMARY
KEY.
When the CONS TRA INT is declared at column level or inline only PRIMA RY KEY
Keyword is enough.
A Composite Primary Key is always defined at Table Level or Out of Line only.
A Primary Key Constraint combines a NOT NULL and UNIQUE Constraint in one
declaration.
Restrictions :
A Table or View can have only one PRIMARY KEY .
PRIMA RY KEY Can not be implemented on Columns having
o

LOB * LONG * LONG RAW * VARRAY * NESTED TABLE

OBJECT * BFILE

* REF * TIMES TAMP WITH TIME ZONE .

The size of a P RIMA RY KEY cannot exceed approx. one Database Block .
A composite PRIMA RY KEY cannot have more than 32 columns.
The same column or combination of columns cannot be designated both as PRIMA RY
KEY and UNIQUE KEY.
PRIMA RY KEY cannot be specified when creating a SubTable or SubView in an
Inheritance Hierarchy.
The PRIMA RY KEY can be specified only for the top level( ROOT )Table or View
Example :
Sql > Create Table Locations
(
LocationID
Number ( 4 ) Constraint Loc_ID_PK PRIMARY KEY,
StAddress
Varchar2( 40 ) NOT NULL ,
PostalCode
Varchar2( 6 ) Constraint PC_NN NOT NULL ,
City
Varchar2 ( 30 ) Constraint City_NN NOT NULL
) ;

Sql > Create Table Locations1


(
LocationID
Number ( 4 ) ,
StAddress
Varchar2( 40 ) NOT NULL ,
PostalCode
Varchar2( 6 ) Constraint PC_NN NOT NULL ,
City
Varchar2 ( 30 ) Constraint City_NN NOT NULL ,
Constraint Loc_ID_PK PRIMA RY KEY ( LocationID )

59

Oragle 10 g Material

) ;
Sql > Create Table Sales Info
(
ProdID
CustID
SaleDate
SaleDesc

Number ( 6 ) ,
Number ( 6 ) ,
Date NOT NULL ,
Long NOT NULL ,

Constraint Prod_Cust_IDPK ( ProdID , Cust ID )


) ;
FOREIGN KEY Constraint :
It is also called as REFERE NTIAL INTEGRITY CONS TRAINT.
It designat es a column as Foreign Key and establishes a relation bet ween the Foreign
Key and a specified Primary or Unique Key.
A Composite Foreign Key designat es a combination of columns as the Foreign Key.
The Table or View cont aining the Foreign Key is called the Child Object.
The Table or View cont aining the REFE RENCE D KEY is called the Parent Object.
The Foreign Key and the Referenced Key can be in the same Table or View.
The corresponding column or columns of the Foreign Key and the Referenced Key must
match in order and data type.
A Foreign Key Constraint can be defined on a single key column either inline or out of
line.
A Composite Foreign Key on attributes should be declared at table le vel or out of line
style.
A Composite Foreign Key Constraint, must refer to a Composite Unique Key or a
Composite Primary Key in the Parent Table or View.
The same column or combination of columns can be designated as both a Foreign K ey
and a Primary or Unique Key.
We can designate the same column or combination of columns as both a foreign key and
a Primary or Unique Key.
Restrictions :
The Foreign Key Columns cannot be applied on .
o

LOB * LONG * LONG RAW * VARRAY * NESTED TABLE

OBJECT * BFILE

* REF * TIMES TAMP WITH TIME ZONE .

The Referenced Unique / Primary Key Constraint on the Parent Table on View must
already be deleted.
A Composite Foreign Key cannot have more than 32 columns.
The Child and Parent Tables must be on the same database.
To enable Referential Int egrity across nodes of a distribut ed databas e Database
Triggers are used.
REFERENCES Clause :
The References Clause Should be used when the Foreign Key Constraint is INLINE.
When the Constraint is OUT OF LINE, we must specify the Foreign Key , Key words.

60

Oragle 10 g Material

ON DELETE Clause :
The ON DELE TE Claus e determines how oracle automatically maintains
REFERE NTIAL INTEGRITY if the REFERE NCE D PRIMA RY or UNIQUE KEY value
is removed.
CASCA DE option can be specified if we want ORA CLE to remove Dependent
FORE IGN KEY values.
Specify SET NULL if we want Oracle to convert dependent FORE IGH KEY values to
NULL.
ON DE LE TE Clause cannot be specified for a view constraint.
Steps to be Followed for Creating Foreign Key Constraint are as Follows :
Step 1 : Create Primary Masters / Pure Masters
These are Tables which contains only Primary Key Columns.
Sql > Create Table Dept
(
Deptno
Number( 2 ) Constraint Deptno_Pk PRIMA RY KEY,
Dname
Varchar2( 20 ) Constraint Dname_NN NOT NULL,
Location
Varchar2( 20 ) Constraint Loc_NN NOT NULL
) ;
Step 2 : Create Detailed / Child Table
These are Tables which can contain Primary Key of their own as well as Foreign
Keys referring to other Primary Masters or to them selves.
These tables are als o called as dependent tables or Referential tables.
Sql > Create Table Employee
(
EmployeeID
Number ( 6 )
Constraint Emp_ID_PK PRIMA RY KEY ,
Ename
Varchar2 ( 30 )
Constraint Ename_NN NOT NULL ,
Designation
Varchar2 ( 30 )
Constraint Desig_NN NOT NULL ,
ManagerID
Number ( 6 )
Constraint Mgr_ID_FK_S elf
REFERENCES Employee ( EmployeeID )
ON DELETE SE T NULL ,
HireDate
Date
Constraint HireDate_NN NOT NULL ,
Commission
Number ( 7, 2 ),
Dept ID
Number ( 2 )
Constraint Dept ID_FK
REFERENCES Dept( Deptno )
ON DELE TE CASCA DE
) ;

61

Oragle 10 g Material

Working With Composite PRIMARY KEY :


Step 1 : Creat e Pure Maters

Sql > Create Table SampleMaster1


(
SampleID1 Numer ( 4 ) Constraint Samp_ID_PK P RIMA RY KEY ,
SampName Varchar2 ( 20 ) Constraint SampName_NN NOT NULL ,
SampDate Date Constraint SampDate_NN NOT NULL
) ;
Sql > Create Table SampMaster2
(
SampleID2 Numer ( 4 ) Constraint Samp_ID2_PK PRIMARY KEY ,
SampName2 Varchar2 ( 20 ) Constraint SampName2_NN NOT NULL ,
SampDate2 Date Constraint SampDate2_NN NOT NULL
) ;
Step 2 : Create The Pure Details

Sql > Create Table SampRef


(
SampIDRef1

Number ( 4 )
Constraint SampIDRef_FK
REFERENCES SampMaster1( SampID1 ) ,
SampIDRef2
Number ( 4 )
Constraint SampIDRef2_FK
REFERENCES SampMaster2( SampID2 ) ,
SampNameRef Varchar2 ( 20 ) ,
SampDateRef Date ,
Constraint SampRef_Comp_PK
PRIMA RY KEY ( SampIDRef1, SampIDRef2 )
) ;
CHECK Constraint :
It defines a condition that each row must satisfy.
To satisfy the constraint, each row in the table must make the condition either TRUE or
UNK NOWN.
ORA CLE does not verify that CHE CK conditions are not mutually exclusive.
Restrictions :
The Condition of a CHE CK Constraint can refer to any column in the table, but it cannot
refer to columns of other tables.
The constructs that cannot be included are ..

62

Oragle 10 g Material

o
o
o
o

Queries to refer to values in other rows


Calls to functions SYSDTE, UID, USE R, USERE NV.
The pseudo Columns CURRVAL, NES TVAL, LEVEL or ROWNUM.
Date constant that are not fully specified.

A single column can have multiple CHE CK constraint that reference the column in the
definition.
There is no limit to the number of CHE CK constraints that can be defined on a column.
The CHECK constrains can be defined at the column level or Table level.
Example :
Sql > Creat e Table Dept
(
Dept no Number ( 2 ) Constraint CHK _Deptno
CHE CK ( Deptno BETWEEN 10 A ND 99 ) ,
Dname Varc har2( 15 ) Constraint CHK _Dname_up
CHE CK ( Dname = UPPER ( Dname ) )
DISABLE ,
Loc
Varchar2 ( 15 ) Constraint CHK _Loc
CHECK ( Loc IN( DALLAS, BOS TON,
NEW YORK , CHICA GO ) )
) ;

Sql > Creat e Table Emp


(
Empno

Mgr

Number ( 4 )
Constraint PR_Empno PRIMARY KEY ,
Varchar2( 25 ) NOT NULL
Constraint CHK_Ename
CHE CK ( Ename = UPPER ( Ename ) ) ,
Varchar2( 30 )
Constraint Job_NN NOT NULL ,
Constraint CHK_Job
CHE CK ( Job = UPPER ( Job ) ) ,
Number ( 4 ) ,

HireDate

Date

Sal

Comm

Number ( 7, 2 )
Constraint Sal_NN NOT NULL ,
Constraint CHK_Sal
CHE CK ( Sal BETWEE N 2000 AND 100000 ) ) ,
Number ( 7, 2 ) ,

Dept no

Number ( 2 ) ,

Ename

Job

DEFAULT SYSDA TE,

Constraint Tot_S al_Chk CHECK ( Sal + Comm < = 100000 )


) ;

63

Oragle 10 g Material

DEFAULT Option :
The DEFA ULT Option is given to maintain a default value in a column.
The option prevents NULL Values from entering the Columns, if a row is inserted without a value
for a column.
The DEFA ULT value can be a literal, an expression or a SQL Function.
The DEFA ULT Expression must match the data type of the Column.
Adding Constraints to a Table :
A constraint can be added to a table at any time after the table was created by using ALTE R
TABLE Statement, using ADD Clause.
Syntax :
Sql > ALTER TABLE < Table_Name >
ADD [ Constraint < Constraint _Name > ]
Cons_Type ( Column_Name ) ;
The Constraint Name syntax is optional, but recommended.
Guidelines :
We can ADD, DROP , ENABLE, or DISABLE a Constraint , but modify the structure.
A NOT NULL can be added to existing column by using the MODIFY Clause of the ALTE R
TABLE Statement.
NOT NULL can be defined only when the table contains no rows.
Example :
Sql > ALTER Table Emp A DD Constraint Emp_Mgr_FK FOREIGN KEY ( Mgr )
REFERENCES Emp ( Empno ) ;

DROPPING Constraints :
To Drop a constraint identify the constraint name from the USER_CONS TRAINTS and
USER_CONS_COLUMNS Data dictionary views.
The ALTE R TABLE Statement is used wit h the DROP Clause.
The CAS CADE Option of the DROP Clause causes any dependent constraints also to be
dropped.
When a constraint is dropped, the constraint is no longer enforced and is no longer available in
the data dictionary.
Syntax : ALTER Table < Table_Name >
DROP PRIMARY KEY / UNIQUE ( Column ) /
CONS TRA INT Constraint_Name [ CASCA DE ] ;
Example :
Sql > ALTER Table Dept DROP P RIMA RY KEY CASCA DE ;
Sql > ALTER Table Emp DROP CONS TRAINT Emp_Mgr_FK ;

64

Oragle 10 g Material

DISABLING Constraints :
The constraints can be disabled without dropping it or rec reating it.
The ALTE R TABLE Statement is used wit h the DISABLE Clause.
Syntax :

ALTER Table < Table_Name >


DISABLE CONS TRA INT < Constraint_Name > [ CASCADE ] ;

Guidelines :
The DISABLE Clause can be used both in CREA TE TABLE and the ALTE R TABLE
statement.
The CAS CADE clause disables dependent integrity constraints.
Examples :
Sql > ALTER Table Emp DISABLE CONS TRA INT Emp_Empno_PK CASCA DE ;

ENABLING Constraints :
The Constraints can be enabled wit hout dropping it or re -creating it.
The ALTE R TABLE statement with the ENABLE Clause.
Syntax :

ALTER Table < Table_Name >


ENABLE CONS TRAINT < Constraint_Name > ;

Guidelines :
Enabling a Constraint applied to all the data in the table.
When an UNIQUE or PRIMARY KEY Constraint is ENABLED, the UNIQUE or P RIMARY
KEY Index is automatically created.
The ENABLE Claus e can be us ed both in CREA TE TAB LE as well as ALTER TAB LE
Statements.
Examples :
Sql > ALTER Table Emp ENABLE CONS TRA INT Emp_Empno_FK ;

VIEWING Constraints :
To View all Constraints on a table by Querying the USER_CONS TRAINTS table.
The Codes that are revealed are
o
o

C
D

CHECK
PRIMARY KEY

REFERENTIAL INTEGRITY

UNIQUE KEY

65

Oragle 10 g Material

Example :
Sql > SELECT CONS TRA INT_NAME, CONS TRA INT_TYPE, SEARCH_CONDITION
FROM USER_CONS TRAINTS WHERE TABLE _NAME = EMP ;

VIEWING The Columns Associated With Constraints :


The Names of the columns that are involved in constraints can be known by querying the
USER_CONS_COLUMNS Data Dictionary View.
Example :
Sql > SELECT CONS TRA INT_NAME, COLUMN_NAME FROM
USER_CONS_COLUMNS WHE RE TAB LE_NAME = EMP ;

JOINS :

A Join is query that combines rows from two or more tables, views, or Materialized views.
A Join is performed whenever multiple tables appear in the queries FROM Clause.
The Queries SELECT list can select any columns from any of these tables.
The common column names within the tables should qualify all references to these columns.

JOIN CONDTIONS :
Many Join Queries contain WHERE Claus e, which compares two columns, eac h from a different
table.
The applied condition is called a Join Condition.
To execute a Join
o

Oracle combines pairs of rows, each containing one row from each table, for which the
Join condition evaluated to TRUE.
The Columns in the Join Conditions need not be part of the SELECT list.
The WHERE Claus e of Join Query can also contain other conditions that refer to columns of only
one table.
To Execute a Join of three or more tables
o

Oracle first Joins two of the tables based on the Join Conditions comparing these
columns and then Joins the result to anot her.

JOIN 1
TABLE 1

TABLE 2

JOIN 2
RESULT

66

TABLE 3

Oragle 10 g Material

RESULT
The Oracle Optimizer determines the older in which Oracle Joins tables based on the
o
o
o

JOIN Condition
INDEX ES on Tables
STATISTICS for the Tables.

The LOB Columns cannot be specified in the WHERE Clause, When the WHERE Clause
contains any JOINS.
Syntax : Table1.Column1 = Table2.Column2 .
Guidelines :
When writing a SELE CT statement that Joins tables, precede the Column Name with the
Table Name for clarity and enhance database Access.
If the same column name appears in more than one table, the column name must be prefixed
with the table name.
To Join n tables together, we need a minimum of n -1 Join Conditions .
The above rule does not apply , if the table contains a concatenated P rimary Key.
EQUIJOINS / SIMPLE JOINS / INS ER JOINS :
An EQUIJOIN is a Join with a Join Condition containing an equality operator.
It combines rows that have equivalent values for the specified columns.
The total size of columns in the equi join condition in a single table may be limited to the size of a
data block minus some overhead.
The size of the data block is specified by the initialization parameter DB _BLOCK_S IZE .
Example :
Sql > Select Emp.Empno, Emp.Ename, Emp.Deptno , Dept.Deptno, Dept. Dname,
Dept.Loc From Emp, Dept Where Emp.Deptno = Dept. Deptno ;
Qualifying Ambiguous Column Names :
The names of the column names should be qualified in the WHERE Clause, with the table
name to avoid ambiguity.
If there are no common column names between the two tables, the qualification is not
necessary.
Example :
Sql > Select Empno, Ename, Emp. Dept no , Loc From Emp, Dept Where
Emp.Deptno = Dept.Deptno AND Job = UPPE R ( manager ) ;
USING TABLE ALIAS ES :

Tables Aliases can be used instead of table names.


A table Alias gives an alternate name for the existing queried table.
Table Aliases help in keeping the SQL Code smaller, hence using less Memory.
The Table alias is specified in the FROM Clause.
To specify a Table Alias, specify the Table Name in full followed by space and then the Table
Alias.

67

Oragle 10 g Material

Guidelines :
A table alias can be upto 30 character in length.
If a Table Alias is used for a particular Table Name in the From Clause, then that Table Alias
must be substituted fro the Table Name through out the SELECT statement.
A Table Alias should be meaningful .
A Table Alias is valid only for the Current SELECT statement .
Examples :
Sql > Select E.Empno, E,Ename, D.Deptno, D.Dname From Emp E, Dept D
Where E.Deptno = D.Deptno ;
Sql > Select E.Ename, E.Job, D. Deptno, D. Dname , D.Loc From Emp E, Dept D
Where E.Deptno = D.Deptno AND E.Job IN(A NALYS T, MANAGE R ) ;
Sql > Select E.Ename, E.Job, D. Dname , D.Loc From Emp E , Dept D
Where E.Deptno = D.Deptno AND D. Dname < > BOSTON ;
SELF JIONS :

It is a Join of a table to itself.


The same table appears twice in the FROM Claus e and is follo wed by table aliases.
The Table Aliases must qualify the Column names in the Join Condition.
To perform a Self Join, Oracle combines and returns rows of the table that satisfy the Join
Condition .
Example :
Sql > Select

E1.Ename Employee Name ,


E2. Ename Managers Name ,
From Emp E1, Emp E2
Where E1.Mgr = E2.Empno ;

Sql > Select

E1.Ename || s Managers is ||
E2.Ename Employees And Managers
From Emp E1, Emp E2
Where E1.Mgr = E2.Empno ;

Sql > Select

E1.Ename || Works Fir ||


E2.Ename Employees And Managers
From Emp E1 , Emp E2
Where ( E1.Mgr = E2.Deptno ) AND E1. Job = CLERK ;

CARTESIAN PRODUCTS :
The CA RTES IAN PRODUCT is a Join Query, that that no Join Condition.
During Cart esian Product Oracle Combines each row of one table with each row of the other.
It tends to generate a large number of rows and the result is rarely useful.
Example :
Sql > Select Ename, Job, Dname From Emp, Dept ;

68

Oragle 10 g Material

Sql > Select Ename, Job, Dname From Emp, Dept Where Job = MANAGER ;
NON EQUI JOIN :
It is a Join Condition that is executed when no column is one table corresponds directly to a
column in the ot her table.
The Data in the tables in directly not related but indirectly or logically related through proper
values.
Example :
Sql > Select E.Ename , E.Sal , S.Grade From Emp E, SalGrade S
Where E.Sal BE TWEEN S.Losal AND S.Hisal ;
Sql > Select E.Ename, E.Sal, S.Grade From Emp E, SalGrade S
Where ( E.Sal > = S.LoSal AND E.Sal < = S.HiSal ) AND S.Grade = 1 ;

OUTER JOI NS :
An Outer Join extends the result of a simple Join.
An OUTE R Join ret urns all rows that satisfy the Join Condition and also those rows from one
table for which no rows from the other satisfy the Join Condition.
To perform an OUT Join of tables A and B and returns all rows from A, apply the outer join
operator ( + ) to all columns of B.
For all rows in A that have no matching rows in B, Oracle ret urns NULL for any select list
expressions containing columns of B.
Syntax :
Sql > Select Table1. Column, Table2. Column From Table1, Table 2
Where Table1.Column ( + ) = Table2. Column ;

Sql > Select Table1. Column, Table2. Column From Table1, Table 2
Where Table1.Column = Table2.Column ( + ) ;
Rules And Re strictions :
The ( + ) operator can appear only in the WHE RE Clause.
The ( + ) operator can appear in the context of the left correlation in the From Clause, and
can be applied only to a column of a Table or View.
If A and B are joined by multiple join conditions, we must use the ( + ) operator in all of these
conditions.
The ( + ) operator can be applied only to a column, not to an arbitrary expressions.
A condition containing the ( + ) operat or cannot be combined with another condition using the
OR Logical Operator.
A condition cannot use the IN Comparison operator to compare a column marked with the ( +
) operator with an expression.
A condition cannot compare any column marked with the ( + ) operator with a
sub query.

69

Oragle 10 g Material

Examples :
Sql > Select E.Ename , D.Deptno, D. Dname From Emp E, Dept D
Where E.Deptno ( + ) = D.Dept no Order By E.Deptno ;
Sql > Select E.Ename, D.Deptno , D.Dname From Emp E, Dept D
Where E.Deptno ( + ) = D.Dept no AND E.Deptno ( + ) = 10
Order By E.Deptno ;
Sql > Select E.Ename, D.Deptno, D. Dname From Emp E, Dept D
Where E.Deptno = D.Deptno ( + ) And E.Deptno ( + ) = 10
Order By E.Deptno ;
JOINING Data From More Than One Table :
JOINS can be established on more than two tables.
The Join is first executed upon the two most relevant tables and then the result is applied upon
the third table.
Example :
Sql > Selecgt C.Name, O.OldID, I. ItemID, I. Itemtot, O. Total
From Customer C, Ord O, Item I
Where C.CustID = O.CustID A ND
O.OldID = I.OldID A ND
C.Name = TKB SPORT SHOP ;
SUB QUERI ES / NESTED S ELECT / SUB SELECT / INNER SELCT :

A Sub Query answers multiple-part questions.


A Sub Query in the From Clause of a SELECT statement is called as INILI NE VIEW.
A Sub Query in the WHERE Clause of a SELE CT statement is called as NES TE D SUBQUERY.
A Sub Query can contain another Sub Query.
Oracle imposes no limit on the number of Sub Query levels in the From Clause of the top -level
query.
Within the WHERE Clause upt o 255 Sub Queries can be Nested.
A Sub Query can be part of a Column, in the SELE CT list.
To make the statements easier for readability, qualify the columns in a Sub Query with the Table
Name or Table Alias.
Purpose of A Sub Query :
To define the set of rows to be inserted into the target table of an INSERT or CREA TE
TABLE statement.
To define the set of rows to be included in a view a materialized view in a CREA TE VIEW or
CREA TE MA TE RIA LIZE D VIEW statement.
To define one or more values to be assigned to existing rows in an UPDA TE statement.
The provide values for conditions in a WHERE clause, HAV ING Clause, S TART WITH
Claus e of SELE CT , UPDA TE, and DE LE TE statements.
To define a table to operated on by a containing query.
Sub Query Principle :
Solve a problem by combining the two queries, placing one query inside the other query.

70

Oragle 10 g Material

The inner query or the sub query returns a value that is used by the outer query on the main
query.
USAGE ..
They are practically very useful when we need to select rows from a table with a condition
that depends on the dat a in the table itself.
Syntax :
Select Select_List From Table_Name
Where Table_Name
( Select Select_List From Table_Name ) ;
The Expr . Operator can be of
o

Single row Operators ( > , = , > = , < , < = )

Multiple row Operators ( IN , ANY , ALL )

TYPES OF S UB QUERIES :
Single Row Sub Query :
o

These Queries return only one Row from the inner SELECT Statement.

Multiple Row Sub Query :


o

These Queries return more than one Row from the inner SELE CT Statement.

Multiple Column Sub Query :


o

These Queries return more than one Column from the inner SELE CT Statement.

Guidelines To Follow ..

A Sub Query must be enclosed in parenthesis.


A Sub Query must appear on the ri ght side of the comparison operat or.
Sub Queries should not contain an ORDE R BY Clause.
Only one ORDER BY Clause can be implemented for the total SELE CT Statement.
Two clauses of comparison operations can be used in sub queries.
* Single Row

* Multiple Row

Single Row Sub Queries :


They return only one row from the INNER SELE CT Statement.
It uses only single row operator.
Examples :
Sql > Select Ename, Sal, Job From Emp
Where Sal > ( Select Sal From Emp Where Empno = 7566 ) ;
Sql > Select Ename, Sal, Job From Emp
Where Job = ( Select Job From Emp Where Ename =

71

Oragle 10 g Material

Upper ( smith) ) Order By Sal ;


Sql > Select Empno, Ename, Hiredate, Sal From Emp
Where Hiredate > ( Select Hiredate From Emp
Where Ename = UPPER ( turnes ) ) Order By Sal ;

Sql > Select Empno, Ename, Sal, Job From Emp


Where Deptno = ( Select Deptno From Dept Where Dname = SALES ) ;
Sql > Select Empno, Ename, Sal, Comm, Sal + NVL( Comm, 0 ) From Emp
Where Dept no = ( Select Deptno From Dept Where Loc = DALLAS ) ;

APPLYI NG GROUP FUNCTIONS IN S UB QUERI ES :


The data from the main query can be displayed by using a Group Function is a Sub Query.
As a Group Function returns a single row, the query passes through t he success state.
The inner sub query should not have a GROUP BY Clause in this scenario.
Examples :
Sql > Select Ename, Job , Sal From Emp
Where Sal = ( Select Max( Sal ) From Emp ) ;
Sql > Select Ename, Job, Sal From Emp
Where Sal = ( Select Min ( Sal ) From Emp ) ;
Sql > Select Ename, Job, Sal From Emp
Where Sal > ( Select Avg ( Sal ) From Emp ) ;
Sql > Select Ename, Job, Sal From Emp
Where Sal < ( Select STDDEV( Sal ) From Emp ) ;

Applying HAVING Clause With Sub Queries :


A Sub Query can be also applied in HAV ING Clause.
The Oracle Server executes the sub query, and the results are returned into the HAVING Clause
of the Main Query.
Example :
Sql > Select Deptno, Min ( Sal ) From Emp
Group By Deptno
Having Min( Sal ) > ( Select Min ( Sal ) From Emp
Where Deptno = 20 ) ;
Sql > Select Job, A vg ( S al ) From Emp
Group By Job
Having A vg( Sal ) = ( Select Min ( A vg ( Sal ) )
From Emp Group By Job ) ;
Sql > Select Job, A vg ( S al ) From Emp
Group By Job
Having A vg ( Sal ) < ( Select Max ( Avg ( Sal ) )

72

Oragle 10 g Material

From Emp Group By Job ) ;


Sql > Select Job, A vg ( S al ) , To_Char ( A vg ( Sal ) , L99,999.99 ) From Emp
Group By Job
Having Avg ( Sal ) < ( Select Max ( Sal ) )
From Emp Group By Deptno ) ;
Sub Queries Returning More Than One Row :

The Sub Queries that return more than one row are called as MULTIP LE ROW SUB QUERIES.
In This case a multiple row operator should be used.
The multiple row operators expect one or more values.
The multiple row operator are IN , ANY, ALL,
o

IN

EQUAL TO ANY MEMBER INDI A THE LIST .

ANY

COMP ARES VALUE TO EACH VALUE RETURNED


BY SUB QUERY .

ALL

COMP ARES VALUE TO EV ERY VALUE RETURNED


BY THE SUB QUERY .

S
Y
N
O
N
Y
S

Examples :
Sql > Select Ename, Sal, Deptno From Emp
Where Sal In( Select Min ( Sal ) From Emp Group By Deptno ) ;
Sql > Select Ename, Sal, Deptno From Emp
Where Sal In ( Select Max ( Sal ) From Emp Group By Deptno ) ;
Sql > Select Ename, Sal , Deptno , Job From Emp
Where Sal In( Select Max ( Sal ) From Emp Group By Job ) ;

Examples Any Operator :


Sql > Select Empno, Ename, Job From Emp
Where Sal < Any( Select Sal From Emp Where Job = CLE RK ) ;
Note : < It means less than the Maximum Value .
Sql > Select Empno, Ename, Job, Sal From Emp
Where Sal < Any ( Select Sal From Emp
Where Dept no = 20 AND Job < > CLERK ;
Sql > Select Empno, Ename, Job From Emp
Where Sal > Any ( Select Sal From Emp Job = CLE RK ) ;
Note : > ANY It means more than the Minimum.
Sql > Select Empno, Ename, Job From Emp
Where Sal = Any ( Select Sal From Emp Where Job = CLE RK ) ;

73

Oragle 10 g Material

Note : = ANY It is Equivalent to IN Operator .


Examples ALL Operator :
Sql > Select Empno, Ename, Job, Sakl From Emp
Where Sal > ALL ( Select Avg ( Sal ) From Emp Group By Deptno ) ;
Note : > ALL It means more than the Maximum .
Sql > Select Empno, Ename Job, Sal From Emp
Where Sal < All ( Select Avg( Sal ) From Emp Group By Dept no ) ;
Note :

< ALL It means less than the Minimum .

Sub Queries Returning Multiple Columns :


In Sun Queries multiple Columns can be compared in the WHE RE Clause, by writing a
Compound WHE RE Clause using logical operators.
Multiple Column sub queries enable us to combine the duplicate WHE RE condition into a single
WHERE Clause.
Syntax :
Select Column1, Column2,
From Table_Name
Where ( Column a, Column b , .) IN
( Select Column a, Column b . ) From Table_Name
Where Condition ) ;
Example :
Sql > Select Order_ID, Product_ID , Quantity From It em
Where ( Product_ID, Quantity ) IN
( Select Product_Id, Quantity From Item
Where Order_ID = 605 A ND Order_ID < > 605 ;
The Column comparisons in a multiple Column sub query can be
o

Pair wise Comparison

Non Pair wise Comparison

In Pair Wise comparisons each candidate row in the SELECT statement must have both the
same values associated with each column in the group.
The Non Pair Wise comparison also called cross product, we can use a WHE RE Clause with
multiple conditions.
In Non Pair Wise comparison, the candidate row must match the multiple conditions in the
WHERE Clause but the values are compared individually.

74

Oragle 10 g Material

Example :
Sql > Select Order_ID, Product_ID, Quantity From It em
Where Product_ID IN(S elect Product_ID From Item
Where Order_ID = 605 )
AND Quantity IN(Select Quantity From Item
Where Order_ID = 605
AND Order_ID < > 605 ;
Handling NULL Values in Sub Queries :
If one of the values returned by the inner query is NULL value, then the entire query returns No
Rows.
All Conditions that compare a NULL Value res ult is a NULL .
Whenever a NULL could be part of a Sub Query, it is better not to use NOT IN Operator
As it is equivalent to ! = NULL .
Example :
Sql > Select E.Ename From Emp E
Where E.Empno IN( Select M.Mgr From Emp M ) ;

Applying Sub Query in From Clause :


A Sub Query in the From Clause is equivalent to a view.
The Sub Query in the From Claus e defines a data source for that particular SELECT statement
and only that SELECT statement.
Examples in Queries :
Sql > Select E.Ename, E.Sal , E.Deptno, E1.SalA vg From Emp E,
( Select Dept no, A vg ( S al ) SalA vg From Emp
Group By Deptno ) E1 Where E.Deptno = E1.Deptno
AND E.Sal > E1.SalA vg ;
Sql > Select T1.Deptno, Dname, Staff From Dept T1,
( Select Dept no, Count( * ) As Staff From Emp
Group By Deptno ) T2
Where T1.Deptno = T2.Deptno
AND Staff > = 5 ;
Sql > Select Deptno, Sum ( Sal ) , Sum ( Sal ) / Tot_S al * 100 Salary Percentage
From Emp, ( Select Sum ( Sal ) Tot_Sal From Emp )
Group By Deptno, Tot_Sal ;
Sql > Select * From ( Select Empno, Ename, Hiredate From Emp
Order By Hiredat e Desc ) ;
Sql > Select Ename, Sal, ( Select Avg( Sal ) From Emp ) Organization A verage
From Emp ;
Sql > Select Ename, Sal, ( Select Max( Sal ) From Emp ) Organization Maximum ,
( Select Min ( Sal ) From Emp ) Organization Minimum

75

Oragle 10 g Material

From Emp ;
Sql > Select E.Emp_Count, D.Dept_Count
From ( Select Count ( * ) Emp_Count From Emp ) E,
( Select Count( * ) Dept_Count From Dept ) D ;
Sql > Select A.Deptno Department Number ,
( A.Num_Emp / B.Total_Count ) * 100 %Employees ,
( A.Sal_Sum / B.Total_Sal ) * 100 %Salary
From ( Select Deptno, Count( * ) Num_Emp,
Sum ( Sal ) Sal_Sum From Emp
Group By Deptno ) A ,
( Select Count ( * ) Total_Count,
Sum( Sal ) Total_Sal From Emp ) B ;
CORRELATED SUB QUERIES :
It is another way of performing Queries upon the data wit h a simulation of Joins.
In this the information from the outer SELE CT statement participates as a condition in the INNE R
SELECT statement.
Syntax :
Select Select_List From Table1 F_Alias1
Where Expr. Operator
( Select Column_List From Table2 F_Alias2
Where F_Alias1.Column Operator F_Alias 2.Column ) ;
Example :
Sql > Select Deptno, Ename, Sal From Emp X
Where Sal > ( Select A vg( Sal ) From Emp
Where x.Deptno = Deptno )
Order By Deptno ;
Steps Performed :
First the Outer Query is executed.
Passes the qualified column value to the inner gueries WHERE Clause.
Then the inner query or candidate query is executed., and the result is passed to the outer
queries WHERE Clause.
Depending on the supplied value the condition is qualified for the specific record.
EXISTS Operator in Correlated Sub Queries :
The E XIS TS Operator tests for existence of rows in a subquery.
It returns TRUE if a subquery returns at least one row.
Example :
Sql > Select Deptno, Dname From Dept D
Where E XIS TS ( Select * From Emp E Where D.Deptno = E.Deptno ) ;
Sql > Select Deptno, Dname From Dept D
Where NOT E XIS TS ( Select * From Emp E Where D.Deptno = E.Deptno ) ;

76

Oragle 10 g Material

Sql > Select E.Ename From Emp E


Where E XIS TS ( Select * From Emp E1 Where E1.Empno = E.Mgr ) ;

Sql > Select E.Ename From Emp E


Where NOT E XIS TS ( Select * From Emp E1 Where E1.Empno = E.Mgr ) ;
Sql > Select E.Ename From Emp E
Where E XIS TS ( Select * From Emp E1 Where E1.Mgr = E.Empno ) ;

Sql > Select E.Ename From Emp E


Where NOT E XIS TS ( Select * From Emp E1 Where E1.Mgr = E.Empno ) ;

HIERARCHI CAL QUERIES :


These are queries that are executed upon tables that contain hierarc hical data.
To execute the hierarchical queries, we need the following queries.
o

START WITH

CONNECT BY : It is used to specify the relationship bet ween parent rows and
child rows of the hierarchy.

WHERE

: It specifies the root rows of the hierarchy.

: It is used to restrict the rows returned by the Query without


affecting ot her rows of the hierarchy.

Steps Folowed :
ORACLE selects the root row ( s ) of the hierarchy, whic h satisfy the condition of the S TA RT
WITH Clause.
ORACLE selects the child rows of each root row. Each child row must satisfy the condition of the
CONNE CT BY Clause, with respect to one of the root rows.
ORACLE selects successive generations of child rows.
ORACLE selects children by evaluating the CONNECT BY condition with respect to a current
parent row.
If the query contains a WHERE Claus e, ORA CLE removed all rows from the hierarchy that do not
satisfy the condition of the WHE RE Clause .
General Representation :

Root

1
2
1
3

Child

9
7
4

10

12

11
77

Oragle 10 g Material

Leafs

Restrictions :
o
o
o

They cannot be used to perform Joins.


They cannot select data from a View, Whose Query lperforms a Join.
If ORDER BY Clause is used, then the rows are returned as per the specific ation in the
ORDER BY Clause.

The General Hirarchy of Emp Data :

KING 7839

JONES 7566

SCOTT 7788

ADAMS 7876

BLAKE 7698

FORD 7902

CLARK 7782

ALLEN 7499

SMITH 7369

MILLER 7934

WARD 7521
MARTIN 7654
TURNER 7844
JAMES 7900

General Structure of Hierarchical Tree :

LEVEL 1 :

Root / Parent

Level 2 :

Root / Parent

Root / Parent

Level 3 :

Child / Leaf

Parent / Child

Parent / Child

Level 4 :

Child / Leaf

Child / Leaf

78

Child / Leaf

Oragle 10 g Material

Note : To Define Hierarchical Queries Properly we must use the following Clauses.
o
o

STA RT WITH
CONNE CT BY

START WITH Clause :


o
o
o
o

It identifies the row(s) to be used as the Root ( s ) of a hierarchical Query.


It specifies a condition that the roots must specify.
If S TA RT WITH is omitted, Oracle uses all rows in the table as ROOT rows.
A START WITH Condition can contain a Subquery.

CONNECT BY Clause :
o
o
o
o
o

This clause specifies the Relationship between Parent and Child Rows, in a hierarc hical
query.
This caluse contains a condition that defines a relationship
This condition can be any condition as defined by the syntax decription.
Within the condition, some part of the condition must use the PRIOR operator, which
refers to the Parent row.
The forms of PRIOR operators is

o
o

PRIOR Expr Comparison operator Expr.


Expr Comparison operaor Expr.

The Clause can contain other conditions to further filter the rows selected by the query.
It cannot cont ain a Sub Query.

Example :
Sql > Select Ename, Empno, Mgr, Job From Emp
CONNECT BY PRI OR Empno = Mgr ;

Sql > Select Ename, Empno, Mgr, Job From Emp


START WITH Job = PRES IDE NT
CONNECT BY PRIOR Empno = Mgr ;

Sql > Select Ename, Empno, Mgr , Job From Emp


START WITH Ename = KING
CONNECT BY PRI OR Empno = Mgr ;
Sql > Select Ename, Empno, Mgr, Job, Sal From Emp
START WITH Sal = 5000
CONNECT BY PRI OR Empno = Mgr ;

PSEUDO Columns :
Pseudo columns behave like a table column, but is not actually stored in a table.
Upon Pseudo columns only SELECTs can be implemented, But INSERT, UPDA TE or DELE TE
Cannot be implemented.
The A vailable Pseudo Columns are

79

Oragle 10 g Material

o CURRVAL
o NEXTVAL
o LEV EL
o ROWID
o ROWNUM
CURRVAL And NEXTV AL :

These Pseudo columns are applied upon the SEQUE NCE SchemaObject.
CURRVAL returns the Curent Value of a Sequence.
NEXTVAL Increments the sequence and returns the Next Value.
The CURRV AL And NEXTVAL can be used only in
o
o
o

The SELECT list of a SELECT Statement


The VALUES Claus e of an INSERT Statement
The SE T Clause of an UPDA TE Statement.

Restrictions :
The CURRVAL and NE XTVAL cannot be used in ..
o
o
o
o
o
o
o
o

A Sub Query
A Views Query or S NAPSHOTs Query.
A SELECT Statement with the DIS TINCT operator
A SELECT Statement with a GROUP BY or ORDER BY Clause.
A SELECT Statement that is combined with another SELE CT Statement with
UNION, INERSE CT, MINUS SE T Operator.
The WHERE Claus e of a SELECT Statement
The DEFA ULT Value of Column in a CREA TE TABLE or ALTE R TABLE
Statement
The Condition of a CHE CK Constraint.

In a single SELECT Statement , all referenced sequences, LONG Columns, Updated


tables, and locked tables, must be located on the same database.
WHEN a SEQUE NCE IS Creat ed, we can define its INITIA L VALUE and the
INCREMENT between its values.
The First refrence to the NE XTVAL ret urns the SEQUENCES Initial Value.
Before the CURRVAL can be used for a SEQUE NCE is a session, first the SEQUE NCE
should be increment ed with NE XTVAL.
A SEQUENCE can be incremented only once in a single SQL Statement.
A SEQUENCE can be accessed by many users concurrently with no WAITING or
LOCK ING.
CURRVAL and NE XTVAL should be qualified with the name of the Sequence.
Syntax :
SEQUENCENAME.CURRV AL Returns the Current Value of the Sequence.
SEQUENCENAME.NEXTV AL Increments the Sequence Value by the Declar
Specification.
SEQUENCE :
A SEQUENCE is a schema object that cn generate unique sequential Values.
The SEQUE NCE Values are often user for P RIMA RY KEYS and UNIQUE KEYs.

80

Oragle 10 g Material

To refer to the Current or Next Value of a SEQUENCE in the Schema of another used. The
following privileges should be available
o
o

SELECT OBJECT P RIVILAGE


SELECT ANY S EQUENCE

For SEQUE NCES in other Schema the Qualifying Syntax is


o

SCHEMANAME.S EQUENCENAME.CURRV AL

SCHEMANAME.S EQUENCENAME.NEXTV AL

To refer to the value of a SEQUENCE on a Remote Database, The SEQUENCE should be


qualified with a complete or partial name of the Database Link.
o

SCHEMANAME.S EQUENCENAME.CURRV AL@DBLI NK


o

SCHEMA NAME.SEQUE NCE NAME.NE XTVAL@DB LINK

CREATI NG S EQUENCES :
Purpose :
An object from which multiple users may generat e Unique Integers.
Can be used to generate PRIMARY KEY values automatically.
Syntax :
CREATE SEQUENCE SequenceName
INCREMENT BY Integer
START WITH Integer
MAXVAL Interger / NOMAX VALUE
MINVAL Integer / NOMIN VALUE
CYCLE / NOCYCLE
CACHE Integer / NOCACHE
ORDER / NOORDER ;
INCREMENT BY :
o
o
o
o

Specifies the int erval between the S equence Numbers.


Vaule can be Positive or Negetive, but can not be 0.
If the value is positive it is Incrementeal Sequence else it Decremental Sequenc e.
If omitted defaults to incrementation of 1.

MINVALUE :
o

Specifies the Sequencess Minimum Vaule.

NOMINV ALUE :
o

Specigfies a minimum value of 1 for an ascending sequence or ( 10 )


For decending sequence.

26

MAXVALUE :

81

Oragle 10 g Material

Specifies the Maximum vaue that can be generat ed.

NOMAXVAULE :
o

Specifies a maximum value of 10


Sequence.

27

for ascending sequece or 1 for Descending

STARTWITH :
o
o

Specifies the first sequence Number to be generated.


For Ascending sequenc es the default value is SEQUENCESs MINIMUM v alue, Vice
Versa.

CYCLE :
o

Specifies the sequence will continue to generat e values after reaching either maximum or
minimum value.

NOCYCLE :
o

Specifies the SEQUENCE cannot genral more values after the targeted limit.

CACHE :
o

Specifies the Preallocation of SEQUENCE Numbers, The minimum is 2.

NOCACHE :
o

Specifies the values of a SEQUE NCE are not Preallocated.


If the above parameters are not specified by default 20 values are cached.

ORDER :
o

Guarant ees the sequenc e numbers to be generated in the order of request.

NOORDER :
o

Does not guarantee the sequence Number without Pre order Default .

Sample Table :
Sql > Create Table Sample
(
SampID
SampName
SampDate

Number ( 4 )
Constraint SampID_PK Primary Key,
Varchar2( 25 ) ,

) ;
Creation of Incremental Sequence with NoCycle :
Sql > Create SEQUE NCE SampleS eq
INCREMENT By 1
STA RT WITH 0
MA XVALUE 5

82

Oragle 10 g Material

NOCACHE
NOCYCLE ;
Acti vating and Attaching the Sequence to a Table :
Sql > Insert into Sample ( SampID, SampName, SampDate )
Values ( SampleSeq.NextVal, Sample, 31-A UG-05 ) ;
Note :
o
o

For every example DROP TABLE and DROP SEQUE NCE .


Create the sample table again without PRIMA RY KEY.

Creating A Sequence With CYCLE :


Sql > Create Sequence S ampleS eq
INCREMENT BY 1
STA RT WITH 0
MA XVALUE 5
NOCACHE
CYCLE ;
o

Follow the Insert statement as previous and check the Inserted Values by executing the
SELECT statement on Sample Table.

Creation of Decremental Sequence :


Sql > Create Sequence S ampleS eq
INCREMENT BY 1
STA RT WITH 5
MA XVALUE 5
MINVA LUE 0
NOCACHE
NOCYCLE ;
Guidelines For Altering A Sequence :
o
o
o
o
o

The ALTE R previlege should be available.


Only the future sequence numbers are affected by the ALTE R SEQUE NCE Statement.
The S TART WITH option cannot by changed using ALTE R SEQUENCE.
To change the S TA RT WITH. Option, drop the SEQUE NCE and then recreate the
SEQUENCE.
Some validation performed, i.e., A NRE MA XVA LUE cannot be imposed that is
less than the current SEQUE NCE number.

Level Pseudocolumn :
o

This Pseudocolumn return 1 for ROOT Node, 2 for a child of a ROOT and so on.

Child Any Non_Root Node.


Root Highest Node within an Inverted Tree.
Parent Any Node / Row that has children.
Leaf Any Node without Children.

83

Oragle 10 g Material

Modifying a Sequence :
o
o

The ALTE R Command can be used to change the present status of a SEQUENCE.
The ALTE R SEQUE NCE Command can be used to change ..

Increment Value
Maximum Value.
Minimum Value
Cycle Option
Cache Option

Syntax :
ALTER S EQUENCE SequenceName
[ INCREMENT BY n ]
[ { MAXVALUE n / NOMA XVALUE } ]
[ { MINVALUE n / NOMINVALUE } ]
[ { CYCLY / NOCY CLE } ]
[ { CACHE n / NOCACHE } ] ;
Example :
Sql > ALTER SEQUENCE SampleS eq
MA XVALUE 10
CACHE
NOCYCLE ;
Confirming Sequences :
All SEQUENCES that have been created are documted in the dta dictionary.
The data dictionary in which the information of SEQUENCES are stored is USER_OB JECTS.
The sttings of the SEQUENCE can be confirmed by SELECTING on USER_SEQUENCES.
Sqll >

Select Sequence_Name, Min_Value, Max_Value, Increment By, Last_Number


From Us er_S equences ;

Viewing the Current Value of a Se quence :


Sql > Select SampleSeq.CURRVA L From Dual ;
Dropping An Exi sting Sequence :
A SEQUE NCE can be DROPPE D at any time.
Once removed, the SEQUENCE can no longer be referenced.
Sql > DROP SEQUE NCE SampleS eq ;
To establish the Hierarchical relationship with LEVEL we need.
o

STA RT WITH

CONNE CY BY

84

Oragle 10 g Material

Sql > Select Ename, Job, Mgr, Level From Emp ;


Sql > Select Lpad ( , 2 * ( LEVEL 1 ) ) Org_Level,
Ename, Empno, Mgr, Job From Emp
STA RT WITH Job = PRESIDENT
CONNE CT BY PRIOR Empno = Mgr ;
Sql > Select Lpad ( , 2 * ( LEVEL 1 ) ) || Ename Org_Chart ,
Empno, Mgr, Job From Emp
STA RT WITH Job = PRESIDENT
CONNE CT BY PRIOR Empno = Mgr ;
Sql > Select Lpad ( , 2 * ( LEVEL 1 ) ) || Ename Org_Chart ,
Empno, Mgr, Job , Sal From Emp
WHERE Job ! = ANALYS T
STA RT WITH Job = PRESIDENT
CONNE CT BY PRIOR Empno = Mgr ;
Sql > Select Lpad ( , 2 * ( LEVEL 1 ) ) || Ename Org_Chart ,
Empno, Mgr, Job, Sal From Emp
STA RT WITH Job = PRESIDENT
CONNE CT BY PRIOR Empno = Mgr AND LEVEL < = 2 ;
Selecting Nth Highest Value From Table :
Syntax :
SELECT LEVEL, MA X ( ColName )
FROM TableName
WHERE Level = & LEVELNO
CONNE CT BY PRIOR ColName > ColName
GROUP BY LEVEL ;
Example :
Sql > SELECT LEVEL, MA X ( SAL ) FROM EMP
WHERE LEVEL = & LEVELNO
CONNE CT BY PRIOR SAL > SAL
GROUP BY LEVEL ;
Selecting Nth Lowest Value From Table :
Syntax :
SELECT LEVEL, MIN ( ColName )
FROM TableName
WHERE Level = & LEVELNO
CONNE CT BY PRIOR ColName < ColName
GROUP BY LEVEL ;
Example :
Sql > SELECT LEVEL, MIN ( SAL ) FROM EMP
WHERE LEVEL = & LEVELNO

85

Oragle 10 g Material

CONNE CT BY PRIOR SAL < SAL


GROUP BY LEVEL ;
ROWNUM P seudo Column :
For each Row returned by a query, the ROWNUM pseudocolumn returns a number indicat ed the
order in which Oracle selects the rwo from a set of Joined rows.
The First Row selected has a Rownum of 1, the second has 2. and so on
The Rownum can be used to limit the Number of rows returned by the Query.
When ORDE R BY Clause follows a Rownu, the rows will be rec ordered by ORDE R By Clause .
If ORDER BY Clause is embedded in a Sub Query and Rownum condition is palced in the
top_level query, then the Rownyum condition can be forced to applied after the ordering of the
rows.
Conditions testing for Rownum values greater than a positive integer are always False.
Sql > Select Lpad ( , RowNum, * ) From Emp ;
Sql > Select RowNum, Ename, Sal From Emp ;
Querying for Top N Records :
We can Ask for Nth largest or smallest values of a column.
Never use Rownum and ORDE R BY together as Oracle first fetches the rows according to
ROWNUM and then SORT the found rows.
From Oracle 8i , ORDE R BY can be used in V IEWS and INLINE VIEWS.
Sql > Select RowNum, Ename, Sal From Emp
Where RowNum < 6
ORDER BY Sal Desc ;

/* Wrong Way */

Sql > Select * From ( Select * From Emp ORDE R BY Sal DESC )
Where RowNum < 6 ; /* Proper Way */
ROWID P seudoColumn :
This Pseudo Column ret urns a Rwos Address for each row in the database.
ROWID Values copntain information necessary to locate a row
o
o
o

The Row belongs to which data block in the data file.


The Row belongs to which row in the Data Block ( First row is 0 )
The row belongs to which Data File ( First File is 1 )

The Rows in different tables that are stored together in the same cluster can have the same
Rowid.
The Date type of the Values belonging to the RowID are of ROW ID Data type.
Use s of ROWID Values :

ROWID is the fastest means of accessing a single row.


ROWID can show how a tables Rows are stored.
RowIDs are Unique identifiers for a Row in a Table.
A RowID can never change during the life time of its Row.
RowIDs should bnot be assigned as PRIMARY KEYs as there is a chance of ROWID to change
when the database is Exported or Imported.
When a Row is DELE TE D, ORA CLE may reassign its Rowid to a new Row that is inserted.

86

Oragle 10 g Material

The ROWID can never be INSERTE D, UPDA TE D and DELE TE D.


The ROWID Pseudo Column can be used in SELECT and WHE RE Clauses.
Sql > Select RowID, Ename, Job From Emp
Where Empno = 20 ;
Sql > Select Ename, Sal, Job From Emp
Where Rowid = AACQQAA CAAAAEHAAA ;
Sql > Select Ename, Sal, Job From Emp
Where Rowid < AACQQAA CAAAAEHAAA ;

Calculating the Cumulative Salary :


Sql > Select B.Sal, Sum ( A.Sal ) Cumulative Salary
From Emp A, Emp B
Where A.ROWID < = B.ROWID
Group By B.ROWID, B.Sal ;
SET OP ERATORS :
These operators are used to Combine information of similar date type from one or more than one
table.
Data type of the corresponding columns in all the SELE CT statement should be same.
The different types of SE T Opeators are
o

UNION

MINUS

* INTERSECT

* UNION ALL

SET operatiors can copmbine two or more queries into one result.
The ORDE R BY Caluse when iomplemented should be applied only upon the column Numbers in
the SELECT list.
UNION Operator :
The UNION Operat or merges the outputs of two or more queries into a single set of rows and
columns.
Syntax :
Select Statement 1
UNION
Select Statement 2
[ ORDE R BY Clause ]
The Queries are all executed independently but their output is merge.
Only final query ends with a semicolon.
Examples :
Sql > Select Job From Emp
Where Dept no = 20
UNION
Select Job From Emp
Where Dept no = 30 ;

87

Oragle 10 g Material

Points to Ponder :
The two select statement may not contain an ORDE R BY Clause, the final result of the entire
UNION operation can be ordered.
The number of columns retrieved by the first SELECT statement must be equal t o the number of
columns retrieved by the second SELECT, and Data types must match.
The columns used for ordering must be defined through a number.
Sql > Select Empno, Ename From Emp
Where Dept no = 10 ;
UNION :
Sql > Select Empno, Ename From Emp
Where Dept no = 30
ORDER BY 1 ;
Sql > Select Empno, Ename, Job From Emp
Where Dept no = ( Select Deptno From Dept
Where Dname = SALES )
UNION
Select Empno, Ename, Job From Emp
Where Dept no = ( Select Deptno From Dept
Where Dname = ACCOUNTING )
ORDER BY 1 ;
UNION ALL :
It is similar to UNION, where UNION suppresses the deplicates.
If the duplicate records have also to be displayed then UNION ALL is used.
Sql > Select Empno, Ename From Emp
Where Dept no = 10
UNION ALL
Select Empno, Ename From Emp
Where Dept no = 30
ORDER BY 1 ;
INTERS ECT Operator :
This operator returns the rows that are common bet ween two sets of rows.
Syntax :
Select Statement 1
INTE RSECT
Select Statement 2
[ ORDE R BY Clause ] ;
Example :
Sql > Select Job From Emp
Where Deptno = 20
INTERS ECT
Select Job From Emp

88

Oragle 10 g Material

Where Dept no = 30 ;
Sql > Select Job From Emp Where Deptno = 20
INTERS ECT
Select Job From Emp Where Dept no = 30 ;
MINUS Operator :
This operators returns the rows Unique to the first query.
Syntax :

Select Statement 1
MINUS
Select Statement 2
[ ORDE R BY Clause ] ;
Example :
Sql > Select Job From Emp Where Deptno = 20
MINUS
Select Job From Emp Where Deptno = 10 ;

Sql > Select RowNum, Ename From Emp Where RowNum < 7
MINUS
Select RowNum, Ename From Emp Where RowNum < 6 ;
VIEWS IN ORACLE :
VIEW :

It is a logical table based on one or more tables or Views.


A View in practicality contains no data by itself
The tables upon which a view is based are called as BASE TABLES.
Views can be created as Object Views or Relational Views.
The Object Views support

LOBs

* Object Types

Nested Tables

* Varrays

* REFs

Object View is a view of a user defined type, where each row contains objects, and each object
with a object Identifier.
PREREQUISITES :
Should have CREA TE VIEW or CREA TE ANY V IEW System privilege.
To create a subview, we need UNDER A NY VIEW system privilege or UNDER OB JE CT privilege
on the SUPE RVIEW.

89

Oragle 10 g Material

The OWNE R of the Schema should have SELE CT, INSERT, UP DA TE or DELE TE Rows from all
tables or Views on which the VIEW is based.
The above privileges must be granted the privileges directly, rather than a role.

Syntax :
Create [ OR REPLACE ] VIEW
[ { FORCE / NOFORCE } ] VIEW ViewName
[ ( AliasName [ , AliasName ..] ) ] As SubQuery
[ WITH { CHE CK OP TION / READ ONLY }
CONS TRA INT ConstraintName ] ;
OR REPLACE :
o

Specifies the view has to be replaced if already Existing.

FORCE :
o

Specifies the V IEW has to be creat ed even if the base tables does not exist.

NOFORCE :
o

Specifies the View Should not be created if the base table does not Exis t, which is
default.

Alias_Name :
o

Specifies the Name of an alias for an expression in the SubQuery.

WITH CHECK OPTION :


o

Specifies that only rows that would be retrieved by the SubQuery can be INSE RTE D,
UPDA TE D or DELE TE D.

CONSTRAINT :
o

Constraint_Name specifies the name of the WITH CHECK Option or READ ONLY
Constraint.

WITH READ ONLY :


o

Specifies that rows my only read from the base tables.

RESTRI CTIONS :
If a View has INSE RTED of Triggers, then only View created on it must have INS TE A D OF
Triggers, even if the Views are Inherantly Updatable.
An Alias cannot be specified when creating an OB JE CT View.
TYP ES OF VIEWS :
Simple Views :

90

Oragle 10 g Material

Which contains a SubQuery that retrieves from one base table.

Complex Views :
o
o
o
o

Cont ain a SubQuery that can perform any of these actions.


Retrieving from multiple base tables.
Groups rows using a GROUP BY or DIS TINCT Clause.
Cont ains a function call.

Simple Views :
o

These Views access one Base Table.

Example :
Sql > Create VIEW Employees As
SELECT Empno ID Number ,.
Ename Name ,
Sal Basic Salary ,
Job Designation
From Emp ;
Selecting Data From A View :
Sql > Select Name, Job From Employees ;
Sql > Select ID Number , Ename, Basic Salary * 12
From Employees ;
Sql > Select ID Number , Name ,
To_Char ( Basic Salary , 99,99,999.99 ) Monthly
Basic Salary * 12 Annual
From Employees
Where Basic Salary > 2500 ;
Complex Views :
o
o

Complex Views can contain SubQueries.


The SubQuery can contain, Queries

That Ret rieve from multiple Base Tables


Group Rows using a GROUP BY or DIS TINCT Clause.
Cont aing a Functional Call .

Example :
Sql > Create VIEW EmpInfo As
Select E.Empno
EmployeeID,
E.Ename
Name ,
D.Deptno
DepartmentID ,
D.Dname
Deparatment Name
From Emp E, Dept D

91

Oragle 10 g Material

Where D.Deptno = E.Deptno


ORDER BY D.Deptno ;

Sql > Create VIEW EmpGrades As


Select E.Ename
Name ,
E.Sal
Basic ,
S.Grade
Grade
From Emp E , Salgrade S
Where E.Sal BE TWEEN
S.LoSal AND S.HiSal
ORDER BY S.Grade ;
Sql > Create or Replace VIEW EmpManagers AS
Select RowNum SerialNo ,
Initcap ( E.Ename ) || Works Under ||
M.Ename Employ ee And Managers
From Emp E, Emp M
Where E.Mgr = M.Empno ;

Sql > Create or Replace VIEW EmpAccounts As


Select Ename, Deptno , Sal Monthly ,
Sal * 12 Annual
From Emp
Where Dept no = ( Select Deptno
From Dept
Where Dname = ACCOUNTING )
ORDER BY Annual ;

Sql > Create or Replace VIEW CumSum As


Select B.Sal , Sum ( A.Sal ) As Cum_Sal
From Emp A, Emp B
Where A.RowID < = B.RowID
GROUP BY B.RowID , B.Sal ;

Sql > Create or Replace VIEW OrgDesignations As


Select Job From Emp Where Deptno = 10
UNION
Select Job From Emp Where Deptno IN( 20, 30 ) ;
VIEWS in Data Dictionary :
Once the View has been created, we can query upon the DA TA DICTIONARY table called
USER_V IEWS to see the Name and definiton of the View.
The text of the SELE CT statement that constitures the VIEW is stroed in a LONG Column

Data Acce ss Using Views :

92

Oragle 10 g Material

The Steps or operations performed by the Oracle Server, when data is accessed using a VIEW
are
o
o
o

Retrieves the VIEW definition from the Data Dictionary table USER_VIEWS.
Checks the Access privileges for the view base table.
Converts the view query into an equivalent opration on the underlying base tabl e or
tables.

Modifying A View :
OR REP LACE Option is used to Modify an existing V IEW with a new definition.
A VIEW can be altered without Dropping, recreating, and regranting object privileges.
The assigned column Aliases in the CREA TE VIEW Clause, are listed in the same order as the
columns in the SubQuery.
Creating Views with Columns Declarations :
When a VIEW is being crated, we can specify the Names of the Columns, that it can project,
along with the V IEWs definition.
Example :
Sql > Create VIEW DeptSalSummary
( DepartmentName ,
MinimumSalary ,
MaxSalary ,
AverageSalary,
SalarySum
) As
Select D.Dname, Min (E.Sal ) , Max ( E.Sal ) , Avg ( E.Sal ) , Sum ( E.Sal )
From Emp E, Dept D
Where E.Deptno = D.Deptno
Group By D.Dname ;
Sql > Create VIEW InsertDept10 As
Select * From Emp
Where Dept no = 10 ;

Inserting The Total Data of Employees From Department 10 Using View :


Sql > Create Table Dept10
As Select * From Insert Dept10 ;

Sql > Create Table EmpGrades ( Employee ,


Designation ,
BasicSalary ,
Grade
) As
Select Ename, Job, Sal, Grade From Emp E, SalGrade S
Where E.Sal BE TWEEN S.LoSal AND S.HiSal ;
DROPPING A VI EW :
The DROP V IEW statement is used to Remove a View permanently.

93

Oragle 10 g Material

Dropping a View has no affect on the tables upon which the View is created.
VIEWS or APPLICA TIONS based on deleted Views become invalid.
We need DROP ANY VIEW privilege to remove the V IEWS.

Syntax :
DROP VIEW ViewName ;
Example :
DROP VIEW InsertDept ;
INLINE VIEWS :
An INLINE VIEW is a SubQuery with an ALIAS ( Called as CORRELA TION NAME ), that can be
used within a SQL Statement.
An INLINE VIEW is similar to using a named SubQuery in the FROM Clause of the Main Query.
An INLINE VIEWE is not a Schema Object.
An INLINE VIEW in the FROM Clause of a SELE CT statement defining Dat a Source for the
SELECT statement.
Examples :
Sql > Select E1.Ename , E1.Sal , E1.Deptno, E2.MaxSal
From Emp E1 , ( Select Deptno, Max ( Sal ) MaxSal
From Emp GROUP BY Deptno ) E2
Where E1. Dept no = E2.Deptno
AND
E1.Sal < E2.MaxSal ;

Rules for Performing DML Operations On A View :


DML operatons can be perfomed upon a table through VIEW.
A row can be removed from a VIEW unless it contains.
o
o
o
o
o

GROUP Function
A GROUP By Clause
The ROWNUM PESUDO COLUMN
The DIS TINCT Key Word
The Columns defined by Expressions.

Data can be added through a view, unless it contains any of the above rules and there are NOT
NULL Columns, and wit hout DEFA ULT V alue.
Example :
Sql > Create View Insert Dept ( DeptID,
DeptName ,
Place
) AS
Select Deptno, Dname, Loc From Dept ;

94

Oragle 10 g Material

Using with CHECK Option Clause :


To ensure that DML on the view stays within the domain of the VIEW by using the WITH CHECK
option Claus e.
VIEWS make it possible to perform Referential Integrity Checks.
Using VIEWS we can enforece constraints at database level.
Using VIEWS we can protect the DA TA INTEGRITY, But the use is very limited.
The WITH CHECK Option Clause specifies that INSERTS, & UP DA TES performed through the
V?IEW are not allowed to create rows, that the VIEW cannot SELECT.
VIEWS allow Integrity Constraits and data validation check to be enforced on data being Inserted
or Updat ed.

Example :
Sql > Create Or Replace VIEW EDept30
AS
Select * From Emp Where Deptno = 30
WITH CHE CK OP TION CONS TRA INT EDept30ChkView ;

Sql > Create Or Replace V IEW Emanager


AS
Select * From Emp Where Job = MANAGE R
WITH CHE CK OP TION CONS TRA INT EmanagerView ;
Applying With READ ONLY OPTION :
By Adding the WITH REA D ONLY option we can ensure that no DML operations are executed.
An attempt to perform a DML operation results in ORA CLE SERVE R ERROR.
Example :
Sql > Create Or Replace View E dpet Read
( EmpId, Name, Designation )
AS
Select Empno, Ename, Job From Emp
Where Dept no = 20
WITH REA D ONLY ;
VIEW CONSTRAINT :
In practicality Oracle does not enforce View constrains, but operations on VIEWS are subject to
the INTEGRITY CONS TRA INTS defined on the underlying base tables.
CONS TRA INTS on VIEWS can be enforced through CONS TRA INTS n base tables.
Restrictions On View Constaints :
The VIEW Constraints area subset of TAB LE CONS TA INTS.
Only UNIQUE, PRIMARY KEY And FORE IGN KEY CONS TRA INTS can be specified on
VIEWES.
The CHECK CONS TRA INT is imposed using WITH CHECK OP TION.
As VIEW CONS TRA INTS are not enforced directly, we cannot specify INTIALLY DEFERRE D or
DEFREEABLE.
VIEW CONTRA INTS are supported only in DISABLE NOVALIDA TE mode.

95

Oragle 10 g Material

INITIALLY DEFERRED :
It Indicat ed that Oracle should check this CONS TRA INT at the end of S UBSEQUE NT
transactions.

Note :
INTIALLY DEFERRED i s not valied if the CONS TRA INT is declared to be
NOTDEFERRABLE
NOT DE FREEABLE CONS TRA INT is AUTOMA TICALLY INITIA LLY IMMEDIA TE and can
never be INITIALLY DE FERRED.
VALIDATE / NOTV ALIDATE :
The Behavior of VALIDA TE and NOVALIDA TE always depends on whether the CONS TRA INT is
ENABLED / DISABLED, either E XPLICITLY or by DEFA ULT.
RELY CLAUS E :
RELY and NORELY are valid only when we are modifying an existing CONS TRINT.
RELY :
It activates an existing CONS TRA INT is NOVALIDA TE mode for query rewrite, in an
unenforced query rewrit e Int egrity mode.

DEFERRABLE Clause :
The DEFE RRABLE and NOTDEFE RRAB LE parameters indicate whet her or not, in the
subsequent transaction, constraint checking can be deferred until the end of the transction using
the SET CONS TRA INT statement.
The default is NOT DEFE RRAB LE.
NOTDEFERRABLE :
It indicates that in subsequent transctions, wee cannot use the SET CONS TRA INT(s) Clause
to defer checking the CONS TRAINT UNTIL the trans action is committed.
The checking of a NOTDEFERRABLE CONS TRA INT can Never be DEFE RRE D to the end
of the transactions.

DEFERRABLE :
It indicated that in subsequent transctions we can use the SE T CONS TRAINT(s ) Clause to
defer checking the CONS TRA INT until aft er the transaction is committed.
The setting is effect lets the user to disable the CONS TRA INT temporarily while making
changes to the database that might violate the CONS TRA INT until all the changes are
complete.
To alter the CONS TRAINTS Deferability, we must DROP the CONS TRAINT and recereate it.
Restriction On The DEFERRABLE Clause :
The parameters cannot be specified for a V IEW CONS TRA INT.

96

Oragle 10 g Material

INITIALLY Clause :
It established the default checking behavior for CONS TRA INTS that are DEFERRABLE.
The INITIALLY setting can be overridden by a SET CONS TRA INT(s) statement in a
subsequent Transaction.
Initially Immediate :
It indicated that Oracle should check this CONS TRA INT at the end of each
subsequent SQL statement .
It is the default setting.
We cannot specify the Using_Indes _Clause the Exceptions_Clause or the ON
DELE TE Clause of the Reference_Clause.
VIEW CONS TRA INTS cannot be defined on attribute of an object column.
Sql > Create View EmpSalary
(
EmpID, Ename, Email UNIQUE RELY DISAB LE NOVALIDA TE ,
Constraint ID_PK PRIMA RY KEY ( EmpID ) RELY DISABLE
NOVALIDA TE ) AS
Select Empno, Ename, Email From Emp ;
Constraint State specifies how and when ORACLE should enforce the
CONS TRA INT.
The constraint state clauses can be specified in any order, but each state can be
specified only once.
Restriction on RELY Clause :
We cannot set a NOT NULL CONS TRA INT to RELY.
Example :
Sql > Create Table Games ( Scores Number Check ( Scores > = 0 ) ) ;
Note : In the above case the default constraint is NOT DEFERRABLE
INTITALLY IMME DIA TE constraint CHE CK.
Sql > Create Table Games1
(
Scores Number ,
Constraint Sco_Num_Unq UNIQUE ( Scores )
INITIALLY DEFERRE D DEFE RRABLE ) ;
WORKI NG WITH INDEX ES :
INDEX :
It is a Schema object which contains an entry for each value that appears in the indexed
column(s ) of the table or cluster.
It provides Direct, Fast Access to Rows.
Type s of INDEX ES :
NORMAL INDEX ES :

97

Oragle 10 g Material

o
o

They are default Indexes.


They are created with B-Tree principle.

BITMAP INDEX ES :
o

They store RowIDs associated with a key value as a Bitmap.

PARTITIONED INDEX ES :
o

They contain partitions containing an entry for eac h value that appears in the Indexed
columns of the table.

FUNCTION BAS ED INDEX ES :


o
o

They are based on expressions.


Enable query to evaluat e value retuned by an expression.

DOMAIN INDEXES :
o

They are INDE XES which are instances of an application specific index of type
Indextype.

PRE REQUISITES :

The table or CLUS TER to be INDE XE D must be in the Own Schema.


INDE X object parivilege should be available on the table to INDE XE D.
Cerate any index SYSTEM privilege must be available.
UNLIMITE D TABLESPACE system privilege or SPACE QUOTA on TAB LE SPACES must be
available.
For DOMAIN INDE XES, E XE CUTE object privilege on the INDE XTYPE should be available.
For FUCTION BASED INDE XES, the FUNCTION used for Indexing must be marked as
DE TERMINIS TIC.
RESTRI CTIONS :
If INDE X is locally partitioned then the TABLE msut be partitioned.
If the TABLE is INDE X ORAGA NIZED, then a SECONDARY INDE X is created.
If TABLE is TEMPORA RY TABLE, then INDE X is also TEMPORA RY with the same scope, as
that of the TABLE.
Restriction On INDEX Columns :
An INDE X c annot be created on Columns or A TTRIB UTES whose type is .
o
o
o
o
o

USER DEFI NED


LONG
LONG RAW
LOB
REF

An INDE X on REF tyhpe columns Or attributes have to be declared with a SCOPE Clause.
Simple Index Example :

98

Oragle 10 g Material

Sql > Create INDE X EmpEmpnoIDx On Emp ( Empno ) ;


Sql > Creat e INDE X Dept DeptnoIDx On Dept ( Deptno ) ;

Syntax :
Create [ UNIQUE ] INDE X IndexName
or
[ BITMAP ] ON
TableName ( Column_name [ , ColumnName .] )
TABLESPA CE TableSpaceName ;
Unique :
* Specify UNIQUE to indicate that the value of the column or columns upon
which the Index is based must be UNIQUE.
Restrictions :
* We cannot specify both UNIQUE and BITMAP.
* UNIQUE Cannot be specified for a domain Index.
BITMAP :
Specify BITMAP to indic ate that INDE X has to be careated with a BITMAP for each DIS TINCT
KEY.
BITMAP Indexes store the RowIDs associated with a key value as a BITMAP.
Each BIT in the B ITMAP corresponds to a possible RowID.
Restrictions :
BITMAP cannot be specified when creating a global partit ioned Index.
BITMAP SECONDA RY INDE X canot be created on an INDE X ORGA NIZE D TABLE unless the
INDE X ORGANIZE D table has a mapping table Associated with it.
We cannot specify both UNIQUE and B ITMAP.
BITMAP cannot be specified for a DOMAIN INDE X.
CLUTER INDEX CLAUSE :
It identifies the CLUS TE R for which a CLUS TER INDE X has to be created.
CLUS TER INDE X Cannot be created for a HASH CLUS TER.
TABLE INDEX CLAUS E :
It identifies the TABLE upon which the INDE X is being defined.
An INDE X on a NES TED TABLE COLUMN can be created by creating the INDE X on the
NES TED storage Table.
CREATI NG UNIQUE INDEX ES :
Sql > Create UNIQUE INDE X EmpEmailIDxUNQ ON Emp ( Email ) ;

99

Oragle 10 g Material

Sql > Create UNIQUE INDE X StuPhnoIDxUNQ ON Student ( PhoneNo ) ;


CRATI NG COMPOSITE INDEXES :
COMPOS ITE INDE X is an INDE X on multiple Columns.

Sql > Create INDE X Stud_Fname_Lname_Idx On Student ( Fname, Lname ) ;


Sql > Create INDE X Emp_Name_Place_IDX ON Emp ( Ename , Street Name ) ;

CREATI NG FUNCTION BASED INDEXES :


These are indexes based on ex pressions.
The Index Expresions are Built from table columns, contancts SQL Functions and User Defined
Function.
Functin based Index es defined with the UPPER ( Column_Name ) or LOWER ( Column_Name )
allow case Insensitive Searches.
To ensure that Oracle uses the Index rather than performing a full table scan, we shoul;d be sure
that the value of the Functins is not NOT NULL in subsequent Queries.
Oracle treats INDE XES with columns marked DESC as Functins Based Indexes.
Example :
Sql > Create INDE X EmpUpperCaseIDx ON
Emp ( UPPER ( Ename ) ) ;
Note : The Function Based Indexes are used only when the Query Statement is
executed through the specified function.
BITMAP INDEXING :
These Indexes are used to tune Queries that use non selective columns in their limiting
conditions
BITMAP INDE XES should be used only when the data is inferequently updated.
BITMPA T INDE XES add to the cost of all data manipulation transaction against the tables they
INDE X.
The ORACLE OP TIMIZE R can dynamically convert BITMAP INDE XES entries to ROWIDs
during the query processing.
Examples :
Sql > Create BITMAP INDE X EmpBitMapJob ON Emp ( Job ) ;
Limitations :
BITMAP INDEX ES should not be used for tables involved in ONLINE TRA NSACTION
PROCESSING applications due to the Internal Mechanisms Oracle user to maintain them.
Restricted with usage to tables involved in Batch transactions.

Specification of An INDEX :
INDE X IS A Schema Object.

100

Oragle 10 g Material

INDE X is used by the ORACLE SERVE R to speed up Retrieval of rows by using a Poiter.
INDE X Reduces the Disk I / O by using rapid path Access method to locate the data quickly.
INDE XEs are Independent of the table it INDE XES, both logically and physically.
INDE X is used and maintained automatically by the ORA CLE SERVER.
INDE XEs can be creat ed or Dropped at any time and have no effect on the base tables or other
INDE XES.
When a table is droopped, the Corresponding INDE XES are also dropped.
INDEX Creation is of Two Types :
1 ) Automatic

2 ) Manual

One Table more than one Index can be created, But this does not mean that, more the Indexes
lead to more faster performance.
Each DML operations that is committed on a table wit h Indexes means that the Indexes must be
updated.
WHEN TO CREATE AN INDEX :

The Column is used frequently in the WHERE Clause or ina Join Condition.
The Column contains a wide range of values.
The column contains a large number of NULL values.
Two or more columns are frequently used together in a WHERE clause or Join Condition.
The table is large and most queries are ex pected to retrieve less than 2 4 % of the rows.

WHEN NOT TO CREATE AN INDEX :

The table is too small


The columns are not oft en used as condition in the query
Most queries are ex pected to retrieve morethan 2 4 % of the rows.
The table is updated frequently
The indexes can be confirmed form the USER_INDE XES Data Dictionarly.
The Column that are involved in an INDE X by querying USE R_IND_COLUMNS.
To DROP an INDE X DROP command is used
DROP INDE X INDE X_NAME ;

DATABAS E SECURITY :
The SECURITY upon databases is applied by defining and describing separate SCHEMA
OBJECTS and GRA NTING required PRIV ILEGES upon them.
In ORACLE the Privileges can be ranted as well as Revolved.
GRANT COMMAND :
Syntax :
GRANT < PRIVILAGES NAME > , ,,,,,,,
ON
< Object_Name > To < User Name >
GRA NT command is used when we waqnt the dat abase to be shared with other users.
The other users are GRA NTED with certain type of rights.
GRAB T cinnabd cab be issued not only on TABLE OB JE CT, but also on V IEWS, SYNONYMS,
INDE XES, SEQUENCES etc.,

101

Oragle 10 g Material

Example :
Sql > GRANT SELE CT ON EMP TO ENDUSERS ;
Sql > GRANT INSERT, SELE CT, DELE TE ON EMP TO OPERA TORS ;
Sql > GRANT INSERT ( Empno, Ename, Job ) ON Emp To E ndUsers ;
REVOKE COMMAND :
Syntax :
REVOKE < PRIVILEGE NAME > , .. ON < OBJECT NAME . TO < USER NAME .
REVOKE is usede when we want one database to stop sharing the information with other users.
REVOKE privileges is assigned not only on table onject, but also Views, Synonyms, Index es
etc,
Example :
Sql > REVOKE INSERT , DELE TE ON EMP FROM Operators ;
Type s of Privileges :
System Privileges :
o

They allow a user to perform certain actions within the database.

Object Privileges :
o

An Object Privilege allows a user to perform cetain actions on database objects.

Checking the Object Privileges Granted :


The schema object that stores the information about the privileges is
o

USER_TAB_P RIV_MADE

The Column of USER_TAB_P RIV _MADE


o

GRANTEE

TABLE_NAME

GRANTOR

PRIVILEGE

GRANTABLE

HIERARCHY

Checking Obect Privileges Received :


The schema object that stores the information about the PRIV ILEGES received are
o

USER_TAB_P RIVS_RECD

The column of USER_TAB_P RIVS _RE CD are ..


o

OWNER

TABLE_NAME

102

Oragle 10 g Material

GRANTOR

PRIVILEGE

GRANTABLE

HIERARCHY

MAKI NG US E OF OBJECT P RIVILEGES :


Once a particular USER has benn granted an object privilege, the specific USER can perform the
Tasks.
Steps to be performed
o
o

Connect to the required user.


Execute the require SQL Statement using the object Hierarchy.

Example :
Sql > CONNECT SA TIS H / YELLANKI
Sql > SELECT * From SCOTT.EMP ;

WORKING WITH ROLES :


A ROLE is a group of PRIV ILEGES that can be assigned to a USE R or another ROLE.
Advantages :
Rather than assigning Privileges one at a time directly to a USER, we can CREA TE a ROLE,
assign PRIVILEGES to that ROLE, and then GRA NT that ROLE to multiple USERS and ROLES.
When you ADD or DELE TE a PRIVILEGE from a ROLE, all USERS and ROLES assigned that
automatically rec eive or lose that PRIV ILE GE
We can Assign multiple roles to a USER or ROLE.
A ROLE can be assigned with a Password.
ROLE s CREATION :
To CREATE a ROLE we should have the CREA TE ROLE SYS TEM privilege.
The Steps in Implementing the ROLES
o
o
o

ROLE CREATION
GRANTI NG PRIVILEGES TO ROLES
GRANTI NG ROLES TO US ERS or OBJECTS

Syntax :
CREATE ROLE < Role Name > IDE NTIFIE D BY < Password > ] ;
Example :
Sql > CREATE ROLE Sales_Mangers IDE NTIFIE D BY SalesAudit ;

Granting Privileges to ROLE :

103

Oragle 10 g Material

The ROLES are granted privileges using the GRA NT statement.


A ROLE can be granted both SYS TEM as well as OB JECT privileges
Example :
Sql > GRANT SELE CT, INSERT, UP DA TE, DELE TE
ON EMP TO Sales_Manager ;
Granting A ROLE To a USER :
Sql > GRANT Sales_Manager to Scott ;
Granting Multiple ROLES to Another Role :
Sql > GRANT ROLE 1, ROLE 2 , .. TO < TA RGE T_ROLE_NAME > ;
Checking ROLES Granted to a USER :
The SCHEMA OBJE CT USE R_ROLE_P RIVS specifies the roles granted to a USER.
The SCHEMA OBJE CT USE R_ROLE_P RIVS contains the following columns.
USERNAME
ADMI N_OPTION

GRANTED_ROLE
DEFAULT_ROLE

OS_GRANTED
Checking System Privileges Granted to A ROLE :
The Schema Object ROLE_SYS-P RIVS specifies the SYS TEM PRIVILEGES Granted to a
ROLE.
The columns present are.
* ROLE
* PRIVILEGE
Checking Object Privileges Granted to a Role :

* ADMIN_OPTION

The Schema Object , ROLE_TAB_P RIVS specifies the OB JECT P RIV ILE GES granted to a
ROLE.
The columns present are
ROLE

OWNER

PRIVILEGE

GRANTABLE

TABLE_NAME

COLUMN_NAME

Revoking a ROLE :
Sql > REVOKE Sales_Managers From Scott ;
Revoking Privileges From A ROLE :
Sql > REVOKE ALL ON Emp From Sales _Managers ;
Dropping A Role :
Syntax :

DROP ROLE < Role_Name >

104

Oragle 10 g Material

Example :

DROP ROLE Sales_Managers ;

WORKI NG WITH SYNONYMS :


A Synonym is schema object, which acts as an alternate name for an existing object.
By using a Synonym, we can avoid the entry of the schema Name, when referencing upon
objects that belong to other schema.
The CREA TE Synonym Privileges is necessary to execute the creation of a Synonym.
Syntax :
Create Synonym < Synonym Name > FOR < SchemaName >. < ObjectName > ;
Example :
Create Synonym EmpInfo FOR SCOTT.EMP ;
Synonym Type s :
The Synonyms are practically of two types
PRIVATE SYNONYM

PUBLI C SYNONYM

We should have CREA TE PUBLIC SY NONYM privilege, and it can be accessed by all USERS.
Example :
Sql > Create PUBLIC S YNONYM EmpInfo FOR S COTT.Emp ;

OLAP FEATURES IN ORACLE :


Some features for Query processing is ORA CLE include the use of ONLINE ANALY TICAL
PROCESSING ( OLAP ) upon the Data base.
OLAP features are useful for DA TA WARE HOUSING and DA TA MART applications.
The OLAP operations are performance enhancements.
TOP_N QUERIES
GROUP BY
CUBE
ROLL UP
ROLL UP :
It is a GROUP BY operation and is used to produce subtotals at any level of the
Aggregation.
The generated substotals ROLL UP to produce grant total .
The totaling is based on a one dimensional Dat a Hierarchy of grouped Information.
Syntax :
GROUP BY ROLLUP ( Column1, Column2 .)

105

Oragle 10 g Material

General Implementation :
Example :
Sql > Select Deptno, Sum ( Sal ) From Emp
Group By RollUp ( Deptno ) ;
Sql > Select Job, Sum ( Sal ) From Emp
Group By RollUp ( Job ) ;
Passing Multiple Columns To RollUp :
When multiple columns are passed to ROLLUP, the ROLL UP , groups the rows into blocks with
the same column values.
Example :
Sql > Select Deptno, Job, Sum ( Sal ) Salary From Emp
Group By RollUp ( Deptno, Job ) ;
Sql > Select Job, Deptno, Sum ( Sal ) Salary From Emp
Group By RollUp ( Job, Dept no ) ;
Sql > Select Job, Deptno, A vg ( Sal ) A verage From Emp
Group By RollUp ( Job, Dept no ) ;
Note :
o
o

NULL Values in the output of ROLLUP operations typically mean that the row contains
subtotal or grant total information.
Use the Nvl ( ) Function for proper meaning.

CUBE :
It is an extension similar to ROLLUP.
CUBE allows to take a specified set of grouping columns and crate sub totals for all possible
cominatins of them.
The result of CUBE is a summary that shows subtotals for every cominiation of columns or
expressions in the GROUP BY clause .
The implementation of CUBE is also called as n-dimensional CROSS_TAB ULA TION.
Example :
Sql > Deptno, Job, Sum ( Sal ) Salary From Emp
Group By CUBE ( Deptno, Job ) ;
Sql > Job, Deptno , Sum ( Sal ) Salary From Emp
Group By CUBE ( Job, Deptno ) ;
Applying Grouping ( ) Function :
The GROUP ING ( ) Function accepts a column and returns 0 or 1.
GROUP ING ( ) Function returns 1 when the column value is NULL, and returns 0 when the
column value is NOT NULL.
GROUP ING ( ) Function is used only upon queries that use ROLLUP or CUBE.

106

Oragle 10 g Material

GROUP ING ( ) Function is useful when we want to display a value when a NULL would otherwise
be ret urned.

Example :
Sql > Select GROUP ING ( Dept no ) , Deptno , Sum ( Sal ) From Emp
Group By RollUp ( Dept no ) ;
Sql > Select GROUP ING ( Job ) , Job , Sum ( Sal ) From Emp
Group By RollUp ( Job ) ;
DECODE Function :

It is a single row function.


The function works on the same principle as the if then else.
We can pass a variable number of values into the call of the DE CODE( ) function.
The first item is always the name of the column that need to be DE CODED.
Once all value-substitute paris have been defined, we can optionally specify a DEFAULT Value.
Syntax :
Select DECODE ( ColumnName, Value 1, Substitute1, Value 2,
Substitute2, . Return Default ) From TableName ;

The function has no restrictuon on the input and output data type.
Example :
Sql > Select Ename, DECODE ( Deptno, 10 , ACCOUNTING ,
20 , RESEARCH ,
30 , SALES ,
40 , OPERATIONS ,
OTHER ) Departments
From Emp ORDER BY Departments ;
Sql > Select Ename || Takes Care of ||
DECODE ( Job, ANA LYS T , ANALYSIS ,
CLERK , FIRING ,
MANAGER , MANAGING ,
PRESIDE NT , ADMINIS TRA TION ,
SALESMAN , SALES ) Responsibilities
From Emp ;
Sql > Select Ename, Job, DE CODE ( Job ,
CLE RK , E ,
SALESMAN , D ,
ANALYS T , C ,
MANAGER , B ,
PRESIDENT , A ,
O ) GRADES
FROM EMP ORDE R BY JOB ;

107

Oragle 10 g Material

Sql > Select Count ( * ) Total ,


Sum ( DECODE ( To_Char (
Sum ( DECODE ( To_Char (
Sum ( DECODE ( To_Char (
Sum ( DECODE ( To_Char (
From Emp ;

Hiredate,
Hiredate,
Hiredate,
Hiredate,

YYYY ) ,
YYYY ) ,
YYYY ) ,
YYYY ) ,

1980,1, 0 ) )
1981,1, 0 ) )
1982,1, 0 ) )
1983,1, 0 ) )

1980 ,
1981 ,
1982 ,
1983

Sql > Select Job, Sal, DECODE ( Job, ANALYS T , Sal * 1.1 ,
CLE RK , Sal * 1.15 ,
MANAGER , Sal * 1.2 , Sal
) REVISE D SALARY
From Emp ;
Count ( DE CODE ( Deptno, 10 , * , NULL ) ) D10_COUNT ,
Sum( DE CODE ( Deptno, 10 , Sal , NULL ) ) D10_S al ,
Count ( DE CODE ( Deptno, 20 , * , NULL ) ) D20_COUNT ,
Sum( DE CODE ( Deptno, 20 , Sal , NULL ) ) D20_S al ,
Count ( DE CODE ( Deptno, 30 , * , NULL ) ) D30_COUNT ,
Sum( DE CODE ( Deptno, 30 , Sal , NULL ) ) D30_S al
From Emp ;

Sql > Select

Sql > Select Job,


Sum ( DECODE ( Deptno , 10 , Sal ) ) Deptno 10 ,
Sum ( DECODE ( Deptno , 20 , Sal ) ) Deptno 20 ,
Sum ( DECODE ( Deptno , 30 , Sal ) ) Deptno 30 ,
Sum ( Sal ) Tot al
From Emp GROUP BY Job ;

Grouping With DECODE ( ) :


The DE CODE ( ) Function can be used to convert 1 and 0 ret urned through GROUPING ( ) into a
meaningful outpout.
Examples :
Sql > Select DECODE ( GROUPING ( Deptno ) ,
1, All Departments , Deptno ) Departments ,
Sum ( Sal ) From Emp Group By RollUp ( Deptno ) ;

Sql > Select DECODE ( GROUPING ( Job ) ,


1, All Designations , Job ) Designations ,
Sum ( Sal ) From Emp Group By RollUp ( Job ) ;

DECODE ( ) and GROUPING ( ) for Converting Multiple Column Values :


Example :
Sql > Select DECODE ( GROUPING ( Deptno ) ,
1 , All Departments , Deptno ) Departments ,
DECODE ( GROUPING ( Job ) ,
1, All Designations , Job ) Designations ,
Sum ( Sal ) From Emp

108

Oragle 10 g Material

Group By RollUp ( Dept no , Job ) ;

GROUPING ( ) With DECODE ( ) and CUBE :


Example :
Sql > Select DECODE ( GROUP ING ( Deptno ) ,
1 , All Departments , Deptno ) Departments ,
DECODE ( GROUP ING ( Job ) ,
1, All Designations , Job ) Designations ,
Sum ( Sal ) From Emp
Group By CUBE ( Dept no , Job ) ;
Applying Grouping SETs Clause :
The GROUPING SE TS Clause is used to get the Subtotal rows.
Example :
Sql > Select Deptno, Job, Sum ( Sal ) From Emp
Group By GROUP ING SETS ( Deptno, Job ) ;
Working with CAS E Expre ssion :
The CASE Expression can be used to perform if then else logic in SQL.
CASE is similar to DECODE byut is ANSI Compliant.
CASE Expressions are of two types
o

Simple CAS E Expre ssions

Searched CASE Expre ssions.

Simple CASE Expre ssions :


These Expressions are used to det ermine the retuned value.
Syntax :
CAS E Search_Expr
WHEN Expr 1 THEN Result 1
WHEN Expr 2 THEN Result 2
.
.
ELS E Default_Re sult
END ;
Example :
Sql > Select Ename, Deptno
CASE Deptno
WHEN 10 THEN A CCOUNTS

109

Oragle 10 g Material

WHEN 20 THEN RESEARCH


WHEN 30 THEN SALES
WHEN 40 THEN OPE RA TIONS
ELSE NOT FOUND
END
From Emp ;

SEARCHED CAS E Expre ssions :


They use conditions to determine the returned value.
Syntax :
CAS E
WHEN Condition 1 THEN Re sult 1
WHEN Condition 2 THEN Re sult 2
:
WHEN Condition n THEN Result n
ELS E Default_Re sult
END

Example :
Sql > Select Ename, Deptno ,
CASE
WHEN Deptno = 10 THE N
WHEN Deptno = 20 THE N
WHEN Deptno = 30 THE N
WHEN Deptno = 40 THE N
ELSE Not Specified
END
From Emp ;

ACCOUNTING
RESEARCH
SALES
OPERA TIONS

Sql > Ename, Sal,


CAS E
WHEN Sal > = 800 AND Sal < = 2000 THEN
LOWEST PAY
WHEN Sal > = 2000 AND Sal < = 4000 THEN
MODERATE PAY
ELS E HIGH PAY END From Emp ;
MATERI ALI ZED VI EWS :
Materialized Views are used in DA TA WARE HOUSES.
They are used to increase the speed of q ueries on Very large dat abases
Queries Making Use of M. Views :
AGGRE GA TION on a Single Table.
JOINS Bet ween Tables.
AGGRE GA TIONS and JOINS.
Materialized Views can be used to replicat e data.
PRIOR to Materialized Views, the Concept of SNAPS HOT was Implemented.

110

Oragle 10 g Material

Query Rewrite :
Materialized Views improve query performance by PRE CALCULA TING Expensive JOIN
and AGGRE GA TION operations on the DA TABASE PRIOR to Execution time and stores
the results in the DA TABASE.
The Query OP TIMIZER can make use of MA TERIALIZE D VIEWS by automatically
recognizing when an Existing MA TERIALIZE D VIEW can and should be used to satisfy a
Request.
After above process is completed then the QUERY OP TIMIZE R transparently rewrites
the request to use the MA TERIALIZE D VIEW.
QUE RIES are then directed to the MA TERIALIZE D VIEW and not to the underlying
DE TAIL TABLES or VIEWS.
REWRITING QUE RIES to yuse MA TERIALIZE D VIEWS rather than detail relations,
results in a significant performance gain.
PREREQUISITES FOR MATERIALI ZED VIEWS PRIVILEGES :
Sql > GRANT QUERY REWRITE TO SCOTT ;
Sql > GRANT CREA TE MA TERIALIZE D VIEW TO SCOTT ;
Sql > ALTER SESSION SE T QUERY _REWRITE _ENABLE D = TRUE ;
Set the InitSid.ORA File :

OPTIMIZE R_MODE = CHOOSE


JOB_QUE UE_INTERVAL = 3600
JOB_QUE UE_P ROCESSES = 1
QUE RY_REW RITE _ENAB LED = TRUE
QUE RY_REW RITE _INTE GRITY = ENFORCE D

Example of Materialized View With Aggregation :


Sql > Create MA TERIALIZE D VIEW Emp_Sum
ENABLED QUE RY REWRITE
AS
SELECT Deptno , Job, Sum ( Sal ) From Emp
Group By Deptno , Job ;
Creating Optimizer Statistics and Refreshing Materialized Views :
Sql > EXECUTE DBMS_UTILITY.ANA LY ZE_SCHEMA
( SCOTT , ESTIMA TE ) ;
Sql > EXECUTE DBMS_MV IEW.REFRESH ( Emp_Sum ) ;
Testing Materialized View :
Sql > SET AUTOTRA CE ON E XPLA IN ;
Sql > SELECT Deptno, Sum ( Sal ) From Emp
Group By Deptno, Job ;
Examples of Materialized View with Join / Aggregation :
Sql > CREATE MA TERIALIZE D VIEW Emp_Dept _Sum
ENABLE QUE RY REWRITE

111

Oragle 10 g Material

AS
SELECT Dname, Job, Sum ( Sal )
From Emp E , Dept D
Where E.Deptno = D.Deptno
Group By Dname, Job ;

Creating Optimizer Statistics and Refreshing Materialized View :


Sql > EXECUTE DBMS_UTILITY.ANA LYSE_SCHEMA ( SCOTT , ESTIMA TE ) ;
Sql > EXECUTE DBMS_MV IEW.REFRESH ( Emp_Dept_S um ) ;
Testing the Materialized Views :
Sql > SET AUTOTRA CE ON E XPLA IN
Sql > SELECT Dname, Job, Sum ( Sal ) From Emp E, Dept D
Where E.Deptno = D.Deptno
Group By Dname, Job ;
Putting the Things with RollUp :
Sql > Create Materialized View Emp_Dept_Agg
ENABLE QUE RY REWRITE
AS
SELECT Deptno, Jon, Count ( * ) , Sum ( Sal )
From Emp
Group By RollUp ( Dept no, Job ) ;
GROUPING_ID ( ) FUNCTION :
The function is used to FILTE R ROWS using a HAV ING Clause to exclude rows that do not
contain a subtot al n total .
The Function accepts one or more columns and returns the decimal equivalent of the
GROUP ING bit vertor.
The GROUPING bit vector is computed by combining the results of a call to the GROUPING( )
function for each column in order.
COMP UTING THE GROUPING BIT VECTORS :
GROUP ING ( ) Function returns 1 when the column value is NULL, else returns 0 Based on
this.
GROUP ING_ID ( ) returns 0 , when Deptno and Job are NOT NULLs
GROUP ING_ID ( ) returns 1 , if Deptno is NOT NULL and Job is NULL.
GROUP ING_ID ( ) returns 2 , if Deptno is NULL and Job is NOT NULL
GROUP ING_ID ( ) returns 3 , if Deptno is NULL and Job is NULL.
Sql > Select Deptno , Job
Grouping(Deptno) GDP T,
Grouping (Job ) GJOB ,
Grouping_ID ( Deptno, Job ) GRP ID,
Sum ( Sal )
From Emp
Group By Cube ( Deptno , Job ) ;

112

Oragle 10 g Material

GROUPING_ID ( ) and HAVING Clause :


Sql > Select Deptno, Job
Grouping_ID ( Deptno, Job ) GRP ID,
Sum ( Sal )
From Emp
Group By Cube ( Deptno , Job )
Having Grouping_ID ( Deptno, Job ) > 0 ;

Representing Column Multiple Times in a Group By Clause :


A Column can be represented multiple times in a Group By Clause .

Sql > Select Deptno , Job , Sum ( Sal ) From Emp


Group Deptno , RollUp ( Deptno, Job ) ;

Applying GROUP_ID Function :


The GROUP_ID ( ) Function is used to remove the deplicate rows returned by GROUP BY
Claus e.
The GROUP_ID ( ) does not accept any parameters.
If n duplicate exist for a particular grouping, GROUP_ID ( ) returns numbers in the range 0 to n
1.
Sql >

Select Deptno, Job, GROUP _ID( ) , Sum ( Sal ) From Emp


Group By Deptno, RollUp ( Deptno, Job ) ;

Sql > Select Deptno, Job, GROUP_ID ( ) , Sum ( Sal ) From Emp
Group By Deptno, RollUp ( Deptno, Job )
Having GROUP _ID ( ) = 0 ;
ANALYTIC FUNCTIONS :
The Built in Analytic Functions enable to perform complex calculations.
Analytic Functions Categories :
o

Ranking Functions :
They Enable to calculate Ranks, Percentiles and n-tiles .

Inverser Percentile Functions :


Enable to calculate the value corresponding to a Percentile.

Window Functions :
Enable to calculate cumulative and Moving Aggregates.

113

Oragle 10 g Material

Reporting Functions :
Enable to Calcuate area like market Shares.

LAG and LEAD Functions :


Enable to get a value in a row where that row is a cetain number of rows
away from the current row.

First and Last Functions :


Enable to get the first and last values in an ord ered group.

Linear Regression Functions :


Enable to fit an ordinary least squares regression line to a set of
number pairs.

Hypothetical Rank and Distribution Functions :


Enable to calculate the rank and percentile that a new row would have if
a value is inserted into a table.

TEST TABLES :
ITEM TYPES TABLE :
Used to store the names of the Item Types that are stocked by the store.

Sql > Create Table ItemTypes


(
ItemTypeID INTEGE R
Constraint ItemTy pePK PRIMARY KEY,
ItemTName Varchar2 ( 10 )
Constraint ItemTName NOT NULL
) ;
ITEMS TABLE :
Used to store detailed information about the Items to be sold.
Sql > Create Table Item
(
ItemID INTE GER
Constraint ItemIDPK PRIMARY KEY,
ItemTypeID INTEGE R
Constraint ItemTy peFK
Referenc es ItemTypes ( ItemTypeID ) ,
ItemName Varchar2 ( 10 )
Constraint ItemNameNN NOT NULL ,
Description Varchar2( 100 ) ,
Price Number ( 5, 2 )
) ;

114

Oragle 10 g Material

DIVISIONS TABLE :
Used to store different divisions existing.
Sql > Create Table Division
(
Divid Char ( 3 )
Constraint DividPK PRIMA RY KEY,
DivName Varchar2 ( 15 ) NOT NULL
) ;
JOBS TABLE :
Used to store different Job Catogories Existing in the Organization.
Sql > Create Table Jobs
(
JobID Char ( 3 )
Constraint JobIDPK PRIMA RY KEY,
JobName Varchar2 ( 20 )
Constraint JobNameNN NOT NULL
) ;
EMPLOYEES TABLE :
Used to store the details of the Employ ees working in the stores.
Sql > Create Table EmpStores
(
EmpID INTEGE R
Constraint EmpStoresPK PRIMA RY KEY ,
Sal Number ( 6, 0 ) ,
FirstName Varchar2 ( 10 )
Constraint FnameNN NOT NULL ,
LastName Varchar2 ( 20 )
Constraint LnameNN NOT NULL ,
JobID Char ( 3 )
Constraint JobIDFK
Referenc es Jobs ( JobID ) ,
Divid Char ( 3 )
Constraint DivIDFK
Referenc es Division ( Divid )
) ;

ALL SALES TABLE :


Used to store the sum of all sales by specified amount, for a particular YEAR, MONTH, ITEM
TYPE and EMOLOYEE.

115

Oragle 10 g Material

Sql > Create Table AllSales


(
Year INTE GER
Constraint YearNN NOT NULL ,
Month INTE GER
Constraint Mont hNN NOT NULL ,
ItemTypeId INTEGE R
Referenc es ItemTypes ( ItemTypeID ) ,
EmpID INTEGE R
Constraint EmpIDAs
Referenc es EmpStores ( EmpID ) ,
SalAmt Number ( 8, 2 ) ,
Constraint AllSalesPK PRIMARY KEY ( Year, Month,
ItemTypeID, EmpID )
) ;
RANKING FUNCTIONS :
The Different types of Ranking Functins are
1 ) RANK ( ) Function :
*

It returns the rank of items in a group.

RANK ( ) leaves a gap in the sequence of rankings in the event of a tie.

2 ) DENS E_RANK ( ) Function :


*

It returns the rank of items in a group.

DENSE_RA NK ( ) doesnt leave a gap in the sequence of rankings in the vent of


tie.
Sql Select ItemTypeID, Sum ( SaleAmt) ,
RANK ( ) OVE R ( ORDE R BY Sum ( SaleAmt ) DES C ) RA NK ,
DENSE_RA NK ( ) OVER ( ORDER BY Sum ( SaleAmt ) DESC ) DENSE_RA NK
FROM AllSales
Where Year = 2003 AND SaleAmt IS NOT NULL
Group By ItemTypeID
ORDER BY ItemTy peID ;

PARTITION BY CLAUS E :
The Clause is used to divide groups into subgroups.
Sql > Select ItemTypeID, Month, Sum ( SaleAmt ) ,
RANK ( ) OVE R ( PARTITION BY Month ORDER BY Sum ( SaleAmt )
DESC ) RANK
From AllSales
Where Year = 2003 AND SaleAmt IS NOT NULL
GROUP BY ItemTypeID, Mont h
ORDER BY ItemTy peID, Month ;
APPLYI NG ROLLUP, CUBE AND GROUPI NG SETS :
Sql > Select ItemTypeID, Sum ( SaleAmt ) ,

116

Oragle 10 g Material

RANK ( ) OVER ( ORDE R BY Sum ( SaleAmt )


DESC ) RANK
From AllSales
Where Year = 2003
GROUP BY RollUP(ItemTypeID)
ORDER BY ItemTy peID ;
Sql > Select ItemTypeID, EmpID, Sum ( SaleAmt ) ,
RANK ( ) OVER ( ORDE R BY Sum ( SaleAmt )
DESC ) RANK
From AllSales
Where Year = 2003
GROUP BY CUBE (ItemTypeID, EmpID)
ORDER BY ItemTy peID , EmpID ;
Sql > Select ItemTypeID, EmpID, Sum ( SaleAmt ) ,
RANK ( ) OVER ( ORDE R BY Sum ( SaleAmt )
DESC ) RANK
From AllSales
Where Year = 2003
GROUP BY GROUP ING SETS (ItemTy peID, EmpID)
ORDER BY ItemTy peID , EmpID ;
Sql > Select ItemTypeID, Sum ( SaleAmt ) ,
RANK ( ) OVER ( ORDE R BY Sum ( SaleAmt )
DESC ) RANK ,
DENSE_RA NK( ) OVE R ( ORDE R BY Sum ( SaleAmt ) DESC )
DENSE_RA NK
From AllSales
Where Year = 2003
GROUP BY ItemTypeID
ORDER BY ItemTy peID ;
NULLS FIRST AND NULLS LAST CLAUS E :
Sql > Select ItemTypeID, Sum ( SaleAmt ) ,
RANK ( ) OVER ( ORDE R BY Sum ( SaleAmt )
DESC NULL LAS T ) RA NK ,
DENSE_RA NK( ) OVE R ( ORDE R BY Sum ( SaleAmt ) DESC NULLS LAS T )
DENSE_RA NK
From AllSales
Where Year = 2003
GROUP BY ItemTypeID
ORDER BY ItemTy peID ;
CUME _ DIST ( ) Function :
It returns the position of a specified value relative to a group of values.
The function represents the Cumulative distribution of the data.
PERCENT_RANK ( ) Function :
It returns the Percent Rank of a Value relative to a group by Values.
Sql > Select ItemTypeID, Sum ( SaleAmt ) ,
CUME_DIS T( ) OVE R ( ORDER BY Sum ( SaleAmt )
DESC ) Cumulative ,

117

Oragle 10 g Material

PERCE NT_RANK ( ) OVER ( ORDER BY Sum ( SaleAmt ) DESC )


Percent
From AllSales
Where Year = 2003
GROUP BY ItemTypeID
ORDER BY ItemTy peID ;
NTILE ( ) Function :
The NTILE ( Buckets ) is used to calculate n tiles.
Bucket specifies the number of buckets into which groups of rows are placed.

Sql > Select ItemTypeID, Sum ( SaleAmt ) ,


NTILE ( 4 ) OVER ( ORDE R BY Sum ( SaleAmt )
DESC ) AS Ntile
From AllSales
Where Year = 2003 AND SaleAmt IS NOT NULL
GROUP BY ItemTypeID
ORDER BY ItemTy peID ;
ROW_NUMBER ( ) Function :
The Function is used to return a number with each row in a group.
The row number starts at 1.

Sql > Select ItemTypeID, Sum ( SaleAmt ) ,


ROW_NUMBER( ) OVER ( ORDE R BY Sum ( SaleAmt )
DESC ) Row_Number
From AllSales
Where Year = 2003
GROUP BY ItemTypeID
ORDER BY ItemTy peID ;
INVERS E PERCENTAGE Function :
These functions are used to get the value corresponding to a percentile.
The types of INVE RSE percentile functions are
o

PERCENTILE_DIST( ) :

It examines the cumulative distribution values in each group until it finds one that
is greater than or equal to x.

PERCENTILE_CONT( ) :

It examines the percent rank values in each group until it finds one that is greater
than or Equal to x.

Sql > Select PERCENTILE_CONT ( 0. 6 )


WITHIN GROUP ( ORDER BY Sum ( SaleAmt )
DESC Percentile_Cont ,
PERCE NTILE_DIS T ( 0.6 )
WITHIN GROUP ( ORDER BY Sum ( SaleAmt )
DESC Percentile_Dist

118

Oragle 10 g Material

From AllSales
Where Year = 2003
GROUP BY ItemTypeID ;

WINDOW FUNCTI ONS :


The WINDOW Functions are used to calculat e Cumulative Sums and moving averages within a
specified range of rows.
The functions athat can be applied with windows are
SUM ( )

AVG ( )

COUNT ( )

VARI ANCE ( ) STDDEV ( )

FIRST_VALUE ( )

MAX ( )

MIN ( )

LAST_V ALUE ( )

CALCULATING CUMULATIVE S UM :
Sql > Select Month, Sum ( SaleAmt ) Mont hlyAmt ,
Sum ( Sum ( SaleAmt ) ) OVE R
( ORDER BY Mont h
ROWS BETWEEN UNBOUNDE D
PERCE DING A ND CURRE NT ROW )
CumulativeAmount
From AllSales
Where Year = 2003
Group By Month
Order By Month ;
UnBounded Preceding :
o

Specifies that the window starts at the first row of the partition.

UnBounded Following :
o

Specifies that the window starts at the last row of the partition.

Current Row :
o

Specifies that the window begins at the Current Row or Value.

Sql > Select Month, Sum ( SaleAmt ) Mont hlyAmt ,


Sum ( Sum ( SaleAmt ) ) OVE R
( ORDER BY Mont h
ROWS UNB OUNDED
PERCE DING )
CumulativeAmount
From AllSales
Where Year = 2003 AND Month BETWEEN 6 AND 12
Group By Month
Order By Month ;
CALCULATING MOVING AV ERAGES :

119

Oragle 10 g Material

Sql > Select Month, Sum ( SaleAmt ) Mont hlyAmt ,


A vg ( Sum ( SaleAmt ) ) OVER
( ORDER BY Mont h
ROWS BETWEEN 3 A ND CURRE NT ROW )
MovingA verage
From AllSales
Where Year = 2003
Group By Month
Order By Month ;
CALCULATING CENTERED AV ERAGE :
Sql > Select Month, Sum ( SaleAmt ) Mont hAmt, Avg ( Sum ( SaleAmt ) ) OVER
( ORDER BY Mont h Rows BETWEEN 1 P RECE DING A ND 1 FOLLOWING ) MovA vg
From AllSales
Where Year = 2003
GROUP BY Month
ORDER BY Month ;
Di splaying First And Last Row s Using First_Value( ) and Last_Value ( ) :
Sql > Select Month, Sum ( SaleAmt ) Mont hAmt, FIRS T_VALUE ( Sum ( SaleAmt ) ) OVE R
( ORDER BY Mont h Rows BETWEEN 1 P RECE DING A ND 1 FOLLOWI NG )
PRRVMonthAmt ,
LAST_VALUE ( Sum ( SaleAmt ) OVE R
( ORDER BY Mont h Rows BETWEEN 1 P RECE DING A ND 1 FOLLOWING )
NXTMonthAmt
From AllSales
Where Year = 2003
GROUP BY Month
ORDER BY Month ;
Working With REPORTI NG Functions :
The Reporting function can be used to perform calculations across groups and partitions within
groups.
The functions that can be used are .
SUM ( )

AVG ( )

COUNT ( )

VARI ANCE ( )

MAX ( )

MIN ( )
STDDEV ( )

RATIO_TO_REP ORT ( )
Sql > Select Month, ItemTypeID, Sum ( Sum ( SaleAmt ) )
OVER ( PARTITION BY Month ) Tot_Month_Amt ,
Sum ( Sum ( SaleAmt ) )
OVER ( PARTITION BY ItemTypeID ) Tot _Pesd_Ty pe_Amt )
From AllSales
Where Year = 2003 AND Month < = 3
GROUP BY Month, ItemTypeID
ORDER BY Month, ItemTypeID ;

120

Oragle 10 g Material

RATIO_TO_REP ORT ( ) Function :


The function is used to compute the ratio of a value to the sum of a set of values.
Sql > Select Month, ItemTypeID ,
Sum ( SaleAmt ) ItemTy peAmt ,
RA TIO_TO_REPORT ( Sum ( SaleAmt ) )
OVER ( PARTITION BY Month ) ProTypeRatio
From AllSales
WHERE Year = 2003 AND Month < = 3
GROUP BY Month, ItemTypeID
ORDER BY Month, ItemTypeID ;
LAG ( ) and LEAD Functions :
Are used to get a value in a row, where that row is a certain num ber of rows away from the
current row.
FIRST and LAST Functions :
Are used to get the FIRS T and LAS T values in an ordered group, the functions can be used in
combination with all group functions.

Sql > Select Month ,


Sum ( SaleAmt ) MonthAmt ,
Avg ( Sum ( SaleAmt ) , 1 )
OVER ( ORDE R BY Month ) PrevMthAmt ,
LEAD ( Sum ( SaleAmt ) , 1 )

OVER ( ORDER BY Month ) NextMthAmt


From AllSales
WHERE Year = 2003 AND Month < = 3
GROUP BY Month
ORDER BY Month ;
Sql > Select Min ( Month )
KEEP ( DENSE_RA NK FIRS T ORDE R BY Sum ( SaleAmt ) )
LowestSaleMonth
From AllSales
Where Year = 2003
GROUP BY Month
ORDER BY Month ;
UPDATING THE DATA IN A TABLE :
The UP DA TE statement is used to change the existing values in a table or in the base table of
view.
It can be used to UP DA TE the master table of Materialized View.

121

Oragle 10 g Material

PREREQUISITES :
The Table must be in the own Schema.
UPDA TE object privilege should be available.

Syntax :
UPDATE < Table_Name >
SET < Specification >
WHERE Clause ;
Examples :
Sql > UPDATE EMP
SET Comm = NULL
WHERE Job = CLE RK ;

Sql > UPDATE Emp


SET ( Job, Deptno ) = ( Select Job, Dept no
From Emp
Where Empno = 7499 )
Where Empno = 7698 ;

Sql > UPDATE Employee


SET Deptno = ( Select Deptno From Emp
Where Empno = 7788 )
Where Job = ( Select Job From Emp
Where Empno = 7788 ;
Sql > UPDATE Emp
SET Job = MANAGE R , Sal = 2500 ,
Dept no = 10
Where Ename = ALLE N ;
Sql > UPDATE Emp
SET Job = ANALYS T ,
Sal = Sal + 1000
Where Ename = BLAKE ;
Sql > UPDATE Emp E1
SET Deptno = ( Select Deptno From Dept
Where Loc = DALLAS ) ,
( Sal, Comm ) = ( Select 1.1 * A vg ( Sal ) ,
1.5 * Avg ( Comm )
From Emp E2
Where E1. Dept no = E2.Deptno )
Where Dept no IN
( Select Detpno From Dept
Where Loc = NEW YORK OR Loc = BOSTON ) ;
Sql > UPDATE Emp
SET Sal = Sal * 1.10
Where Dept no = ( Select Deptno From Dept

122

Oragle 10 g Material

Where Loc = CHICA GO ) ;

APPLYI NG DEFAULT VALUES :


It is used to UPDA TE a value in a Column with DEFA ULT value set in the Constraints.
Sql > UPDATE Emp

SET Sal = DEFAULT


Where Ename = SMITH ;
Sql > UPDATE Emp
SET Hiredate = DEFAULT
Where Ename = TAYLOR ;
DEFAULT key word i s Introduced from Oracle 9i onwards.

RETURNING CLAUS E :
The returning clause is introduc ed from 10g.
It is used to Return a value from a AGGREGA TE Function.
The Clause can be specified for tables and Materialized Views and for Views with a single base
table.
Restrictions :

Each expression must be a simple expression or a single set Aggregate function.


It cannot be specified for multi table insert.
It cannot be used with parallel DML or with Remote objects.
It cannot be used to Retrieve LONG Types.
It cannot be specified upon a VIEW upon which a INS TEAD OF Trigger is defined.

Example 1 :
Sql > VARIABLE Sumsal Number
Sql > UPDATE Emp Set Sal = Sal * 1.1
Where Dept no = 10
RE TURNING Sum ( Sal ) INTO :SumSal ;
Sql > PRINT SumSal ;
Example 2 :
Sql > VARIABLE Salary NUMBER ;
Sql > VARIABLE DeptNum NUMBER ;
Sql > VARIABLE Name VARCHAR2 ( 10 ) ;
Sql > UPDATE Emp
SET Job = SALES MAN ,

123

Oragle 10 g Material

Sal = Sal + 1000 ,


Deptno = 30
Where Ename = JONES
RE TURNING Sal * 0.25 ,
Deptno, Ename INTO
:Salary, :DeptNum , :Name ;
MERGE :
The MERGE Statement is used to SELECT rows from one or more sources for UP DA TE or
INSE RT into one or more tables.
The MERGE Statement is convenient to Combine multiple operations and avoid multiple
INSE RT, UPDA TE, DE LE TE.
MERGE is a deterministic statement, using which the same row of the target table multiple ti mes
in the same MERGE statement.
Example :
Sql > CREATE table Bonus
(
Empno NUMBE R ,
Bonus NUMBER DEFAULT 100 ) ;
Sql > INSERT INTO Bonus ( Empno )
( SELECT E.Empno From Emp E
Where Job = SALES MAN ) ;
Sql > MERGE INTO Bonus B
USING ( SELE CT Empno, Sal, Deptno From Emp
Where Dept no = 30 ) S
ON ( B.Empno = S.Empno )
WHEN MA TCHED THEN
UPDA TE SE T B.Bonus = B.Bonus + S.Sal * 0.1
DELE TE WHERE ( S.Sal > 4000 )
WHEN NOT MA TCHED THEN
INSE RT ( B.Empno, D.Bonus )
VALUES ( S.Empno, S.Sal * 0.1 )
WHERE ( S.Sal < = 4000 ) ;

Sql > CREATE Table ExamTimeTable


(
ExamName VARCHA R2( 30 ) ,
ExamTime VARCHAR2 ( 6 ) ,
Constraint ExamNamePK PRIMA RY KEY ( ExamName ) ) ;

Sql > INSER INTO ExamTimeTable


( PHYSICAL SCIE NCES , 9:00 AM ) ;
Sql > MERGE INTO ExamTimeTable E1
USING ExamTimeTable E2 ON
( E2.ExamName = E1.ExamName AND
E1.ExamName = PHYSICAL S CIE NCES )
WHEN MA TCHED THEN
UPDA TE SE T E1.ExamTime = 10:30 AM
WHEN NOT MA TCHED THEN
INSE RT ( E1.ExamName, E1.ExamTime )

124

Oragle 10 g Material

VALUES ( PHYSICAL S CIE NCES , 10:30 AM ) ;


Sql > MERGE INTO ExamTimeTable E1
USING ExamTimeTable E2 ON
( E2.ExamName = E1.ExamName AND
E1.ExamName = CHEMICAL S CIE NCES )
WHEN MA TCHED THEN
UPDA TE SE T E1.ExamTime = 12:30 PM
WHEN NOT MA TCHED THEN
INSE RT ( E1.ExamName, E1.ExamTime )
VALUES ( CHEMICAL S CIE NCES , 12:30 PM ) ;
DELETE STATEMENT :
It is used to remove rows from
o
o
o

An Un Partitioned or Partitioned Table.


The Un Partitioned or Partitioned Base Table of a View.
The Un Partitioned or Partitioned cont ainer table of Writable Materialized View.

Prerequisites :
To DELE TE rows from a table, the table must be in the users shema.
To DELE TE rows from a Materialized View, DELE TE Object privilege is a must.
DELE TE any Table system privilege allows to DELE TE rows from any table or table partition or
form the Base Table of any View.
Syntax :
DELETE [ FROM ] < Table_Name >
[ WHERE Condition ] ;
Example :
Sql > DELETE From Emp
Where Ename = SMITH ;
Sql > DELETE From Emp
Where Hiredate > To_Date ( 01-01-1997 , DD-MM-YYYY ) ;
Sql > DELETE From SalGrade ;
Sql > DELETE From Emp
Where Dept no = ( Select Deptno From Dept
Where Dname = SALES ) ;
Sql > DELETE From ( Select * From Emp )
Where Job = SALESMAN AND Comm < 300 ;
USING RETURNING CLAUS E :
Sql > VARIABLE Salary NUMBER ;
Sql > DELETE From Emp

125

Oragle 10 g Material

Where Job = SALESMAN


AND
Hiredate < Sysdate
RE TURNING Sal INTO :Salary ;
Sql > PRINT :Salary ;
TRANS ACTION CONTROL :
Oracle Server ensures Data Consistency based upon transactions.
Trans actions consist of DML statements that make up one consistent change to the data.
TRANS ACTION START and END Ca se s :
A Transaction begins when the first executable SQL statement is encountered.
The Transaction terminates when the following specifications OCCUR.
o
o
o
o
o

A COMMIT or ROLLBACK i s i ssued.


A DDL Statement issued.
A DML Statement issued.
The USER exists the SQL * Plus
Failure of Machine or System crashes.

A DDL Statement or a DCL statement is automatically committed and hence implicitly ends a
transaction.
EXPLICIT TRANS ACTION CONTROL STATEMENTS :
The logic of Transaction can be controlled by using
o

COMMIT :

SAVEP OINT Name :

It ends the current transaction by making all pending data changes permanent.

It marks a SavePoint wit hin the Current Trans action.

ROLLBACK [ TO SAV EP OINT NAME ] :

It ends the Current Transaction by discarding all pending data changes.

STATE OF DATA BEFORE COMMIT OR ROLLBACK :

E very data change made during the transaction is temporary until the transaction is committed.
Data Manipulation operations primarily affect state of the data can be recovered.
The current user can review the results of the data manipulation operation by querying the tables.
Other USERS cannot view the results of the data manipulation operations made by the current
user.
The ORACLE SERVER institutes read consistency to ensure that each USER sees dat a as it
existed at the last COMMIT.
STATE OF THE DATA AFTER COMMIT IS ISSUED :
Data changes are written to the database
The previous state of the data is permanently lost

126

Oragle 10 g Material

All users can view the results of the transaction.


The LOCKS on the affected rows are released
All SAVEPOINTS are erased.
Sql > COMMIT ;

ALTERTING THE TABLE DEFI NITION :


The ALTE R TABLE statement is used to change the Tables Structural Definition.
The ALTE R TABLE statement is used to
o
o
o

ADD a new Column


MODIFY an Existing Column
DEFINE a DEFAULT value for a new Column.

Syntax :
ALTER TABLE < Table_name >
ADD ( ColumnName DataType [ DEFAULT Expr ]
[ , ColumnName DataType ] ) ;
ALTER TABLE < TableName >
MODIFY ( ColumnName Datatype
[ DEFAULT Expr ]
[ , Column Datatype ] ) ;
STATE OF THE DATA AFTER ROLLBACK :

ROLLBACK Statement is used to discard all pending changes.


The Date changes are undone.
The previous state of the data is ret urned
The LOCKS on the affected rows are released.
Sql > ROLLBACK ;

ROLLI NG BACK CHANGES TO A SAV EP OINT :


SAVEPOINT is used to create a marker in the Current trans action.
Using SAVEPOINT the transaction can be discarded up to the marker by usi ng the
o

ROLLBACK

TO

< SAVEPOINT Name > ;

If a second SAVEPOINT is created with the same name as an earlier SAVEPOINT, the Earlier
SAVEPOINT is Deleted.
ADDING A COLUMN TO A TABLE :
The ADD Clause is used to add Columns.

Sql > ALTER TABLE Dept30


ADD ( Job V ARCHAR2 ( 9 ) ) ;
Guidelines for ADDING Column :

127

Oragle 10 g Material

A column can be A DDE D or MODIFIED but cannot be dropped from a table.


We cannot specify the location where the column can appear, it by default becomes the last
column.
If the table contains records, before the column is added, the new column contains NULLs.

MODIFYING A COLUMN :
A column Datatype, size and Default value can be changed.
A change to the Default value affects only subsequent insertions to the table.
Guidelines to MODIFY a Column :
We can Increase the width or precision of a Numeric Column
We can Decrease the width of a column if the column contains only NULL values and if the table
has no rows.
We can change the dat atype if the column cont ains NULLs
We can convert a CHAR column to the VARCHA R2 datatype or convert a VARCHAR2 column to
the CHAR datatype if the column cont ains NULL values or if the Size is not changes.
A change to the default value of a column affects only subsequent insertions to the table.
DROPPING A COLUMN :
A column can be dropped from a table by using the ALTE R TAB LE statement.
The DROP Column Clause is used for this purpose and the feature is enabled from
Oralce 8i Onwards.
Guidelines to DROP a Column :

The column may or may not contain data


Only one column can be dropped at a time.
The table must have atleast one column remaining in it after it is altered.
Once a column is dropped it cannot be recovered.

Sql > ALTER TABLE Dept30


DROP Column Job ;
SET UNUSED OPTION :
The SE T UNUSE D OP TION marks one or more columns as Unused such that they can be
dropped when the damage on system Resources is less ( 8 i ) .
The Response time is faster than the DROP Clause.
Unus ed columns are treated as if the were dropped, even t rough their column data remains in the
tables rows.
After a column has been marked unused, we cannot have access to that column.
The names and types of columns marked unused will not be displayed during a DESCRIBE.
We can add to a table a New Column with the same name as an unused column.

Sql > ALTER TABLE Dept30


SET UNUSED ( Ename ) ;

128

Oragle 10 g Material

DROP UNUS ED COLUMNS OPTION :


This option removes from the table all columns currently marked as unused.
The option is used when we want to reclaim the extra dis k space from unus ed columns in the
table.
If the table does not cont ain unused columns the statement returns with no errors.

Sql > ALTER TABLE Dept30


DROP UNUSED COLUMNS ;

DROPPING A TABLE :
It removes the definition of the Oracle Table.
The Command not only drops the table but the entire Database is lost along wit h the associated
Indexes.
Syntax :
DROP TABLE < Table_Name > ;
Example :
DROP TAB LE Dept30 ;
GUIDELI NES TO DROP TABLE :
The data is totally deleted from the table
Any views and synonyms will remain that are invalid
Any pending transactions are committed.
Only the create of the table is a user with DROP any table privilege can remove a table
The drop table statement once executed is irreversible ..
CHANGING THE NAME OF AN OBJECT :
The rename command can be used to change the name of a
Table
View
Sequence
Synonym
To rename the object we must be the owner of the object

Syntax :
RENAME < old name > TO < new name > ;
Sql > Rename Dept TO Department.
TRUNCATI NG A TABLE :
It is used it remove all rows from a table and to release the storage space used by the specific
table.
The truncate table will not facilitate for rollback

129

Oragle 10 g Material

Syntax :
TRUNCATE TABLE < Table Name > ;
Sq l> TRUNCATE Table Department ;
we must be the owner of the table for truncating
APPLYI NG COMMENTS UPON A TABLE :
The comments command is used to add comments to a table or a column or view etc.
Each comment can be upto 2000 bytes
The data dictionary is which comments are stored are
ALL_COL_COMME NTS
USER_COL_COMMENTS
ALL_TAB _COMMENTS
USER_TAB_COMME NTS
Syntax:
COMMENT ON Table < Table Name > / column < Tablename. Column >
is Text ;
Sql > COMMENT ON Table Emp is the table storing employee information ;

DROPING A COMMENT :
A comment is dropped from the database by setting it to an empty string.
Sql > COMMENT ON Table Emp is ;

ADVANCED TABLE CREATION STRATEGIES :


Creating a table from an existing table
Oracle allows the creation of a new table on_the_fly, depending on a select statement on an
already existing table.

Syntax :
Create Table < Table Name >
As
Select columns
From Table_Name ;
[ Where Condition ] ;
The create table As selectcommand will not work if one of the selected columns use long
data type.
When the new table is described it reveals that it has INHERITED the column definition from
the existing table.
Using this style we can include all columns using Asterisk is a subset of columns from table.
The new table can contain invented columns which are the product of function of the
combination of other columns

130

Oragle 10 g Material

The column definition will adjust to the size necessary to contain the data is the invented
columns.
Sql > Create Table Sampdept as Select * from dept;
Sql > Create Table Sampdept1(Deptid , Deptname , Place) As Select * From Dept;
Sql > Create Table Sampdept2 as Select Deptno ,Dname From Dept;

Creating a table with column definitions and without data :


Sql > Create Table Sampdept3 As Select * From Dept Where 1 = 2 ;

Creating a table without Generating redo log Entrie s :


Redo log ent ries are chronological rec ords of dat abase actions used during dat abase recoveries
The RE DO log entries generating can be avoided by using the NOLOGGING keyword
By circumventing the perform ance of the create table command will improve as less work is
being done
As the new table creation is not being written to the redo log files ,the table will not be re -create
following a database failure
The redo log files are us ed to recover the database

Sql> Create Table SampDept NOLOGGING As Select * From Dept ;


Creating Index-Organized Table :
An index organized table keeps its data stored according to the primary hey column values for
the table
An index organized table stores its data as if the entire table was stored in an index
To create an index organized table the organiz ation index clause of the create table is used
Sql >Create Table Sample (Sampid Number(4),
Sampname Varchar2(20),
Sampdate DA TE,
Constraint SampidSampnamePK
Primary Key(Sampid, Sampname ) )organization index ;
To create a table as an index organized table we must creat e a primary key constraint on it
To minimize the amount of active management of the index table only of the tables data is very
static
An index organized table is most effective when the primary key constitutes a large part of the
tables columns

Working With Partitioned Tables :


Dividing the rows of a single table into multiple parts is called partitioning of a table.
The table that is partitioned is called partitioned table and the parts are called partitions
The partitioning is useful for very large tables

The Important Goals Behind Partitioning Are

131

Oragle 10 g Material

The performanc e of queries against the tables can improve performance


The management of the table becomes easier
As the partitioned table date is stored in multiple parts , it is easier to load and delete data in
partitions than in the large table
The backup and recovery operating can perform better

Sql >Create Table Sampletable(Sampleid Number(4) Primary Key ,


Sampname Varchar2(20),
Sampdate DA TE,
Sampdesc LONG ) ;

Create Partition Table :


Sql > Create Table Sampletablepart(S ampid Number(4) Primary Key ,
Sampname Varchar2(20) ,
Sampdate Date ,
Sampdesc Varchar2( 4000 ) )
PARTITION By RANGE( Sampid )
(PARTITION Sampidpart1
VALUES LESS THAN(5000) ,
PARTITION Sampidpart2
VALUES LESS THAN(1000) ,
PARTITION Sampidpart3
VALUES LESS THA N ( Max value ) ) ;
The maximum value need not be specified fr the last partition, the max value keyword is
specified.
The max value specifies oracle to use the partition to store any data that could not be stored In
the easier partitions
We can create multiple partitions each wit h its qwn upper value defined
The minimum value for the range is implicitly determined by oracle from the definition of the
preceding partition
HAS H PARTITIONS UPON A TABLE :
A hash partition upon a table det ermines the physical placement of data
The physical placement of data is determined by performed a hash function on the values of the
partition key
In hash partition consecutive values of the partition key are not generally stored in the same
partition
Hash partitioning distributes a set of records over a great er set of partitions, decreasing the
likelihood for i/o contention
To create a hash partition we use the partition by hash clause
Format choice
Specify the number of partitions and the table space to use
specify the nam ed partitions
Sq l> Create Table Emptablehash(Empno Number(6)
Constraint Empnopk Primary Key,
Ename Varchar2(30) ,
Job Vachar2(30) ,

132

Oragle 10 g Material

Deptno Number(2) ,
Sal Number(8,2) ,
Constraint Deptnofk_Hash
Foreign Key( Deptno )
Referenc es Dept ( deptno ) )
PARTITION BY HASH( Deptno )
PARTITIONS 10;
Sql > Create Table Empt ablehash ( Empno Number(6)
Constraint Empnopk Primary key,..)
PARTITION BY HAS H(Dept no)
PARTITION 2 S TRORE IN
(Deptnopart1ts , Deptnopart2ts ) ;
WORKI NG WITH LIST PARTITIONING :
In list partitioning we specify oracle all the possible values and designated the partition into which
the corresponding rows should be inserted
Sql>Creat e Table Empsamplelist
(Emp Number(4)
Constraint Empnopk Primary Key,
Ename Varchar2(20) ,
Sal Number(8,3) ,
Hiredate Date ,
Deptno Number(2) ,
Job Varchar2(15) ,
Constraint Deptnofk Foreign Key ( Dept no )
References Dept ( Deptno ) )
PARTITION Jpart1 VALUES (P RESIDE NT,ANALIS T) ,
PARTITION Jpart2 Values(MA NAGE R,SALESMAN,CLECK) ) ;

Generating sub partitions :


sub partitions are partitions of partition
sub partitions can be used to combine the two types of partitions
1. RANGE PARTITIONS
2. HASH PARTITIONS
In very large tables, the Composite Partition strategy is an effective way of separating the data
into manageable and tunable divisions
Sql > Create Table Empsamplesubpart ( Empno Number(6) Primary Key ,
Ename Varc har2(30) ,
Sal number(8,2) ,
Dept no Number(2) ,
Job Varchar2(30) ,
Constraint Deptnofk Foreign Key( Deptno )
References Dept( Deptno ) )
PARTITION BY RANGE (Ename)
SUBPARTITION BY HAS H(Job)
SUBPARTITIONS 5
(PARTITION Namep1 VALUES LESS THA N(M)
PARTITION Namep2 VALUES LESS THAN ( Max value ) ;

133

Oragle 10 g Material

SPLITTING TABLE PARTITIONS :


Sql>Alter Table Sampletablepart SPLIT PA RTITION Sampidpart 3 AT (2000)
INTO (PARTITION Sampidpart3 ,
PARTITION SAMPIDPA RT4 ) ;
Sq l> Alter Table Empsamplelist SPLIT PARTITION Jpart2 Values(SALESMA N) /
INTO(PA RTITION Jsalesman, PARTITION Ssalesman ) ;

Merging table PARTITIONS :


Sql > Alter Table Empsamplelist MERGE PARTITIONS Jpart1,
Jsalesman INTO PARTITION Jpart1 ;
Sql > Alter Table Samplet ablepart MERGE PARTITIONS Sampidpart2 ,
Samplepart3 INTO PARTITION Sampidpart3 ;

Dropping a table PARTITION :


Sql > Alter Table Sampletablepart DROP PARTITION Sampleidpart 3 ;
Sql > Alter Table Empsamplelist DROP PARTITION Jpart1 ;

Creating Indexes upon PARTITIONS :


Once a partitioned table is created ,we have to create an index upon that table
The index may be partitioned according to the same range of values as that were us ed to
partition the table
The indexed partitions can be palced into specific table spaces
Sql > Create Index Empsamplelistinx ON Empsamplelist ( Job ) LOCAL
( PARTITION Jpart1,Jpart2) ;
The local keyword tells oracle to creat e a separate index for each partition on the table
The global keyword tells oracle to create a nonpartitioned index
Local indexes are easier to manage than global indexes
Global index es can perform uniqueness checks faster than local indexes
OBJECT TABLES :
IN an OB JECT TABLE each row is treated as an OB JECT
Each row in an object table has an OID
The OID is assigned by oracle when the row is created.
The rows of an object table can be referenced by other objects with in the database
An object table is created using the create table command
CREATING AN OBJECT :
Syntax :
CREA TE OR REPLA CE TYPE <TYPE NAME> AS OBJECT
( Column Name1 Dat a Type(Size),Column Name n

134

Oragle 10 g Material

Data Type( Size ) ) ;


Sql > CREATE OR REPLA CE TYPE Student AS OBJECT( Studid Number(6) ,
Sname Varchar2(20),
Dob Date ,
Doa Date ,
Fees Number(7,2) ) ;

CREATING AN OBJECT TABLE :


Syntax :
Create Table Table_Name of typename ;
Sql > Create Table Mcastudent Of Student ;
The above statement creates the table mcastudent as an abstract data type
Each row in the object table has an OID value
The rows in object table are referenced as OB JECTS
INSERTING ROWS INTO OBJECT TABLES :
To insert a record into an object table we may use the constructor method of the actual datatype
or directly implement the insert ststement
The normal insert or REGA TIONAL INSE RT is possible only when the table doesnot contain any
nested datatypes
INSERT UNSING CONSTRUCTOR METHOD :
Sql > Insert Into Mcastudent Values (91234,Satish,05-S ep-99,Sysdate,1300 ) ;
INSERT USING WITHOUT CONSTRUCTOR METHOD :
Sql > Insert Into Mcastudent Values(1234,Kumar,07-Oct-98,Sysdate,15000 ) ;
INSERTING RECORDS THROUGH COLUMN REFERENCES :
Sql > Insert Into Mcastudents ( Studid, Studname ) Values ( 1234, Krishna ) ;
UPDATING DATA FROM OBJECT TABLES :
Sql > Update Mcastudent Set Studname = Sriram Where Studid = 1234 ;
DELETING DATA FROM OBJECT TABLES :
Sql > Delete From Mcastudent Where Studid = 1234 ;
Sq l> Delete From Mcastudent ;
SELECTING DATA FROM OBJECT TABLES :
the abstract data types column can be referred as a part of the tables columns

135

Oragle 10 g Material

Sql > Select * From Mcastudent ;


Sql > Select Studid , Studname From Mcastudent ;
Sql > Select Studid , Studname From Mcastudent Where Studid=1234 ;

THE REF FUNCTION :


The ref function allows to reference existing row objects
The OID assigned to each row can be seen by using the REF function
Sql > SELECT REF(A) from Mcastudent A Where Studname = SATIS H ;
The REF(A) value will be different under different system and may be wrapped onto multiple
lines
The REF function takes as its input the alias given to the object table
The REF functions takes can only referenc e row objects ,hence we cannot use REF for
referencing column objects
The column objects can be of
1.
2.
3.

Abstract data types


LOBs
collections

The REF function by itself does not give any useful information
DEREF FUNCTION :
The DE REF function takes a reference value i.e, the OID generated for a reference and return
the value of the row object
Sql > Create Table Studentincharges ( Inchargename Varchar2(30),
Studentincharc ge REF Student ) ;
The StudentIncharge column references the data that is stored elsewhere
The REF function points the StundentInchage column to a row object of the student data type.
As mcastudent is an object table of the student data types the studentIncharge column can point
to the row object within the mcastudent object table
The studentIncharge table can be described as an ordinary table .
Sql > DESC StudentIncharge ;
Seeing full details of the reference
Sql > SET DESCRIBE DEP TH 2 ;
Sql > DESC Student Incharge ;
INSERTING RECORDS INTO REFERENCE TABLES :
To insert rec ords into reference tables we have to use the REF function

136

Oragle 10 g Material

Sql > INSERT INTO Student Incharges SELECT S UBRAMA NYAM SHRMA REF(A )
From Mcastudents A where Name=SA TISH K UMAR ;

IN THE ABOV E CAS E :


1.
2.
3.
4.
5.

The mcastudents table is queried first


The REF function return the OID for the row object selected
THE selected OID is stored in the studentIncharge table as a pointer to thet row object in
the mcastudents object table
The student Incharges actually contains the name of the studentIncharge and a
reference to a row object in the mcastudents table
The REFE RENCE OID can be seem by querying upon the studentIncharge table

Sql > SELECT * FROM studentIncharge ;


The reference value cannot be seem until we use the DE REF function
Sql > SELECT DE REF(X>StudentIncharge) FROM studentIncharge X
WHERE Inc hargeName= SUBRAMA NYAM SHA RMA ;
The parameter for the DE REF function is the column Name of the REF column but not the table
Name.
POINTS TO NOTE :
The query uses a reference to a row object to travel from one table to the second
A join is performing in the background without specifying the join criteria
The object table it self is not mentioned in the query
The name of the object table need not be known to DEREF the values
The entire referenced object is returned not just part of the row
IMPLEMENTING V ALUE FUNCTION :
Sq l> SELECT VALUE (A) FROM Mcastudents A WHERE SNAM = SATISH ;
VALUE FUNCTION :
The VALUE function is useful when debugging RE FERE NCES
The VALUE function allows to query the formatted values directly from the object table
We can select the values from object table without using the DEREF query upo n the
studentIncharges , studentIncharge column
INVALID REFERENCES :
We can DELE TE the object to which a RE FERE NCE points
We can D:ETE a row from mcastudents object table to which studentInc harge record ponts
Sql > DELETE FROM Mcastudents WHERE name=satish kumar ;

137

Oragle 10 g Material

DANGLI NG REF: It is a record which has an OID pointing to a record in an object table for
which the reference record is not existing in the original object table
As oracle generates a OID for the row object which can be referenced by any other row from
other object table when the row object is DELE TED the OID is lost and the oracle doesnt reuse
the OID numbers

Henc e if a new record for SA TIS H KUMA R is inserted this is given a ane OID value ,but the
studentIncharge record still points to the old value
In a relational system the join bet ween two tables in dependent only on the current data
In an OOP system the join is between objects ,hence the fact that two objects having the same
data does not mean they are same

OBJECT VIEWSWITH REFS :


OBJECT views are very important to super impos e oops structures on an exiting relations table
We can create abstract data types and use them within the object view of an existing table
OBJECT view acts as a bridge bet ween the existing relat ional application to object relational
applications
CREATING US ER DEFINED DATA TYP ES AND I NTEGRATI NG THEM TO RELATIONAL TABLES :
RELATIONAL STAGE :
Sql > Create Table Students( Studid Number(6) Constraint Studidpk Primary Key ,
Sname Varc har2(30) ,
Street Varchar2(40) ,
Cityname Varchar2(25) ,
Statename Varchar2(40) ,
Pincode Number(6) ) ;
CREATING ABSTRACT DATA TYP ES :
Sql > Create Or Raplace Type Myaddress As Object ( Street Varchar2(40) ,
Cityname Varchar2(25) ,
Statename Varchar2(40) ,
Pincode number(6) ) ;
Sql > Create Or Replace Type Mystudent As Object(Sanme Varc har2(30)
Saddress Myaddress ) ;
As student table was created without using the Myaddress and Mystudent data types it has to be
accessed via OB JECT V IEWS.
The above principle of accessing data is called as OBJE CT BASED ACCESS
An OBJECT V IEW can be specified upon the abstract data types to apply onto the relational
table
CREATING AN OBJECT VI EW :
Sql > Create Or Replace View Student ov (Studid ,Studdef ) As
Select Studid , Mystudent (Sname ,

138

Oragle 10 g Material

Myaddress (Street , Cityname , Statename, Pincode ) )


FROM students ;
we can access the students table directly as a relational table or via the CONS TRUCTOR
methods for the abstract dat a types

OBJECT VIEWS WITH REFERENCES :


If the students table is relat ed to another table ,then ,object views can be create as a references
between the table
By using the above concept ORACLE uses the existing Primary KEY|Foreign Key relationships
to simulated OIDs for use by REFs between the table.
By Implementing the above concept we can access the table either as RE LA TIONA L TABLE OR
AS OBJECTS
When the table are treat ed as objects we can use the REFs to automatically performs joins
upon the tables using the DE REF function
GENERATI NG OIDS :
We Can Use An Object view to assign OIDs to the records in students table.
OIDs are assigned to records inan OB JE CT TABLE and an OB JECT TAB LE in turn is based on
an ABSTRA CT DA TA TYPES
As first step create an ABS TRA CT DA TA TYPE that has the same structure as the student
Sql > Create Or Replace Type Student Type As Object ( Studid Number(6) ,
Sname VARCHAR2(30) ,Street Varchar2(40) ,
Cityname Varchar2(25), Statename Varchar2(40) ,
Pincode Number( 6 ) ) ;
As the next step create a view based upon the studenttype by assigning OID values to the
records in stundent table
CREATE A REFERENCE TABLE FOR STUDENTS :
Sql > Create Table StudentBooks( Libtranno Number(6), Studid Number(6),
Booktittle Varchar2(50) , Lendingdate Date ,
Constraint LibtreamNoPK Primary Key
(LibTeamNO, Studid) ,
Constraint StudentBooksFK Foreign Key
(Studid) References Students(Studid ) ) ;
Sql > INSERT INTO Students VALUES ( 1000,SA TISH KUMAR,
SHIV BAGH , HYDERABA D, ANDHRA P RADES H , 506001 ) ;
Sql > INSERT INTO StudentBooks VALUES (1000, 2000, THE RMO DYNAMICS, SYSDATE ) ;

Sql > Select * From Tab ;


Tname
TabType
Clustered
-------------------------------------------------------------------------------

139

Oragle 10 g Material

ADMIN
ADMINTABLE
ARTIS T
IMAGE TABLE
THEME
UPLOA D
UPLOA DS
USERS

TABLE
TABLE
TABLE
TABLE
TABLE
TABLE
TABLE
TABLE

Sql > Desc Admin ;


Name
Null?
Type
-------------------------------------------------------------------------------------ADMIN
PASSWORD

VARCHAR2(20)
VARCHAR2(30)

Sql > Desc Artist ;


Name
Null?
Type
----------------------------------------------------------------------------------------ARTIS TID
ARTIS TNAME
PASSWORD
INTA REA
E XPERIENCE
CLASSNAME
HIS TORY
CONTENT

VARCHAR2(20)
VARCHAR2(25)
VARCHAR2(12)
VARCHAR2(15)
VARCHAR2(2)
VARCHAR2(12)
VARCHAR2(255)
VARCHAR2(255)

Sql > Desc Theme ;


Name
Null?
Type
-----------------------------------------------------------------------------------------THEMEID
THEMENAME
CA TEGORY
THEMENOTE

NUMBE R(5)
VARCHAR2(15)
VARCHAR2(10)
VARCHAR2(255)

Sql > Desc Upload ;

Name
Null?
Type
-----------------------------------------------------------------------------------------IMAGE ID
FILE NAME
ARTIS TID
IMAGE NAME
LOCA TION

NUMBE R(5)
VARCHAR2( 30 )
VARCHAR2( 20 )
VARCHAR2( 20 )
NUMBE R( 3 )

140

Oragle 10 g Material

Sql > Desc Users ;


Name
Null?
Type
-----------------------------------------------------------------------------------------USERNAME
PASSWORD
NAME
PHONE
EMAIL
OCCUPA TION
ADDR1
ADDR2
ADDR3
ADDR4

VARCHAR2( 20 )
VARCHAR2( 12 )
VARCHAR2( 25 )
NUMBE R( 10 )
VARCHAR2( 25 )
VARCHAR2( 15 )
VARCHAR2( 20 )
VARCHAR2( 20 )
VARCHAR2( 20 )
VARCHAR2( 20 )

Sql > Select * From Admintable ;


USERID
PWD
------------------------------------------------------Kalyan

Kalyan

Sql > CREATEOR REP LACE VIEW S TUDENTOV OF Student Type


WITH OB JECT IDE NTIFIER (StudID)AS SELECT StudID
Sname, Street, Cityname, Statename, Pincode From Student ;
The first part of the statement tells the databas e to CREA TE a view based on the structure
defined in student Type
The next part of the CREA TE VIEW tells the databas e how to construct OID values for the rows
in students
With the above step the rows of students are now accessible as row OBJE CTS via the
studentOV View
The PID values generat ed for the studentOV rows are called as PKOIDs as they are based
upon students primary key values
The relational tables can accessed as row OB JE CTS if OB JECT Views are created upon them
GENERATI NG REFERENCES :
Actually the rows of studentBooks reference rows in students
As per relational concept the relationship is determined by the foreign key pointing from the
STUDE NTBOOKS.StudID column to the STUDENT>StudID column

141

Oragle 10 g Material

From the studentov OB JECT View that has been created, and the rows in students table can be
accessed via OIDs we have to CREA TE REFERE NCE VALUES in studentBooks that reference
students
Once the Refs are create we can use DEREF function to Access the students data from student
Books
Sql > CREA TE VIEW StudentBooksov As SELECT MAKE_REF( StudentOv , StudID )
studID, LibTranNo, Book Tittle, LendingDate From StudentBooks ;

MAKE_REF FUNCTION :
It creates REFE RENCES whic h are called PKREFs from an existing view to another view
PKREFs are named so as they are based on PRIMARY KEYS
The function takes as an arguments(s) as the name of the OBJE CT VIEW being REFERE NCE D
and the name of the column or columns that form the FOREIGN KEY in the Local Table
Since MAKE_REF creates a view the result of an operation must be given a COLUMN ALIAS
QUERYI NG THROUGH OBJECT VIEWS :
We use the DEREF function to SELECT the value of the referenced data
The concept is almost all same as that of OBJE CT VIEWS
Sql > SELCT DE REF(SB.StudID) FROM StudentBookOVSB Where
Book Tittle=THERMO DY NAMICS ;
STEPS PERFORMED :
The Query finds the record in the StudentBooks table for which the LendingDate is the Current
System Date .
Taking the studid value from that record evaluates its reference
The evaluated reference studid is pointed to the PKOID value in the studentOv OBJE CT VIEW
using MAKE_RE F.
The StudentOV OB JECT View ret urned the record whose PKOID matched the REFE RENCED
value
The DE REF function then gets activat ed returning the value of the referenced row
The query return rows from students even through the USE R actually queried on StudentBooks
THINGS TO NOTE :
Object views of column objects enable to work with table as if they were both relational tables
and object relational table
When OBJE CT views are extended to row OB JECT they enable to generated OID values based
on established FOREIGN KY| PRIMARY KEY relationship
OBJECT Views allow us to continue to use the existing constraints and standard
INSE RT,DE LE TE UPDA TE and SELE CT statements
They help in using OOP features such as REFERE NCES against the Object TABLES
They provide an Technological Bridge for migrating to an oops db architecture
Oracle performs JOINS that resolve the references defined in the database
When references\d data is retrieved it beings the entire row object that was referenced
To reference the dat a we need to establish POIDs in the table that is PRIMA RI KEY table
relationship
Use MAKE_REF to generat e references in the table that is FORE IGN KEY table relations hip

142

Oragle 10 g Material

Once the above specifications are completed we can work with the data as if it were stored in
OBJECT TAB LES.

143

Oragle 10 g Material

Potrebbero piacerti anche