You are on page 1of 43

Oracle SQL

CONTENTS
CONTENTS................................................................
................................................................................................
...............................................................
............................... ..........................2
........................2
INTRODUCTORY CONCEPTS .............................................................
............................................................. ..................................
............................... ......................3
....................3
THE D ATABASE O BJECTS ................................................................ .................................................................. 3
D ATABASE O BJECT N AMING R ULES ................................
.................................................................................4
D ATATYPES................................................................
........................................................................................4
TH E DATA
DATA DEFINITION COMMA
COMMANDS FOR TABLES ............................... .............................
........................... ..........
...... 8
CREATING A TABLE ................................ ...........................................................................................................8
CONSTRAINTS ON TABLES................................................................ ................................................................. 9
D ROPPING A TABLE ................................ .........................................................................................................12
LTERING A TABLE ................................
ALTERING .........................................................................................................13
SAMPLE TABLES ................................................................
...............................................................................14
TABLES............................ ..................................
QUERYING THE TABLES .............................. ..............................................................15
............................................................15
CONDITIONAL RETRIEVAL OF ROWS ................................ ..............................................................................15
SQL FUNCTIONS..............................................................................................................................................17
G ROUP (OR AGGREGATE ) FUNCTIONS ................................ ...........................................................................17
SINGLE ROW ( OR SCALAR) FUNCTIONS................................ ..........................................................................20
JOINS TO Q UERY MULTIPLE TABLES................................ ...............................................................................27
SET O PERATORS ................................................................
..............................................................................29
N ESTED Q UERIES ............................................................................................................................................30
DATA MAN COMMAND S ............................... ..............................................................
MAN IPULATION COMMAND ............................................................ ........33
..... 33

THE INSERT COMMAND ................................................................


................................................................33
33
THE DELETE COMMAND ................................................................
...............................................................33
33
THE UPDATE COMMAND ................................................................
...............................................................33
33
TH E TRANSA
TRANSACTION COMMAND S ............................... .....................................................35
CTION CONTROL COMMAND ...................................................35

THE COMMIT COMMAND ................................................................


...............................................................35
35
THE ROLLBACK COMMAND ................................ ..........................................................................................35
35
WORKING WITH OBJECTS ............................................................
WITH OTH ER SCHE MA OBJECTS ............................................................ .........................37
.....................37
SEQUENCES................................................................ ...............................................................................
....... ...............
.......37
37
SYNONYMS ................................ ...............................................................................................................
....... ...............
.........38
38
VIEWS................................
...............................................................................................................................3939
INDEXES...........................................................................................................................................................4141
CLUSTERS .........................................................................................................................................................4242
Infosys ORACLE 8i

Introductory Concepts

