OracleSQL Infosys
OracleSQL Infosys
CONTENTS
CONTENTS.........................................................................................................................................................2
INTRODUCTORY CONCEPTS .....................................................................................................................3
THE DATABASE OBJECTS .................................................................................................................................. 3
DATABASE OBJECT NAMING RULES .................................................................................................................4
DATATYPES ........................................................................................................................................................4
THE DATA DEFINITION COMMANDS FOR TABLES ...................................................................... 8
CREATING A TABLE ...........................................................................................................................................8
CONSTRAINTS ON TABLES .................................................................................................................................9
DROPPING A TABLE .........................................................................................................................................12
ALTERING A TABLE .........................................................................................................................................13
SAMPLE TABLES ...............................................................................................................................................14
QUERYING THE TABLES............................................................................................................................15
CONDITIONAL RETRIEVAL OF ROWS ..............................................................................................................15
SQL FUNCTIONS..............................................................................................................................................17
GROUP (OR AGGREGATE) FUNCTIONS ...........................................................................................................17
SINGLE ROW ( OR SCALAR) FUNCTIONS ..........................................................................................................20
JOINS TO QUERY MULTIPLE TABLES ...............................................................................................................27
SET OPERATORS ..............................................................................................................................................29
NESTED QUERIES ............................................................................................................................................30
DATA MANIPULATION COMMANDS .....................................................................................................33
THE INSERT COMMAND ................................................................................................................................33
THE DELETE COMMAND ...............................................................................................................................33
THE UPDATE COMMAND ...............................................................................................................................33
THE TRANSACTION CONTROL COMMANDS ....................................................................................35
THE COMMIT COMMAND ...............................................................................................................................35
THE ROLLBACK COMMAND ..........................................................................................................................35
WORKING WITH OTHER SCHEMA OBJECTS .....................................................................................37
SEQUENCES......................................................................................................................................................37
SYNONYMS .......................................................................................................................................................38
VIEWS ...............................................................................................................................................................39
INDEXES ...........................................................................................................................................................41
CLUSTERS .........................................................................................................................................................42
Infosys ORACLE 8i
I ntroductory Concepts
? The database objects are entities stored in the database. These objects may be either
schema objects , or non-schema 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 na me as that user (e.g., scott, trng01, etc.). Each 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 are also stored in the database and can be created and 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
Datatypes
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
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;)
? 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.
? 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 row in a table in the
database. You can view this a ddress 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 Definition Commands for 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
Example:
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.
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)
);
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:
Note: CASCADE CONSTRAINTS allows you to drop a parent table that has referen c-
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
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:
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
? 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
? 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 name and salary of the employees whose salary is more than 1500
To list emp loyee details whose salary is between 1000 and 2000
To list employee names having ‘I’as the second character, and end character as 'S'
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 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 min imum 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
COUNT(*)
----------
9
TOTAL
----------
23625
tot jobs
----------
4
MAXIMUM
----------
5000
MAX(SAL)
----------
1400
Infosys ORACLE 8i
AVG(SAL) COUNT(*)
---------- ----------
3518.75 4
GROUP BY Clause
Examples
Job Employees
--------- ----------
ANALYST 2
CLERK 2
MANAGER 3
SALESMAN 2
To list the departments and the total salaries payable in each department
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.
String Functions
Function Description
String || String Concatenates two strings
ASCII(string) Returns ASCII value of the character
CHR(integer) Returns ch aracter 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
General Functions
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
Least
------
HAROLD
Greatest
----------
645
ENAME COMMISSION
---------- ---------------------
WARD 500
BLAKE No Commission
TURNER 0
ENAME Commission
---------- ------------------------
WARD 500
BLAKE NOT Eligible
TURNER Eligible, but 0
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.
Format Example/Description
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
Format Example/Description
“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
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
SYSDATE NEXT_DAY
--------- ---------
12-DEC-02 19-DEC-02
To get the last of the month
TODAY REVIEW ON
--------- ---------
12-DEC-02 01-JUL-03
To get years of experience of employees in department 20
HIREDATE In Words
--------- ----------------------------------
09-JUN-81 09, June , Nineteen Eighty-One
23-JAN-82 23, January , Nineteen Eighty-Two
HIREDATE In Words
--------- ---------------------
09-JUN-81 June, 9th, 1981
23-JAN-82 January, 23rd, 1982
To get the current time
Time Now
--------
12:20:08
To get the day name of a particular date
Date Day
--------- ---------
29-AUG-68 THURSDAY
Infosys ORACLE 8i
? 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 *
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:
? 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 (+) operator 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 */
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 */
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
INTERSECT
INTERSECT
INTERSECT
MINUS
/* List the jobs which are done in accounts only and not in sales */
MINUS
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 :
? Examples:
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 */
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 */
? 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 */
/* To list out the department details in which there are any employees */
DNAME DEPTNO
-------------------- ----------
Accounting 10
Research 20
Sales 30
Infosys ORACLE 8i
The DML commands INSERT, UPDATE, and DELETE are discussed in this section.
? 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');
? 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
Note: Update without a WHERE clause will update all the rows in a table.
? Example:
? 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.
? 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;
? A ROLLBACK undoes all the changes in the current transaction, and ends the transa c-
tion. It also releases the transaction's locks.
? Example:
? Using the ROLLBACK command with the TO SAVEPOINT clause performs the fo l-
lowing operations:
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
? 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:
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:
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
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:
SELECT *
FROM pucust;
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) :
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
If you did not want any insert or update to the base table through this view , create the
view with WITH READ ONLY option:
If you want to create a view that exposes only the clerks in the emp table, create a view as
follows:
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:
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 .
Example
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
Infosys ORACLE 8i
o Then create the tables within the cluster. This is done by including the
CLUSTER clause in the CREATE TABLE command
o Before you can insert any rows into the clustered tables, you must cr e-
ate a cluster index
Example: Creating tables emp and dept clustered around department number.
CREATE CLUSTER PERSONNEL(DEPT_NO NUMBER(2));