? SQL (Structured
(Struct ured Query Language) is a standard RDBMS language.
? Oracle SQL is is the set of commands that all pr ograms and users must must use to access
and modify the data within the Oracle Database.
? For executing SQL queries in the user schema, he/she must be granted some type of 
system privi
privileges
leges by DBA.
? The SQL statements can be be broadly classi
classifi
fied
ed into three categ ories:
o Data Definiti
Definition
on Language (DDL) - Used to create, alter, or drop dro p objects
objects (e.g., ta-
bles, indexes, synonym
synonyms, s, views,
views, clusters, etc.) in the database
o Data Manipulation
Manipulation Language (DML) - Used to query, insert insert,, delete and update of 
data stored in the database.
o Data Control Language (DCL) - Used for controll contro llin
ing
g data stored
sto red in the dat abase.

The Database Objects

? The database objects are entities stored


store d in
in the database. These objects may be either
schema
schema objects
objects , or non-schema
non-schema objects
objects .
? Schema objects are objects belonging to a particular schema. A schema is made up of 
a collection of logical structures of data, or schema objects. A schema is owned by a
database user and has the same
same na me as that user (e.g., scott, trng01,
t rng01, etc.). Each
E ach user
owns a single schema.
? SQL is used to create and manipulate the schema objects.
? Some schema objects are listed:
o Clusters
o Database Links
o Database Triggers
o Indexes
o Packages
o Sequences
o Stored Functions
o Stored Procedures
o Synonyms
o Tables
o Views
? Other types of objects
objects are also
also stored in the database and can be
be created and manip
manip u-
lated with SQL, but are not contained in a schema. These are  non-schema objects ,
and some of them are listed blow:
o directories
o profiles
o roles
o rollback segments
o tablespaces
o users

Database Object Naming Rules


? Maximum
Maximum character length
length can be 30 (Except for database names
names which
which are li mited to
8 characters).
? Must not contain a question mark.
? Case insensitive.
insensitive.
? Must begin with an alphabet.
? May only contain the characters a -z, A-Z, 0-9, _, $ and #.
? Must not duplicate
duplicate an Oracle Reserved word.
? Must not duplicate
duplicate another database object belongin
belonging g to that user.

Object Name Valid/Invalid Reason


employee valid
1_test invalid
invalid Begins with a number
check invali
invalid
d ORACLE reserved word
Spp&prts invali
invalid
d Use of “ &” not all
allowed
Pass/fail invali
invalid
d Use of “/” not allowed
allowed

Datatypes

Internal Datatype Description


VARCHAR2(size) Variable length character string having maximum length size
bytes. Maximum size is 4000, and minimum is 1. You must
specify size for a VARCHAR2.
NUMBER(p,s) Number having precision  p and scale s.
LONG Character data of variable
variable length up to 2 gigabytes, or
31
2 -1 bytes.
DATE Valid
Valid date range from January 1, 4712 BC to Dec emberember 31,
4712 AD.
AD. Stores time
time too.
RAW(size) Raw binary data of length size bytes. Maximum size is 2000
bytes. You must specify size for a RAW value. This datatype
datat ype is
used to store binary data.
LONG RAW Raw binary
binary data of variable
variable length
length up to 2 giga
g iga bytes.
Infosys ORACLE 8i

ROWID Hexadecimal string representing the unique address of a


row in its table. This datatype is primarily for values r e-
turned by the ROWID pseudocolumn.
CHAR(size) Fixed length character data of length size bytes. Maximum
size is 2000 bytes. Default and minimum size is 1 byte.
CLOB A character large object containing single byte characters.
Maximum size is 4 gigabytes.
BLOB A binary large object. Maximum size is 4 gigabytes.
BFILE Contains a locator to a large binary file stored ou tside the
database. Enables byte stream I/O access to external
LOBs residing on the database server.

Character Datatypes

? CHAR and VARCHAR2 are the character datatypes that can be used to store and ma-
nipulate text data in a table column.
? CHAR specifies a fixed length character string (e.g., CHAR(10)) for a defined col-
umn. In case you store a string that is smaller than the column length, Oracle blank -
pads the value to the column length.
? The VARCHAR2 specifies the maximum number of bytes of data that it can hold in a
column. Oracle stores each value in the column exactly as specified (without any
blank-padding).

Number Datatype

? The NUMBER datatype is used to store zero, positive and negative f ixed and floating
point numbers.
? You can specify a fixed poi nt number with:
NUMBER(p,s)
? You specify an integer with:
NUMBER (p)
? You specify a floating point number with:
NUMBER

LONG Datatype

? LONG is used to store large text strings, up to 2GB in size.


? There are certain restrictions when you use a LONG column:
o A table cannot contain more than one LONG column.
o LONG columns cannot appear in integrity constraints (except for NULL and NOT
NULL constraints).
o LONG columns cannot be indexed.
o A stored function cannot return a LONG value.
o LONG columns cannot appear in certain parts of SQL statements: WHERE, GROUP
BY, ORDER BY, in SELECT statements, SQL functions such as SUBSTR or
INSTR, expressions or conditions
? Due to such restrictions, it is recommended that you use CLOB datatype to store large
character data instead of the LONG datatype.

DATE Datatype

? The DATE datatype is used to store the date and time information. For each DATE
value the following information is stored:
o century
o year
o month
o day
o hour
o minute
o second
? The function TO_DATE can be used to convert a string (or numeric) value to date for-
mat. This function is discusses later.
? You can get the current date and time using the function SYSDATE (e.g., SELECT
SYSDATE from DUAL;)

RAW and LONG RAW Datatypes

? The RAW and LONG RAW datatypes are used for raw binary data that is not to be
interpreted by Oracle. Examples of such data include pictures, sound, documents, etc.
? LONG RAW data cannot be indexed, but RAW data can be indexed.
? It is recommended that you use BLOB datatype for binary data ins tead of RAW
datatypes.

Large Object (LOB) Datatypes

? The Large Object (LOB) datatypes can store up to 4 GB of unstructured data such as
text, image, video, documents, etc.
? BLOB, CLOB , and BFILE are the three types of LOBs.
? BLOB and CLOB are called inter nal LOBs as they store data within the database.
BFILE is called external LOB as the corresponding data is stored external to the dat a-
base, in the OS files.
? An Oracle-supplied package, DBMS_LOB, is used to work with the LOB data.
? Any number of columns in t able can be of LOB type (unlike the LONG or LONG
RAW types)

ROWID Datatype
Infosys ORACLE 8i

? ROWID (represented as a hex string) represents the address of a ro w in a table in the


database. You can view this address by querying the pseudocolumn ROWID in a table
(e.g., SELECT ROWID FROM emp;).
? An Oracle-supplied package DBMS_ROWID let you interpret the meaning of the hex
address string of the ROWID.
The Data Def inition Commands f or Tables

? Here we look at the DDL commands to work with one of the database objects –
tables.
? Table can be created with the CREATE TABLE command.
? Various integrity co nstraints let you impose restrictions on the data that gets into
the tables, according to the business rules.
? The structure of the table can be altered using the ALTER TABLE comm and. The
same command can be used to add or drop the constraints on the table.
? You can remove a table from the database with the DROP TABLE command.

Creating a Table

Tables are created using the CREATE TABLE command, and owned by the user who cr e-
ates them.
? Syntax

CREATE TABLE table


({column datatype [DEFAULT expr 
]
[constraint]}
[,{column datatype [DEFAULT expr 
]
[constraint]}]...)
[CLUSTER cluster (column [, column] ...)]
[AS query 
]

o DEFAULT specifies a value to be assigned to the column if a row is inserted wit h-


out a value for this column.
o CLUSTER includes this table in the named cluster (this is discusses later in a
separate section)

Example:

CREATE TABLE products


( productno NUMBER(4),
productname VARCHAR2(20),
quantityonhand NUMBER (4));
Infosys ORACLE 8i

Constraints on Tables

? Constraints limit the values entered into the columns of the table , thereby ensuring the
integrity of the data in the database.
? The business rules are translated as constraints on the tables (e.g., each employee
number should be unique, the valid product categories can be A, B, or C only, etc.)
? Depending on the placement of the constraint, a constraint can be termed a column
constraint, or a table constraint:
o a column constraint : Constraint specified as part of the column defin ition:
o a table constraint: Constraint specified towards the end of the CREATE TABLE
statement

Types of Constraints

Constraint Description
NULL | NOT NULL Specifies if a column may or may not support NULL values .
UNIQUE Forces values of a column (or com bination of columns) to be
unique. The unique key made up of a single column can contain
nulls.
PRIMARY KEY Identifies a column (or combination of columns) as a primary
key. A primary key value cannot appear in more than one row
in the table, and it canno t be null either (it is equivalent to
UNIQUE NOT NULL). A table can have only one primary
key.
FOREIGN KEY Also called a referential integrity constraint, designates a co l-
umn (or combination of columns) as a foreign key to a specified
primary or unique ke y, called the referenced key. In this rel a-
tionship, the table contai ning the foreign key is called the child
table and the table co ntaining the referenced key is called the
parent table.
CHECK Specifies a condition that the column (or combination of co l-
umns) must satisfy for the row to exist in the table.

Example 1: NOT NULL constraints

CREATE TABLE products


( productno NUMBER(4) NOT NULL,
productname VARCHAR2(20) CONSTRAINT NNL_pname NOT NULL,
quantityonhand NUMBER (4));

 Named and unnamed constraints :


? In the example above , the first NOT NULL constraint an unnamed constraint,
where as the second NOT NULL constraint is given a nam e NNL_pname. The
unnamed co nstraints will automatically be assigned system generated names (of 
the format SYS_Cxxx where xxx is a unique number) by Oracle.
? Naming the constraints will help manage the constraints better.
? The information about the constrain ts will be stored in the data dictionary table
user_constraints. To view the constraints, issue a query like the one given below:

SELECT TABLE_NAME, CONSTRAINT_NAME, CONSTRAINT_TYPE


FROM USER_CONSTRAINTS
WHERE TABLE_NAME = 'PRODUCTS';

Example 2: UNIQUE constraints

CREATE TABLE dept


(deptno NUMBER(2),
dname VARCHAR2(10) CONSTRAINT unq_dname UNIQUE,
loc VARCHAR2(10)
); /* column constraint */

CREATE TABLE dept


(deptno NUMBER(2),
dname VARCHAR2(10),
loc VARCHAR2(10),
CONSTRAINT unq_dname UNIQUE (dname)
); /* table constraint */

Example 3: PRIMARY KEY constraint

CREATE TABLE dept


(deptno NUMBER(2) CONSTRAINT pk_dept PRIMARY KEY,
dname VARCHAR2(10) CONSTRAINT unq_dname UNIQUE,
loc VARCHAR2(10)
); /* column constraints */

CREATE TABLE dept


(deptno NUMBER(2),
dname VARCHAR2(10),
loc VARCHAR2(10),
CONSTRAINT pk_dept PRIMARY KEY (deptno),
CONSTRAINT unq_dname UNIQUE (dname)
); /* table constraints */
Infosys ORACLE 8i

Example 4: FOREIGN KEY constraint

CREATE TABLE emp


(empno NUMBER(4),
ename VARCHAR2(10),
job VARCHAR2(9),
mgr NUMBER(4),
hiredate DATE DEFAULT SYSDATE,
sal NUMBER(7,2),
comm NUMBER(7,2),
deptno NUMBER(2) CONSTRAINT fk_deptno
REFERENCES dept(deptno),
grade CHAR(1)
); /* column constraint */

CREATE TABLE emp


(empno NUMBER(4),
ename VARCHAR2(10),
job VARCHAR2(9),
mgr NUMBER(4),
hiredate DATE,
sal NUMBER(7,2),
comm NUMBER(7,2),
deptno NUMBER(2),
grade CHAR(1),
CONSTRAINT fk_deptno
FOREIGN KEY (deptno) REFERENCES dept(deptno)
); /* table constraint */

 Note:
? Before you define a referential integrity constraint in the child table, the refe r-
enced UNIQUE or PRIMARY KEY constraint on the parent table must already be
defined . For the example above, dept table should have deptno designated as
PRIMARY KEY already.
? Having a foreign key allows you to maintain referential integrity of your data. For
example, having declared a foreign key deptno in emp table, if you try to insert
a row in table emp with a deptno value 50, this deptno should be present in
the parent table dept already; else the insert fails.
? The ON DELETE CASCADE option with foreign key: You cannot delete the pa r-
ent table row in case there are referencing child table rows. With ON DELETE
CASCADE option, Oracle permits deletions of referenced key values in the pa rent
table and automatically deletes dependent rows in the child table to maintain re f-
erential integrity:
CREATE TABLE emp
(empno NUMBER(4),
ename VARCHAR2(10),
job VARCHAR2(9),
mgr NUMBER(4),
hiredate DATE,
sal NUMBER(7,2),
comm NUMBER(7,2),
deptno NUMBER(2) CONSTRAINT fk_deptno
REFERENCES dept(deptno) ON DELETE CASCADE,
grade CHAR(1)
);

Example 5: CHECK constraints

CREATE TABLE emp


(empno NUMBER(4),
ename VARCHAR2(10),
job VARCHAR2(9) CONSTRAINT chk_job
CHECK (job IN ('CLERK', 'SALESMAN','ANALYST',
'PRESIDENT')),
mgr NUMBER(4),
hiredate DATE,
sal NUMBER(7,2),
comm NUMBER(7,2) CONSTRAINT chk_comm
CHECK (comm BETWEEN 100 AND 1000),
deptno NUMBER(2) CONSTRAINT fk_deptno
REFERENCES dept(deptno) ON DELETE CASCADE,
grade CHAR(1)
CONSTRAINT chk_totsal CHECK (sal + comm <= 6500)
);

Dropping a Table

? DROP TABLE is used to remove a table and all its data from the database .
? When you drop a table, Oracle also drops all the indexes on the table, and invalidates
other dependent objects like views, stored procedures, stored functions, packages,
etc., and these invalid objects can not be used.
? Syntax:
DROP TABLE table
 _name CASCADE CONSTRAINTS;
Infosys ORACLE 8i

Examples:

DROP TABLE emp;


DROP TABLE dept CASCADE CONSTRAINTS;

 Note: CASCADE CONSTRAINTSallows you to drop a parent table that has referenc-
ing child table. Without this option, if such referential integrity constraints exist, Oracle
returns an error message and does not drop the table.

 Altering a Table

? You can alter the definition of a table for:


o adding a column
o dropping a column
o adding an integrity constraint
o dropping an integrity constraint or trigger
o modifying/ redefining a column (datatype, size, default value)
? Syntax:

ALTER TABLE table


{ [ADD ( { column_element | constraint }
[, column_element | constraint }] ... )]
[ DROP COLUMN column ]
[ MODIFY (column_element | constraint
[, column_element | constraint] ... )]
[ DROP drop]...

 Note:
? ADD allows you to add a new column to table, or add a constraint to the table’s defin i-
tion.
? DROP allows you to remove a column .
? The drop clause is used to remove an integrity constraint or trigger from the dat a-
base.
? You cannot use MODIFY option:
o To reduce the width of a column unless all the columns are empty.
o To change the data type unless the column is empty.
o To make it NOT NULL unless all rows have values in that column.
? The only type of integrity constraint that you can add to a n existing column using the
MODIFY clause with the column constraint syntax is a NOT NULL constraint. For all
other constraints use ADD clause to add the constraint.
Examples:

ALTER TABLE emp DROP COLUMN grade;

ALTER TABLE emp ADD (grade CHAR(1));

ALTER TABLE emp MODIFY (job NOT NULL);

ALTER TABLE emp MODIFY (sal NUMBER(8,2));

ALTER TABLE emp ADD CONSTRAINT pk_emp PRIMARY KEY (empno);

ALTER TABLE emp ADD CONSTRAINT fk_emp


FOREIGN KEY (deptno) REFERENCES dept(dept no);

ALTER TABLE emp1 DROP CONSTRAINT pk_emp;

ALTER TABLE emp1 MODIFY (hiredate DEFAULT SYSDATE);

Sample Tables

The emp and dept tables that we have used in many examples are sample tables from
Oracle, and look like:

EMP Table
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7369 SMITH CLERK 7902 17-DEC-80 800 20
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7566 JONES MANAGER 7839 02-APR-81 2975 20
7654 MARTIN SALESMAN 7698 28-SEP- 81 1250 1400 30
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7788 SCOTT ANALYST 7566 09-DEC-82 3000 20
7839 KING PRESIDENT 17-NOV-81 5000 10
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7876 ADAMS CLERK 7788 12-JAN-83 1100 20
7900 JAMES CLERK 7698 03-DEC-81 950 30
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7934 MILLER CLERK 7782 23-JAN-82 1300 10

DEPT Table
DEPTNO DNAME LOC
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
Infosys ORACLE 8i

Querying the Tables

? The SELECT DML command is used to query the contents of a table.


? Syntax:

SELECT * | [DISTINCT] column [, column]...


FROM table [, table]...
[WHERE condition]
[GROUP BY column [, column]...]
[HAVING condition]
[ORDEY BY expr 
];

? The WHERE clause is used to conditionally retrieve the rows from the table(s)
? The ORDER BY clause is used to get the data in the sorted order
? The GROUP BY and HAVING clauses are used to group together rows and get the
aggregate results

Examples

To display the information of all employees

SELECT * FROM emp;

To list employee names and their departments

SELECT ename, deptno FROM emp;

To get the unique values of department numbers in the emp table

SELECT DISTINCT deptno FROM emp;

To List different job titles available in emp table

SELECT DISTINCT job FROM emp;

Conditional Retrieval of Rows

? The WHERE clause in the query is used for conditional retrieval of rows
? Operators used to specify the conditions in WHERE clause:
Relational (Comparison) oper ators =, >, <, >=, <=, <> , !=
Logical operators   AND , OR , NOT
Special operators IS [NOT] NULL, IN, BETWEEN, LIKE

? The IS NULL and IS NOT NULL operators are used in comparing nulls.
? The LIKE operator is used for checking partial equality conditions with
LIKE 'pattern' – the pattern can contain the wildcard characters % (indicates
any sequence of zero or more chara cters), and _ (underscore, for single character) .
? You can select expressions from a table .
? You can provide aliases for viewing data. Alias names are displayed in place of actual
column nam es. Alias names are given to the right of a column name, enclosed within
quotes. (e.g., SELECT ename "Employee Name", sal + 100 "Increased Salary"
FROM emp;)

Examples

To list the employees belonging to the department 10

SELECT * FROM emp WHERE deptno = 30;

To list the name and salary of the employees whose salary is more than 1500

SELECT ename, sal


FROM emp
WHERE sal > 1500
ORDER BY ename;

To list all the managers in department 20

SELECT * FROM emp WHERE job='MANAGER' AND deptno=20;

To list emp loyee details whose salary is between 1000 and 2000

SELECT * FROM emp


WHERE sal >= 1000 AND sal <=2000
ORDER BY sal DESC;

SELECT * FROM emp


WHERE sal BETWEEN 1000 AND 2000
ORDER BY sal DESC;

To list all the clerks in the departments 10 or 20

SELECT * FROM emp


WHERE job='CLERK' AND (deptno = 10 OR deptno = 20)

SELECT * FROM emp


WHERE job='CLERK' AND deptno IN (10, 20)
Infosys ORACLE 8i

To list names of employees who are not salesmen

SELECT ename FROM emp


WHERE job <> ‘SALESMAN’;

To list employees who are not gett ing any commission

SELECT ename FROM emp


WHERE comm IS NULL;

To list employees belonging to some dept

SELECT ename FROM emp


WHERE deptno IS NOT NULL;

To list the employees whose names start with ‘A’

SELECT ename FROM emp WHERE ename LIKE ‘A%’;

To list employee names having ‘I’ as the second character, and end character as 'S'

SELECT ename FROM emp WHERE ename LIKE ‘_I%A’;

SQL Functions

? There are several standard functions that Oracle provides to manipulate the data and
return a result.
? There are two types of SQL functions:
o Scalar (single row) functions – act on a single row at a time, returns a
single result row for every row of a queried table or view ; used for ma-
nipulating data values
o Group (aggregate) functions – acts on a group of rows, returns a single
result row for a group of queried rows; used for summarizing data

Group (or Aggregate) Functions

? Group functions are utilized for summarizing data from a set of rows or from the en-
tire table.
? The group functions produce a single value for an entire group or table. In all group
functions NULLs are ignored.
? The group functions supported by standard SQL are:
Group Function Description
SUM([DISTINCT| ALL] n) returns the sum of values of n
MAX([DISTINCT|ALL] n) returns the maximum value of n
  MIN([DISTINCT|ALL] n) returns the minimum value of n
 AVG([DISTINCT|ALL] n) returns the average value of n
COUNT({* | [DISTINCT |ALL] n}) returns the number of rows in a query

Examples

To list the total number of employees in the emp table

SELECT COUNT(*) FROM emp;

COUNT(*)
----------
9

To get the total salary paid to the employees

SELECT SUM(sal) as Total


FROM emp;

TOTAL
----------
23625

To list the number of jobs available in the emp table

SELECT COUNT(DISTINCT job) "tot jobs" FROM emp;

tot jobs
----------
4

To select the maximum salary paid to all the employees

SELECT MAX(sal) Maximum FROM emp;

MAXIMUM
----------
5000

To list the maximum salary of employee working as a clerk 

SELECT MAX(sal) FROM emp WHERE job = ‘CLERK’;

MAX(SAL)
----------
1400
Infosys ORACLE 8i

To list the average salary and number of employees working in dept 20

SELECT AVG(sal), COUNT(*) FROM emp


WHERE deptno = 20;

AVG(SAL) COUNT(*)
---------- ----------
3518.75 4

GROUP BY Clause

? GROUP BY clause groups the rows using a specified column.


? This column induces a co ntrol break using the specified field as the control field.
? The group functions can be used on the individual groups to summarize the data.
? Conditional retrieval of rows from a grouped result is possible with the HAVING
clause. The HAVING clause filters the rows returned by the GROUP BY clause.

Examples

To list the minimum salaries in each of the departments

SELECT deptno "Department", min(sal) "Min Sal" FROM emp


GROUP BY deptno;

Department Min Sal


---------- ----------
10 1400
20 1100
30 1250

To list the number of employees working with each job title

SELECT job "Job", COUNT(*) "Employees " FROM emp


GROUP BY job;

Job Employees
--------- ----------
ANALYST 2
CLERK 2
MANAGER 3
SALESMAN 2

To list the departments and the total salaries payable in each department

SELECT deptno "Department", SUM(sal) "Total Salary" FROM emp GROUP


by deptno;

Department Total Salary


---------- ------------
10 3950
20 14075
30 5600

To list those departments which have more than 2 employees

SELECT deptno "Dept", COUNT(*) "Employees"


FROM emp
GROUP BY deptno
HAVING COUNT(*) >2;

Dept Employees
---------- ----------
20 4
30 3

 Note: The selected columns in the query (involving a GROUP BY clause) must form the
list of columns spe cified in the GROUP BY clause or should be group functions.

Single Row ( or Scalar) Functions

N u m b e r F u n c t io n s

ABS(value) POWER(value, exponent)


CEIL(value) ROUND(value, precision)
COS(value) SIGN(value)
COSH(value) SIN(value)
EXP(value) SINH(value)
FLOOR(value) SQRT(value)
LN(value) TAN(value)
LOG(value) TANH(value)
MOD(value) TRUNC(value, precision)

Examples: Number Functions

SELECT ABS(-15) “Absolute” SELECT CEIL(15.7) “Ceiling”


FROM DUAL; FROM DUAL;
Absolute Ceiling
---------- ----------
15 16
SELECT FLOOR(15.7) “Floor” SELECT MOD(11,4) FROM DUAL;
FROM DUAL; MOD(11,4)
Floor ----------
---------- 3
15
SELECT POWER(3,2) “Raised” SELECT ROUND(15.193,1) “Round”
FROM DUAL; FROM DUAL;
Raised Round
---------- ----------
9 15.2
Infosys ORACLE 8i

SELECT ROUND(15.193,-1) “Round” SELECT SIGN(-20) “Sign” FROM DUAL;


FROM DUAL; Sign
Round ----------
---------- -1
20
SELECT TRUNC(15.79,1) “Truncate” SELECT TRUNC(15.79,-1) “Truncate”
FROM DUAL; FROM DUAL;
Truncate Truncate
---------- ----------
15.7 10

S t r i n g F u n c t io n s

Function Description
String || String Concatenates two strings
ASCII(string) Returns ASCII value of the character
CHR(integer) Returns character corresponding to the ASCII
integer value
CONCAT(string1, string2) Concatenates two strings
INITCAP(string) Capitalizes the first letter of the string
INSTR(string, Returns an integer indicating the pos ition of the
set[,start[,occurrence]])
character in string that is the first character of 
this occurrence
LENGTH(string) Returns the length of the string
LOWER(string) Converts all characters to lower case
LPAD(string, n[,’set’]) Returns string right-padded to length n with the
sequence of characters in set
LTRIM(string[,’set’]) Removes characters from the left of  sring  , with
all the leftmost characters that appear in set re-
moved
RPAD(string, n[,’set’]) Returns string left-padded to length n with the
sequence of characters in set
RTRIM(string[,’set’]) Removes characters from the right of  sring  ,
with all the leftmost characters that appear in set
removed
SOUNDEX(string) Returns a string containing the phonetic repr e-
sentation of string . This function allows you to
compare words that are spelled d ifferently, but
sound alike in English.
SUBSTR(string, start[, count]) Returns the count characters starting from start 
in the string
UPPER(string) Converts all characters to upper case
Examples : String Functions

SELECT ename || ', ' || job SELECT ASCII(‘A’), ASCII(‘B’)


FROM emp FROM DUAL;
WHERE deptno=10;
ASCII('A') ASCII('B')
ENAME||','||JOB ---------- ----------
--------------------- 65 66
CLARK, MANAGER
MILLER, CLERK
SELECT LOWER(ename)"Lower", SELECT ename, LENGTH(ename)
UPPER(ename) "Upper", FROM emp
INITCAP(LOWER(ename)) "Initcap" WHERE deptno=20;
FROM emp WHERE deptno=20;
ENAME LENGTH(ENAME)
Lower Upper Initcap ---------- -------------
---------- ---------- ---------- JONES 5
jones JONES Jones SCOTT 5
scott SCOTT Scott ADAMS 5
adams ADAMS Adams FORD 4
ford FORD Ford
SELECT RPAD(ename, 20, '.'), deptno SELECT LPAD(ename, 15), sal
FROM emp WHERE deptno=20; FROM emp WHERE deptno=20;

RPAD(ENAME,20,'.') DEPTNO LPAD(ENAME,15) SAL


-------------------- ---------- --------------- ----------
JONES............... 20 JONES 2975
SCOTT............... 20 SCOTT 5000
ADAMS............... 20 ADAMS 1100
FORD................ 20 FORD 5000
SELECT SUBSTR(hiredate, 4) SELECT ename, INSTR(ename, 'I')
FROM emp WHERE deptno=10; "I Posn." FROM emp WHERE deptno=10;

SUBSTR ENAME I Posn.


------ ---------- ----------
JUN-81 CLARK 0
JAN-82 MILLER 2
SELECT loc FROM dept WHERE SOUNDEX(loc)=SOUNDEX('Sidney');
--both Sidney and Sydney would match

G e n e r a l Fu n c t i o n s

Function Description
GREATEST (expr [,expr]…) Returns the greatest of the list of expre ssions. The
expression can be numeric, character, or date.
LEAST (expr [,expr]…) Returns the least of the list of expressions . The ex-
pression can be numeric, character, or date.
NVL (expr1, expr2) If expr1 is null, returns expr2; if expr1 is not null,
returns expr1
DECODE (value, if1, then1 If the value is if1 then the result of the DECODE is
[, if2, then2]... else)
then1; if it is if2 then the result is then2, and so on; if 
the value equals none of the ifs, then the result is else
Infosys ORACLE 8i

Examples: General Functions

SELECT LEAST ('HARRY', 'HARRIOT', 'HAROLD') "Least" FROM DUAL;

Least
------
HAROLD

SELECT GREATEST (23, 645, 123) "Greatest" FROM DUAL;

Greatest
----------
645

SELECT ename, sal + comm "totsal", sal + NVL(comm, 0) "to


tsal"
FROM emp WHERE deptno=30;

ENAME totsal totsal


---------- ---------- ----------
WARD 1750 1750
BLAKE 2850
TURNER 1500 1500

SELECT ename, NVL(TO_CHAR(comm), 'No Commission') "COMMISSION"


FROM emp WHERE deptno = 30;

ENAME COMMISSION
---------- ---------------------
WARD 500
BLAKE No Commission
TURNER 0

SELECT ename, DECODE(comm, null, 'NOT Eligible',


0, 'Eligible, but 0', comm) "Commission"
FROM emp WHERE deptno=30;

ENAME Commission
---------- ------------------------
WARD 500
BLAKE NOT Eligible
TURNER Eligible, but 0

SELECT ename, DECODE(deptno, 10, 'ACCOUNTING',


20, 'RESEARCH',
30, 'SALES',
40, 'OPERATION', 'NONE') "Department"
FROM emp WHERE job='CLERK';

ENAME Department
---------- ----------
ADAMS RESEARCH
MILLER ACCOUNTING
Date Functions

Function Description
ADD_MONTHS(date,n) Adds n months to the date
LAST_DAY(date) Returns the date of the last day of the month that
contains date
MONTHS_BETWEEN(date1, date2) Returns number of months between dates date1
and date2
NEXT_DAY(date, ‘day’) Returns the date of the first weekday named by
day that is later than the date date
TO_CHAR(date, ‘format’) Converts date of DATE datatype to a value of 
VARCHAR2 datatype in the format specified by the
date format format. If you omit format, date is
converted to a VARCHAR2 value in the default date
format.
TO_DATE(string, ‘format’) Converts string of CHAR or VARCHAR2 datatype
to a value of DATE datatype, in the date format
specified by format. If you omit format, string 
must be in the default date format.

 Date Formats (With both TO_CHAR and TO_DATE)

Format  Description
Example/ 
MM 12
RM XII
MON DEC
MONTH DECEMBER
DDD 354
DD 23
D 6 (day of the week, where Sunday is 1)
DY FRI
DAY FRIDAY
YYYY 1982
SYYYY -1000
YYY 982
YY 82
Y 2
YEAR NINETEEN-FORTY-SIX
Q 3 (Number of quarter)
WW 46
W 3
J Julian days since Dec 31, 4713 BC 
HH 11
HH12 Same as HH 
HH24 17
MI 58
SS 43
Infosys ORACLE 8i

SSSS 43000 (0-83699)


/ , - : . Punctuation for TO_CHAR
A.M
P.M
AM or PM
B.C
A.D
BC or AD

 Date Formats (Only with TO_CHAR)

Format  Description
Example/ 
“string” “is”
fm Suppresses padding of Month or Day in format
TH DdTH or DDTH gives: 24th or 24TH
SP DDSP, DdSP, or ddSP gives: THREE, Three, or three
SPTH DdSPTH gives: Third
THSP Same as SPTH 

Examples : Date Functions

To get current date

SELECT SYSDATE FROM Dual;

SYSDATE
---------
12-DEC-02
To get a date 5 months back 

SELECT SYSDATE "Today", ADD_MONTHS(SYSDATE, -5) "Result" FROM DUAL;

Today Result
--------- ---------
12-DEC-02 12-JUL-02
To get the date of next Friday

SELECT SYSDATE, NEXT_DAY(SYSDATE, 'THURSDAY') FROM DUAL;

SYSDATE NEXT_DAY
--------- ---------
12-DEC-02 19-DEC-02
To get the last of the month

SELECT SYSDATE "Today", LAST_DAY(SYSDATE) "MonthEnd" FROM DUAL;

Today Month End


--------- ---------
12-DEC-02 31-DEC-02
To get a date that is 1st of the month 6 months from now
SELECT SYSDATE TODAY, LAST_DAY(ADD_MONTHS(SYSDATE, 6))+1"REVIEW ON"
FROM DUAL;

TODAY REVIEW ON
--------- ---------
12-DEC-02 01-JUL-03
To get years of experience of employees in department 20

SELECT ename "Name", hiredate "Joined",


ROUND(MONTHS_BETWEEN(SYSDATE, hiredate)/12) "Experience"
FROM emp WHERE deptno=20;

Name Joined Experience


---------- --------- ----------
JONES 02-APR-81 22
SCOTT 19-APR-87 16
ADAMS 23-MAY-87 16
FORD 03-DEC-81 21
To get the dates in words

SELECT hiredate, TO_CHAR(hiredate,'DD, Month, Year' ) "In Words"


FROM emp WHERE deptno=10;

HIREDATE In Words
--------- ----------------------------------
09-JUN-81 09, June , Nineteen Eighty-One
23-JAN-82 23, January , Nineteen Eighty-Two

SELECT hiredate, TO_CHAR(hiredate, 'fmMonth, ddTH, YYYY') "In Words"


FROM emp WHERE deptno=10;

HIREDATE In Words
--------- ---------------------
09-JUN-81 June, 9th, 1981
23-JAN-82 January, 23rd, 1982
To get the current time

SELECT TO_CHAR(SYSDATE, 'HH:MI:SS') "Time Now" FROM DUAL;

Time Now
--------
12:20:08
To get the day name of a particular date

SELECT TO_DATE('29-Aug-68') "Date",


TO_CHAR(TO_DATE('29-Aug-68'), 'DAY') "D ay" FROM DUAL;

Date Day
--------- ---------
29-AUG-68 THURSDAY
Infosys ORACLE 8i

Joins to Query Multiple Tables

? Joins are powerful relational operators that combine data from multiple tables into a
single result table.
? There are different types of joins :
o Cartesian Joins
o Equi Joins
o Self Joins
o Outer Joins

Cartesian Joins

? In this join the tables are joined without any WHERE clause ; each row of one table
matches every row of the other table.
? It is also known as Natural Join.
? Examples:

SELECT supp_name, po_status


FROM suppliertab, orderfile;

/* List all the information about the departments and


courses offered by them */

SELECT *
FROM department, course;

Equi Joins

? When two tables are joined together using equality of values in one or more columns
they make an equi join.
? Table prefixes are used to prevent ambiguity and the where clause is used to specify
which columns are to be joined.
? Example:

/* List the lecturers' name and their department name */

SELECT lecturer.c_Lect_Name, department.c_Dept_Name


FROM lecturer, department
WHERE lecturer.i_Dept_No = department.i_Dept_No
ORDER BY lecturer.i_Dept_No;
Outer Joins

? When two tables are joined, only those that satisfy the given criteria are retrieved by
the query.
? If the user wants to check which were the rows that did not have a corresponding
match and still view the data with N ULL values outer joins are made use of.
? Examples:

/* List suppliers and their order status (also list the supplier who have
not placed the orders */
SELECT supp_name, po_num, po_status
FROM suppliertab, orderfile
WHERE orderfile.supp_code(+)= suppliertab.supp_code;

 Note:
? In the above example , the (+) is placed on the side of the table whose co lumns
do not have a corresponding match in the other table.
? Also note that you cannot have (+) o perator for both the joined tables.

/* List the lecturers name and their department’s name (list those d e-
partment also which does not have any employee */

SELECT lecturer.c_Lect_Name, department.c_Dept_Name


FROM lecturer, department
WHERE lecturer.i_Dept_No =(+) department.i_Dept_No
ORDER BY lecturer.i_Dept_No;

Self Joins

? When one row of a table is joined with another of the same table you perform a SELF
JOIN.
? Example:

/* List the name of each employee along with his/her manager from
emp table */

SELECT worker.ename, manager.ename


FROM emp worker, emp manager
WHERE worker.mgr = manager.empno;

In the above example, since both the employee and his/her manager are part of the same
table a self joi n is made use of.
Infosys ORACLE 8i

 Note: To distinguish the columns of the copy of the same table , table aliases are used. In
JOINS when the table name has to be written to specify columns more than once then it
is better to use aliases in place of writing big table name s.

Set Operators

? Set operators combine 2 or more queries into a single result. The data type of the
corresponding columns must be the same.
? The different set operators:
o UNION
o INTERSECT
o MINUS

UNION

? This operator is useful when it is required to draw info rmation from more than one
table that have the same structure.
? It returns rows of the first query plus the rows of the second query after eliminating
duplicate rows.
? Example:

/* List the employees from account and research tables whose salary is
greater than 2000 */
SELECT ename, sal
FROM account
WHERE sal > 2000

UNION

SELECT ename , sal


FROM research
WHERE sal > 2000;

INTERSECT

? INTERSECT returns only those rows that are common to bo th queries.


? Example:
/* List the jobs that are common in research, accounts and sales d e-
partment */
SELECT job FROM research

INTERSECT

SELECT job FROM accounts

INTERSECT

SELECT job FROM sales;

 MINUS

? MINUS returns rows that are unique to the first query.


? Example:

/* List the jobs which are done in accounts only and not in sales */

SELECT job FROM account

MINUS

SELECT job FROM sales;

Nested Queries

? In this type of query the result of one query is dynamically substituted in the cond i-
tion (WHERE clause) of another query.
? In nested queries, the sub query within the WHERE clause is evaluated first. The r eturn
value is then substituted in the condition of the outer query.
? Oracle supports infinite level of nesting.
? The general syntax for a nested or sub query is :

SELECT col1 [, col2]...


FROM table1
WHERE column operator (SELECT column
FROM table2
WHERE condition);
Infosys ORACLE 8i

? Examples:

/* To list the names of employees drawing the highest salary */ 

SELECT ename, sal FROM emp


WHERE sal = (SELECT MAX (sal) FROM emp);

ENAME SAL
---------- ----------
SCOTT 5000
FORD 5000

 Note: When using relational operators with subqueries, ensure that the sub query returns
a single row output. For comparison with a set of rows returned by the subquery, use the
IN operator.

/* To list all the managers in the emp table who have more
than 1 person reporting to him/her */ 

SELECT empno FROM emp


WHERE empno IN
(SELECT mgr FROM emp
GROUP BY mgr HAVING COUNT(*) > 1);

EMPNO
----------
7566
7698

Correlated Subqueries

? SQL sub queries that perform the subquery over and over again, once for each row of 
the outer query are called correlated subqueries.
? Example:

/* List all items whos e quantity is greater than the average transaction qua ntity
for that item */ 

SELECT item_code, trans_qty


FROM trans_file tfile
WHERE trans_qty > ( SELECT AVG(trans_qty)
FROM trans_file
WHERE tfile.item_code = trans_file.item_code)
ORDER BY item_code;
 Note: While referring to the outer query , alias is mandatory in the inner query.

Using the EXISTS operator in subqueries

? EXISTS is a special operator that returns TRUE if a subquery returns at least one
row.
? Examples:

 /* To list the employee details only if more than 3 employees are present in
dept 20 */ 

SELECT * FROM emp


WHERE deptno = 20 AND EXISTS
(SELECT COUNT(*)
FROM emp WHERE deptno = 20
GROUP BY deptno
HAVING COUNT (*) > 3 );

 /* To list out the department details in which there are any employees */ 

SELECT dname, deptno FROM dept


WHERE EXISTS
(SELECT * from emp
WHERE dept.deptno = emp.deptno);

DNAME DEPTNO
-------------------- ----------
Accounting 10
Research 20
Sales 30
Infosys ORACLE 8i

Data Manipulation Commands

The DML commands INSERT, UPDATE, and DELETE are discussed in this section.

The INSERT command

? INSERT statement is used to insert values into the table.


? Syntax:
INSERT INTO table [ ( column [, column ]… ) ]
{ VALUES ( expression [, expression ]… ) | query }

? The INSERT with a VALUES clause inserts a single row into the table
? The INSERT with a query is used to add all the rows returned by a query at once.
? All data types to be included in quote s(' ') , except numeric data types.
? Examples:

INSERT INTO dept VALUES (60, 'Education', ' Boston');

INSERT INTO emp (empno, ename, deptno)


VALUES (8000, 'John', 20);
--rest of the columns will take a null or default value

The DELETE Command

? Using the DELETE statement row (s) can be deleted from a table.
? Syntax:
DELETE FROM table [WHERE condition];

? Examples:

DELETE FROM emp; -- deletes all rows

DELETE FROM emp WHERE empno=8000;

The UPDATE Command

? The UPDATE statement is used to change existing values in a specified table.


? Syntax:

UPDATE table SET


{column = expression [, column = expression]...
| ( column [, column]…) = (subquery ) }
[WHERE condition];

 Note: Update without a WHERE clause will update all the rows in a table.

? Example:

To modify the salary and dep artment number of SMITH

UPDATE emp
SET sal = sal + 100, deptno = 30
WHERE ename = 'SMITH';
Infosys ORACLE 8i

The Transaction Control Commands

? A transaction (or a logical unit of work) is a sequence of SQL statements that Oracle
treats as a single unit.
? The Transaction Control commands manage changes made by insert, update or d e-
lete commands.
? The transaction control commands are:
o COMMIT
o ROLLBACK
? A transaction begins with the first executable SQL statement after a COMMIT,
ROLLBACK or connection to the database. A transaction ends with a COMMIT,
ROLLBACK or disconnection (intentional or unintentional) from the d atabase.

The COMMIT Command

? COMMIT is used to end the current transaction and make permanent all changes done
in the transaction.
? This comma nd also releases the transaction's locks.
? Example:
INSERT INTO dept VALUES (60, 'Education', 'London');
COMMIT;

Upon commit, the inserted row resides permanently in the database .

The ROLLBACK Command

? A ROLLBACK undoes all the changes in the current transaction, and ends the transa c-
tion. It also releases the transaction's locks.
? Example:

DELETE FROM emp;


ROLLBACK;

ROLLBACK with SAVEPOINT

? Using the ROLLBACK command with the TO SAVEPOINT clause performs the fo l-
lowing o perations:
o Rolls back just the portion of the transaction after the savepoint.
o Erases all savepoints created after that savepoint.
o Releases all the locks obtained since the savepoint.
? Example :
UPDATE emp SET sal = sal + 100 WHERE deptno = 10;
SAVEPOINT s1;
DELETE FROM emp WHERE empno = 8000;
ROLLBACK TO SAVEPOINT s1;

In the above example, only the DELETE statement will be rolled back. The UPDATE is
neither committed nor rolled back at this point.
Infosys ORACLE 8i

Working with Other Schema Ob jects

? Some of the database schema objects that we will work with are:
o Sequences
o Synonyms
o Views
o Indexes
o Clusters

Sequences

? Sequences are used to generate sequential numbers, helpful in multi -user environ-
ments to generate and return unique se quential numbers, and to generate unique int e-
gers for use as primary keys.
? Sequence generators are objects that are stored as part of the database.
? Syntax:

CREATE SEQUENCE seqname


[INCREMENT BY n]
[START WITH m]
[MAXVALUE integer | NOMAXVALUE ]
[MINVALUE integer | NOMINVALUE ]
[CYCLE | NOCYCLE ]
[CACHE integer | NOCACHE ]

 Note:
? The default INCREMENT BY is 1. A positive number will cause incrementing up and
a negative number incrementing down.
? The default for MINVALUE for ascending sequences is 1.
? The default for MAXVALUE for descending sequences is -1.
? The default START WITH is MAXVALUE for descending sequences and MINVALUE
for ascending; use START WITH to override this default.
? To restart a sequence, specify CYCLE.
? CACHE allows a preallocated set of sequence numbers to be kept in memory. The d e-
fault is 20.
? To use the contents of a sequence use seq_name.CURRVAL or
seq_name.NEXTVAL.
? seqname.CURRVAL returns the current value of the sequence.
? seqname.NEXTVAL returns the next value of the sequence. Also increments the
value.
Examples:

CREATE SEQUENCE dept_seq


START WITH 1
INCREMENT BY 1;

To use the sequence:

INSERT INTO dept (deptno, dname, loc)


VALUES (dept_seq.NEXTVAL, 'Education', 'Fremont');

SELECT dept_seq.CURRVAL FROM DUAL;

SELECT dept_seq.NEXTVAL FROM DUAL;

 DUAL is Oracle supplied table that is made up of one column and one row. This table is
available to all users by default.

Synonyms

? A synonym is just another name for a database object.


? Synonyms do not require additional storage other than its definition in the data di c-
tionary.
? Synonyms are used:
o For security reasons to mask the owner and name of the object
o To simplify SQL statements.
o To provide transparency to user from remote databases.

? Whenever a user execute the query for example,

SELECT *
FROM table_name;

Oracle interprets it as

SELECT *
FROM owner.table_name;
Infosys ORACLE 8i

If the user is not the owner of the table then he has to use
owner.table_name. In order to hide the actual owner as well as ta-
ble_name synonyms can be used as fo llows:

CREATE PUBLIC SYNONYM syn_name FOR owner.table_name;

Example: Creation and use of Synonyms

CREATE PUBLIC SYNONYM pucust


FOR scott.customer;

SELECT *
FROM pucust;

INSERT INTO pucust(...) VALUES(...)

The PUBLIC option indicates that any user can access the synonym.

 Views

? A view is a logical table. It does not contain any data itself; it draws data from other
tables and views.
? The tables on which a view is based are called  base tables.
? Views are constructed with queries. A view takes the output of a query and treats it as
a table; hence, a view can also be thought of as a “stored query” or a “virtual table”.
? You can use the normal querying on the views as though views were tables the m-
selves.
? Insert, update, and delete to the base tables through the view is subject to certain r e-
strictions.
? All operations performed on a view actually affect data in the base tables of the view.
? Views can used to for various reasons like:
o Store complex queries
o Provide security to base tables by exposing only certain portions of table
data through views
o Isolate applications from changes in definitions of base tables

Creating Views

The CREATE VIEW DDL command is used to create a view, that mentions a query
based on which the view is created (in the absence of  aliases, the view column names are
same as that mentioned in the query) :

CREATE [OR REPLACE] VIEW


view  [ ( alias [, alias ]… ) ]
AS query 
[WITH CHECK OPTION]
[WITH READ ONLY]
WITH READ ONLY option specifies that no deletes, inserts, or updates to the base table
can be pe rformed through the view.
WITH CHECK OPTION specifies that inserts and updates performed through the view
must result in rows that the view query can select

Examples of Views

Suppose you would like to expose only part of the emp table. You can do so by creating a
view that selects certain columns from the table, and using (or granting privileges on, to
other users) this view, as shown below.

Table EMP
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7329 SMITH CLERK 7902 17-DEC-87 300.00 80 20
7499 ALLEN SALESMAN 7698 20-FEB-88 300.00 600 30
7521 WARD SALESMAN 7698 22-FEB-88 5.00 250 30
7566 JONES MANAGER 7839 02-APR-88 975 20

EMPNO ENAME JOB MGR DEPTNO


7329 SMITH CLERK 7902 20
7499 ALLEN SALESMAN 7698 30  View STAFF
7521 WARD SALESMAN 7698 30
7566 JONES MANAGER 7839 20

The above view is created with the DDL:

CREATE VIEW staff AS


SELECT empno, ename, job, manager, deptno
FROM emp;

You can then use the view as a normal table:

SELECT * FROM Staff;


INSERT INTO staff VALUES (8000, 'John', 'SALESMAN', 7839, 20);

If you did not want any insert or update to the base table through this view , create the
view with WITH READ ONLY option:

CREATE VIEW staff AS


SELECT empno, ename, job, manager, deptno
FROM emp
WITH READ ONLY;
Infosys ORACLE 8i

If you want to create a view that exposes only the clerks in the emp table, create a view as
follows:

CREATE VIEW clerk (id_number, person, department, position)


AS SELECT empno, ename, deptno,job
FROM emp WHERE job = 'CLERK'
WITH CHECK OPTION;

The WITH CHECK OPTION specifies that inserts and updates performed through the
view must result in rows that the view query can select. In this example any row other
than the one having job='CLERK' cannot be inserted into the table.

 Note: You cannot perform inserts, updates or deletes for a view if the view query co n-
tains:
o  joins
o set operators
o group functions
o GROUP BY clause
o the DISTINCT operator

Indexes

? The data in the tables are not sto red in any particular order of any column. Hence,
when you access the table data, it is sequential access. This can pose a performance
problem if the table is huge.
? You can use  Indexes to provide random access to data, there by enhancing perfor m-
ance due to faster access to the data.
? Indexes are stored separately from the actual data. The index is made up of the co l-
umn on which you are indexing, and the physical address ( ROWID) of the row with
that column value.
? Indexes are referred to whenever the indexed c olumns are referenced in the WHERE
clause.
o E.g., if the query
SELECT ename, sal FROM emp WHERE ename = 'SMITH'
is issued, and if there is an index on ename already, the index will be first
searched to find the location of the row with specified ename value, and
then the row is fetched from the table.
? With every data manipulation, the appropriate indexes are automatically updated.
o E.g., if there is an insert into the table, the corresponding indexes are also
updated to reflect the new rows.
? Indexes are created using the CREATE INDEX DDL command:

CREATE INDEX index_name ON table_name(column_name);


Example

CREATE INDEX idx_ename ON emp(ename);

When you create an index:


? Oracle gets and sorts the columns to be indexed,
? Stores the ROWID along with the index value for each row , and
? Loads the index from the bottom up.

 Note:
? Oracle, by default, creates indexes for columns defined as PRIMARY key or UNIQUE
key, at the time of table creation .
? Internally, Oracle uses B*Trees to manage the indexes.

Composite Indexes

A Composite index is one that is created on multiple columns in a table. It is also known
as concatenated index.

CREATE INDEX index_name ON table_name( col1, col2, col3);

Example

CREATE INDEX ordcust


ON orders(custcode,ordno)

Clusters

? A Cluster is a group of tables that share the same data blocks, because they share
the same columns and are often used together.
? If multiple tables are clustered together, they should have commo n column(s),
called the cluster key. E.g., emp and dept tables can be clustered together based
on the cluster key deptno that is common to both the tables.
? Advantages of using clusters:
o Disk I/O is reduced and access time improves for joins of clustered ta bles.
o Each cluster key is stored only once in the cluster and the cluster index, no
matter how many rows of different tables contain the value.

Creating a Cluster

? To create a cluster:
o First create the cluster using the CREATE CLUSTER command

You might also like