Vous êtes sur la page 1sur 73

ORACLE 10g FAST n FINAL

BEST OF LUCK

gaduamb@gmail.com

Mana Bhanjan Gadua

NOTE:

What is SQL and where does it come from? Structured Query Language (SQL) is a language that provides an interface to relational database systems. SQL was developed by IBM in the 1970s for use in System R, and is a de facto standard, as well as an ISO and ANSI standard. SQL is often pronounced as SEQUEL. OR SQL is a nonprocedural language that is designed specifically for data access operations on normalized relational database structures. In common usage SQL also encompasses DML (Data Manipulation Language), for INSERTs, UPDATEs, DELETEs and DDL (Data Definition Language), used for creating and modifying tables and other database structures. The development of SQL is governed by standards. A major revision to the SQL standard was completed in 1992, called SQL2. SQL3 support objects extensions and will be (partially?) implemented in Oracle8.

State the differences between SQL and other conventional programming Languages The primary difference between SQL and other conventional programming languages is that SQL statements specify what data operations should be performed rather than how to perform them. What is difference between SQL and SQL*PLUS

SQL*PLUS is a command line tool where as SQL and PL/SQL language interface and reporting tool. It is a command line tool that allows user to type SQL commands to be executed directly against an Oracle database. SQL is a language used to query the relational database (DML, DCL, and DDL). SQL*PLUS commands are used to format query result, Set options, Edit SQL commands and PL/SQL. Rules of Precedence Operator Name Arithmetic operators Concatenation operator Relational/Comparison conditions Logical Operator Operator *, /, +, || =, !=, >,<, >=, <=, <> IS [NOT] NULL, LIKE, [NOT] IN [NOT] BETWEEN NOT AND OR UNION UNOIN ALL INTERSECT MINUS Order Evaluated 1 2 3 4 5 6 7 8 All rows selected by either query All rows selected by either query, including all duplicates All distinct rows selected by both queries All distinct rows selected by the first query but not the second

Set Operators

State DDL, DML, DRL, TCL, and DCL? DDL (Data Definition Language): A data base schema is specifies by a set of definitions expressed by a special language called DDL. Examples: ALTER - alters the structure of the database. CREATE - to create objects in the database. DROP - delete objects from the database.

TRUNCATE - remove all records from a table, including all spaces allocated for the records are removed. RENAME - rename to a table.

DML (Data Manipulation Language): This language that enable user to access or manipulate data as
organized by appropriate data model.

Procedural DML or Low level: DML requires a user to specify what data are needed and how to get those data. Non-Procedural DML or High level: DML requires a user to specify what data are needed without specifying how to get those data.

Examples: INSERT - insert data into a table UPDATE - updates existing data within a table DELETE - deletes all records from a table, the space for the records remain DRL (Data Retrieval Language): Examples: SELECT - retrieve data from the database. TCL (Transaction Control Language): Examples: COMMIT - save work done SAVEPOINT - identify a point in a transaction to which you can later roll back ROLLBACK - restore database to original since the last COMMIT DCL (Data Control Language): Examples: GRANT gives users access privileges to database. REVOKE withdraw access privileges given with the GRANT command.

DDL
DDL -- create, alter, drop, truncate, rename CREATE TABLE SYNTAX Create table <table_name> (col1 datatype1, col2 datatype2 coln datatypen); Ex: SQL> create table student (no number (2), name varchar (10), marks number (3)); USING ALTER This can be used to add or remove columns and to modify the precision of the datatype. a)
ADDING COLUMN

Syntax: alter table <table_name> add <col datatype>; Ex:


SQL>

alter table student add sdob date;

b)

REMOVING COLUMN

Syntax: alter table <table_name> drop <col datatype>; Ex:


SQL>

alter table student drop column sdob;

c)

INCREASING OR DECREASING PRECISION OF A COLUMN

Syntax: alter table <table_name> modify <col datatype>; Ex:


SQL>

alter table student modify marks number(5);

* To decrease precision the column should be empty. d)


MAKING COLUMN UNUSED

Syntax: alter table <table_name> set unused column <col>; Ex:


SQL>

alter table student set unused column marks;

Even though the column is unused still it will occupy memory.

d)

DROPPING UNUSED COLUMNS

Syntax: alter table <table_name> drop unused columns; Ex:


SQL>

alter table student drop unused columns;

* You can not drop individual unused columns of a table. e)

RENAMING COLUMN

Syntax: alter table <table_name> rename column <old_col_name> to <new_col_name>; Ex:


SQL>

alter table student rename column marks to smarks;

USING TRUNCATE This can be used to delete the entire table data permanently. Syntax: truncate table <table_name>; Ex:
SQL>

truncate table student;

USING DROP This will be used to drop the database object; Syntax: Drop table <table_name>; Ex:
SQL>

drop table student;

USING RENAME This will be used to rename the database object; Syntax: rename <old_table_name> to <new_table_name>; Ex:
SQL>

rename student to stud;

USER DEFINED TYPE SQL> CREATE TYPE <Type_Name> IS OBJECT (V_NAME1 DATATYPE (Size) V_NAME2 DATATYPE (Size) V_NAME3 DATATYPE (Size) ); Example:

DML
INSERT This will be used to insert the records into table. We have two methods to insert. Syntax: insert into <table_name) values (value1, value2, value3 . Valuen); Ex: SQL> insert into student values (1, sudha, 100); SQL> insert into student values (2, saketh, 200); To insert a new record again you have to type entire insert command, if there are lot of records this will be difficult. This will be avoided by using address method. b) USING ADDRESS METHOD Syntax: insert into <table_name) values (&col1, &col2, &col3 . &coln); This will prompt you for the values but for every insert you have to use forward slash. Ex: SQL> insert into student values (&no, '&name', &marks); Enter value for no: 1 Enter value for name: Jagan Enter value for marks: 300 old 1: insert into student values(&no, '&name', &marks) new 1: insert into student values(1, 'Jagan', 300) SQL> / Enter value for no: 2 Enter value for name: Naren Enter value for marks: 400 By value method By address method

a) USING VALUE METHOD

old 1: insert into student values(&no, '&name', &marks) new 1: insert into student values(2, 'Naren', 400) c) INSERTING DATA INTO SPECIFIED COLUMNS USING VALUE METHOD Syntax: insert into <table_name)(col1, col2, col3 Coln) values (value1, value2, value3 . Valuen); Ex: SQL> insert into student (no, name) values (3, Ramesh); SQL> insert into student (no, name) values (4, Madhu); d) INSERTING DATA INTO SPECIFIED COLUMNS USING ADDRESS METHOD Syntax: insert into <table_name)(col1, col2, col3 coln) values (&col1, &col2 .&coln); This will prompt you for the values but for every insert you have to use forward slash. Ex: SQL> insert into student (no, name) values (&no, '&name'); Enter value for no: 5 Enter value for name: Visu old 1: insert into student (no, name) values(&no, '&name') new 1: insert into student (no, name) values(5, 'Visu') SQL> / Enter value for no: 6 Enter value for name: Rattu old 1: insert into student (no, name) values(&no, '&name') new 1: insert into student (no, name) values(6, 'Rattu') UPDATE This can be used to modify the table data. Syntax: Update <table_name> set <col1> = value1, <col2> = value2 where <condition>; Ex:
SQL>

update student set marks = 500; update student set marks = 500 where no = 2; update student set marks = 500, name = 'Venu' where no = 1;

If you are not specifying any condition this will update entire table.
SQL> SQL>

DELETE This can be used to delete the table data temporarily. Syntax: Delete <table_name> where <condition>;

Ex:
SQL>

delete student; delete student where no = 2;

If you are not specifying any condition this will delete entire table.
SQL>

USING TCL
USING COMMIT This will be used to save the work. Commit is of two types. a)
IMPLICIT

Implicit Explicit

This will be issued by oracle internally in two situations. b) When any DDL operation is performed. When you are exiting from SQL * PLUS.

EXPLICIT

This will be issued by the user. Syntax: Commit or commit work; * When ever you committed then the transaction was completed. USING ROLLBACK This will undo the operation. This will be applied in two methods. Syntax: Roll or roll work; Or Rollback or rollback work; * While process is going on, if suddenly power goes then oracle will rollback the transaction. USING SAVEPOINT You can use savepoints to rollback portions of your current set of transactions. Upto previous commit Upto previous rollback

Syntax: Savepoint <savepoint_name>; Ex:


SQL> SQL> SQL> SQL> SQL> SQL> SQL> SQL>

savepoint s1; insert into student values(1, a, 100); savepoint s2; insert into student values(2, b, 200); savepoint s3; insert into student values(3, c, 300); savepoint s4; insert into student values(4, d, 400);

Before rollback
SQL>

select * from student; NO NAME --- ------1 2 3 4 a b c d MARKS ---------100 200 300 400

SQL>

rollback to savepoint s3; Or rollback to s3;

SQL>

This will rollback last two records.


SQL>

select * from student; NO NAME --- ------1 2 a b MARKS ---------100 200

USING DCL
DCL commands are used to granting and revoking the permissions.

1. GRANT 2. REVOKE

: Use to grant privileges to other users or roles. : Use to take back privileges granted to other users and roles.

TYPES OF PRIVILEDGE 1. System Privileges. System Privileges are normally granted by a DBA to users. Examples of system privileges are CREATE SESSION, CREATE TABLE, and CREATE USER etc. 2. Object Privileges. Object privileges means privileges on objects such as tables, views, synonyms, procedure. These are granted by owner of the object. Privilege Select Insert Update Delete References Alter Index Description Ability to query the table with a select statement. Ability to add new rows to the table with the insert statement. Ability to update rows in the table with the update statement. Ability to delete rows from the table with the delete statement. Ability to create a constraint that refers to the table. Ability to change the table definition with the alter table statement. Ability to create an index on the table with the create index statement.

USING GRANT This is used to grant the privileges to other users. Syntax: Grant <privileges> on <object_name> to <user_name> [with grant option]; Example: 1. Individual privilege: SQL> grant select on EMP to MANA; 2. Set of privileges: SQL> grant select, insert on EMP to MANA; 3. All privileges:

10

SQL> grant all on EMP to MANA; 4. An user also grant permissions: SQL> grant all on EMP to MANA WITH GRANT OPTION; 5. To all other users of the database: SQL> GRANT select on EMP to public;

6. Suppose you want to grant update and insert privilege on only certain columns not on all the columns then include the column names in grant statement. SQL> grant update (ename), insert (empno, ename) on EMP to MANA;
Now the MANA user has to use dot method to access the object. SQL> select * from SCOTT.EMP; USING REVOKE This is used to revoke the privileges from the users to which you granted the privileges. Syntax: Revoke <privileges> on <object_name> from <user_name>; Ex:

1. revoke individual privilege:


SQL>

revoke select on EMP form MANA;

2. revoke set of privileges:


SQL>

revoke select, insert on EMP from MANA;

3. revoke all privileges:


SQL>

revoke all on EMP from MANA;

4. To all other users of the database: SQL> revoke select on EMP from public;
Note: You cannot take back column level privileges. Suppose you just want to take back insert privilege on ename column then you have to first take back the whole insert privilege and then grant privilege on empno column. ROLES A role is a group of Privileges. A role is very handy in managing privileges, particularly in such situation when number of users should have the same set of privileges. For example you have four users: Sami, Scott, Ashi, Tanya in the database. To these users you want to grant select, update privilege on EMP table, select, delete privilege on dept table. To do this first create a role by giving the following statement: Create role clerks Then grant privileges to this role. grant select,update on emp to clerks; grant select,delete on dept to clerks;

11

Now grant this clerks role to users like this grant clerks to sami, scott, ashi, tanya ; Now Sami, Scott, Ashi and Tanya have all the privileges granted on clerks role. Suppose after one month you want grant delete on privilege on emp table all these users then just grant this privilege to clerks role and automatically all the users will have the privilege. grant delete on emp to clerks; If you want to take back update privilege on emp table from these users just take it back from clerks role. revoke update on emp from clerks; To Drop a role Drop role clerks; LISTING INFORMATION ABOUT PRIVILEGES To see which table privileges are granted by you to other users. SELECT * FROM USER_TAB_PRIVS_MADE To see which table privileges are granted to you by other users SELECT * FROM USER_TAB_PRIVS_RECD; To see which column level privileges are granted by you to other users. SELECT * FROM USER_COL_PRIVS_MADE To see which column level privileges are granted to you by other users SELECT * FROM USER_COL_PRIVS_RECD; To see which privileges are granted to roles SELECT * FROM USER_ROLE_PRIVS;

12

USING ALIASES
CREATE WITH SELECT We can create a table using existing table [along with data]. Syntax: Create table <new_table_name> [col1, col2, col3 ... coln] as select * from <old_table_name>; Ex:
SQL>

create table student1 as select * from student; create table student2(sno, sname, smarks) as select * from student; create table student3 as select no,name from student; create table student2(sno, sname, smarks) as select * from student where 1 = 2;

Creating table with your own column names.


SQL>

Creating table with specified columns.


SQL>

Creating table with out table data.


SQL>

In the above where clause give any condition which does not satisfy. INSERT WITH SELECT Using this we can insert existing table data to a another table in a single trip. But the table structure should be same. Syntax: Insert into <table1> select * from <table2>; Ex:
SQL>

insert into student1 select * from student; insert into student1(no, name) select no, name from student;

Inserting data into specified columns


SQL>

COLUMN ALIASES Syntax: Select <orginal_col> <alias_name> from <table_name>; Ex:

13

SQL>

select no sno from student; or select no sno from student;

SQL>

TABLE ALIASES If you are using table aliases you can use dot method to the columns. Syntax: Select <alias_name>.<col1>, <alias_name>.<col2> <alias_name>.<coln> from <table_name> <alias_name>; Ex:
SQL>

select s.no, s.name from student s;

USING MERGE
MERGE You can use merge command to perform insert and update in a single command. Ex:
SQL>

Merge into student1 s1 Using (select *From student2) s2 On(s1.no=s2.no) When matched then Update set marks = s2.marks When not matched then Insert (s1.no,s1.name,s1.marks) Values(s2.no,s2.name,s2.marks);

In the above the two tables are with the same structure but we can merge different structured tables also but the datatype of the columns should match. Assume that student1 has columns like no,name,marks and student2 has columns like no, name, hno, city. Merge into student1 s1 Using (select *From student2) s2 On(s1.no=s2.no) When matched then Update set marks = s2.hno When not matched then Insert (s1.no,s1.name,s1.marks)

SQL>

14

Values(s2.no,s2.name,s2.hno);

MULTIPLE INSERTS
We have table called DEPT with the following columns and data DEPTNO -------10 20 30 40 a) b) DNAME -------accounting research sales operations LOC ---new york dallas Chicago boston

CREATE STUDENT TABLE SQL>

Create table student(no number(2),name varchar(2),marks number(3)); Insert all Into student values(1,a,100) Into student values(2,b,200) Into student values(3,c,300) Select * from dept where deptno=10;

MULTI INSERT WITH ALL FIELDS SQL>

-- This inserts 3 rows c)


MULTI INSERT WITH SPECIFIED FIELDS SQL>

insert all Into student (no,name) values(4,d) Into student(name,marks) values(e,400) Into student values(3,c,300) Select *from dept where deptno=10;

15

-- This inserts 3 rows d)


MULTI INSERT WITH DUPLICATE ROWS SQL>

insert all Into student values(1,a,100) Into student values(2,b,200) Into student values(3,c,300) Select *from dept where deptno > 10;

-- This inserts 9 rows because in the select statement retrieves 3 records (3 inserts for each row retrieved) e)
MULTI INSERT WITH CONDITIONS BASED SQL>

Insert all When deptno > 10 then Into student1 values(1,a,100) When dname = SALES then Into student2 values(2,b,200) When loc = NEW YORK then Into student3 values(3,c,300) Select *from dept where deptno>10;

-- This inserts 4 rows because the first condition satisfied 3 times, second condition satisfied once and the last none. f)
MULTI INSERT WITH CONDITIONS BASED AND ELSE SQL>

Insert all When deptno > 100 then Into student1 values(1,a,100) When dname = S then Into student2 values(2,b,200) When loc = NEW YORK then Into student3 values(3,c,300) Else Into student values(4,d,400) Select *from dept where deptno>10;

-- This inserts 3 records because the else satisfied 3 times g)


MULTI INSERT WITH CONDITIONS BASED AND FIRST SQL>

Insert first When deptno = 20 then Into student1 values(1,a,100) When dname = RESEARCH then

16

Into student2 values(2,b,200) When loc = NEW YORK then Into student3 values(3,c,300) Select *from dept where deptno=20; -- This inserts 1 record because the first clause avoid to check the remaining conditions once the condition is satisfied. h)
MULTI INSERT WITH CONDITIONS BASED, FIRST AND ELSE SQL>

Insert first When deptno = 30 then Into student1 values(1,a,100) When dname = R then Into student2 values(2,b,200) When loc = NEW YORK then Into student3 values(3,c,300) Else Into student values(4,d,400) Select *from dept where deptno=20;

-- This inserts 1 record because the else clause satisfied once i)


MULTI INSERT WITH MULTIBLE TABLES

SQL>

Insert all Into student1 values(1,a,100) Into student2 values(2,b,200) Into student3 values(3,c,300) Select *from dept where deptno=10;

-- This inserts 3 rows ** You can use multi tables with specified fields, with duplicate rows, with conditions, with first and else clauses.

17

State difference between CHAR and VARCHAR? The basic difference between CHAR and VARCHAR is that, if we declare a space in CHAR and if we dont use all space, then unused space will be wasted but not in VARCHAR. What is a query? A query with respect to DBMS relates to user commands that are used to interact with a data base. The query language can be classified into data definition language and data manipulation language. What are the primitive operations common to all record management systems? Addition, deletion and modification. Name the buffer in which all the commands that are typed in are stored Edit Buffer. Oracle Built-in Datatypes DATA TYPES CHAR(size) NCHAR(size) VARCHAR(size)/ VARCHAR2(size) NVARCHAR2(size) NUMBER(p,q) DESCRIPTION Stores character string. Maximum number of character- 255. Inserted values will be padded with space. Fixed-length character data of length size characters. Maximum size is determined by the national character set definition, with an upper limit of 2000 bytes. Default and minimum size is 1 character. Stores variable length alphanumeric data. Maximum number of character- 4000. Inserted values will not be padded with space. Variable-length character string having maximum length size characters. Maximum size is determined by the national character set definition, with an upper limit of 4000 bytes. You must specify size for NVARCHAR2. Stores numbers (fixed or floating point). p Determines maximum length of the data. q - Determines the number of places to the right oh the decimal. Maximum length -1 followed by 125 zeros. If scale is omitted, default is zero. If precision is omitted, values are stored with their original precision up to the Maximum of 38 digits. Represents date and time. The standard format is DD-MON-YY.

DATE

18

DATETIME stores date in 24-hour format. By default, the time in a date field is 12:00:00 AM. The default date for a date field is the first day of the current month. TIMESTAMP Year, month, and day values of date, as well as hour, minute, and second (fractional_ seconds_precision) values of time, where fractional_seconds_precision is the number of digits in the fractional part of the SECOND datetime field. Accepted values of fractional_seconds_precision are 0 to 9. The default is 6. TIMESTAMP All values of TIMESTAMP as well as time zone displacement value, where (fractional_seconds_precision) fractional_seconds_precision is the number of digits in the fractional part of the WITH TIME ZONE SECOND datetime field. Accepted values are 0 to 9. The default is 6. TIMESTAMP All values of TIMESTAMP WITH TIME ZONE, with the following exceptions: n (fractional_seconds_precision) Data is normalized to the database time zone when it is stored in the database. WITH LOCAL TIME ZONE n When the data is retrieved, users see the data in the session time zone. INTERVALYEAR Stores a period of time in years and months, where year_precision is the (year_precision) number of digits in the YEAR datetime field. Accepted values are 0 to 9. The TO MONTH default is 2. INTERVAL DAY Stores a period of time in days, hours, minutes, and seconds, where n (day_precision) day_precision is the maximum number of digits in the DAY datetime field. TO SECOND Accepted values are 0 to 9. The default is 2. n fractional_seconds_precision is (fractional_seconds_precision) the number of digits in the fractional part of the SECOND field. Accepted values are 0 to 9. The default is 6. LONG Stores variable length character string up to 2GB. Used to stores array of binary data in ASCII format. RAW(size) Raw binary data of length size bytes. Maximum size is 2000 bytes. You must specify size for a RAW value. LONG RAW Raw binary data of variable length up to 2 gigabytes. ROWID Base 64 string representing the unique address of a row in its table. This datatype is primarily for values returned by the ROWID pseudo column. UROWID [(size)] Base 64 string representing the logical address of a row of an index-organized table. The optional size is the size of a column of type UROWID. The maximum size and default is 4000 bytes. Object Type LOB They hold values called locations, specifying the location of large objects that are stored out of line. CLOB A character large object containing single-byte characters. Both fixed-width and variable-width character sets are supported, both using the CHAR database character set. Maximum size is 4 gigabytes. NCLOB A character large object containing Unicode characters. Both fixed-width and variable-width character sets are supported, both using the NCHAR database character set. Maximum size is 4 gigabytes. Stores national character set data. BLOB A binary large object. Maximum size is 4 gigabytes. BFILE Contains a locator to a large binary file stored outside the database. Enables byte stream I/O access to external LOBs residing on the database server. Maximum size is 4 gigabytes. How can you come to know that an object is valid or not? SQL> SELECT STATUS FROM USER_OBJECTS WHERE OBJECT_NAME= ObjectName; Example: SQL> SELECT STATUS FROM USER_OBJECTS WHERE OBJECT_NAME= EMP; How can you see the current user? Sql> show user How can you switch to dos? Sql> host How can you change the Sql prompt? SQL> set sqlprompt MANA > How do you get the distinct rows in a table? Using DISTINCT.

19

Sql > SELECT DISTINCT job FROM EMP; Using GROUP BY. Sql > SELECT job FROM EMP GROUP BY job; How can you get the duplicate rows? Sql> SELECT job FROM EMP GROUP BY job HAVING COUNT (1)>1; How can you eliminate/delete the duplicate rows? Sql>DELETE FROM emp WHERE rowid NOT IN (SELECT MIN (rowid) FROM emp GROUP BY empno, ename, job, mgr, hiredate, sal, comm., deptno); What are different Oracle database objects? TYPES Independent Object OBJECT TABLE VIEW SEQUENCE SYNONYMS INDEX CONSTRAINT DESCRIPTION Basic unit of storage; composed of row and columns. Logically represents subsets of data from one or more tables. Generates primary key values. Alternative name for an object. Improves the Performance of queries. Used to define the Integrity rule

Dependent Object

20

FUNCTION SINGLE ROW FUNCTION GROUP FUNCTION


AVG (Distinct/All col) SUM (Distinct/All col) MAX (Distinct/All col) MIN (Distinct/All col) COUNT (*/Distinct/All col) STDDEV (Distinct/All col) VARIENCE (Distinct/All col)

CHARACTER FUNCTION

NUMBER FUNCTION
ABS (n) SIGN (n) SQRT (n) POW (n, m) MOD (n, m) ROUND (n, m) TRUNC (n, m) CEIL (n) FLOOR (n)

DATE FUNCTION

CASE CONVERSION FUNCTION

LOWER (col/expr) UPPER (col/expr) INITCAP (col/expr) CONCAT (col1/expr1, col2/expr2) LENGTH (col/expr) INSTR (col/expr, char, m, n) SUBSTR (col/expr, m, n) LPAD (char1, n, char2) RPAD (char1, n, char2) LTRIM (char, set) RTRIM (char, set) TRIM (LEADING/TRALING/BOTH, TrimChar FROM TrimSource) REPLACE (char, SearchStr, ReplaceStr) TRANSLATE (char, From, To) DECODE CHR (n) ASCII (char)

ADD_MONTHS (Date, n) MONTHS_BETWEEN (Date1, Date2) NEXT_DAY (Date, char) LAST_DAY (Date) ROUND (Date, Format) TRUNC (Date, Format)
Format= DAY/MONTH/YEAR

TO_CHAR (Number, Format, nlsparms) TO_CHAR (Date, Format, nlsparms) TO_NUMBER (char, Format, nlsparms) TO_DATE (char, Format, nlsparms)

MISCELLANEOUS FUNCTION
UID USER LEAST (expr1, expr2) GREATEST (expr1, expr2) VSIZE (expr) SOUNDEX (char) USERNV (option) ****************************************************
Where OPTION are: ISDBA LANGUAGE TERMINAL SESSIONID ENTRYID LANG INSTANCECLIENT_INFO **********************************************************

GENERAL FUNCTION
These functions work with any data type and pertain to using nulls. NVL (expr1, expr2) NVL2 (expr1, expr2, expr3) NULLIF (expr1, expr2) COALESCE (expr1, expr2, ..., exprn)

21

DATE FORMAT TO_CHAR (DATE, format,nlsparameters); Sysdate=27.DEC.2009 Time=12:01:55 AM EXAMPLE: Sql> SELECT sysdate, TO_CHAR (sysdate, 'D') FROM DUAL DATE FORMAT: EXPLANATION D Numeric week day indicator (1-7) DD Month day indicator (1-31) DDD Year day indicator (1-366) TH Date format suffixes SP SPTH FM Fill mode indicator FX Format exact DY Abbreviated weak day indicator DAY Week day spelling indicator (SUNDAY-SATURDAY) W Week of the month indicator WW Year week indicator (1-53) IW ISO standard year week indicator (1-53) MM Numeric month indicator (01-12) MON Abbreviated month indicator (JAN-DEC) MONTH Month spelling indicator (JANYUARY-DECEMBER) Q Quarter of the year indicator (1-4) J Julian day indicator CC Century indicator SCC S prefixes BC date with - IY ISO standard 2 digit year indicator YY 2 digit year indicator IYYY ISO standard 4 digit year indicator YYYY 4 digit year indicator SYYY YEAR Spelled year indicator SYEAR AM Meridian indicator A.M. PM P.M. HH 12 hour clock mode HH12 HH24 24 hour clock mode MI Minute indicator SS Second indicator SSSSS Second past mid night (0-86399) HH:MI:SS - / !, ., ;, : Date format punctuator

RESULT 1 27 361 27TH TWENTY-SEVEN TWENTY-SEVENTH SUN SUNDAY 4 52 52 12 DEC DECEMBER 4 2455193 21 21 AD 09 09 2009 2009 THO THOUSAND NINE

12 01 55 115 12:01:55

22

GENERAL FUNCTION These functions work with any data type and pertain to the use of null values in the expression list. FUNCTION NVL(expr1, expr2) DESCRIPTION

Converts a NULL value to an actual value. If expr1 is NULL, NVL returns expr2. Data types that can be used are date, character, and number.
Where:

expr1 is the source value or expression that may contain a


NVL2(expr1, expr2, expr3) null. expr2 is the target value for converting the null

If expr1 is NOT NULL, NVL2 returns expr2. If expr1 is NULL, NVL2 returns expr3.
The argument expr1can have any data type. Where: expr1 is the source value or expression that may contain null expr2 is the value returned if expr1 is not null expr3 is the value returned if expr2 is null returns expr1, if they are not equal. You cannot specify the literal NULL for first expression. Returns the first non-null expression in the expression list The advantage of the COALESCE function over the NVL function is that the COALESCE function can take multiple alternate values. Where: expr1 returns this expression if it is not null expr2 returns this expression if the first expression is null and this expression is not null exprn returns this expression if the preceding expressions are null

NULLIF (expr1, expr2)

Compares two expressions and returns null if they are equal, or

COALESCE (expr1, expr2,,exprn)

CONDITIONAL EXPRESSIONS Two methods used to implement conditional processing (IF-THEN-ELSE logic) within a SQL statement are the CASE expression and the DECODE function.

1. CASE expression
CASE expressions let you use IF-THEN-ELSE logic in SQL statements without having to invoke procedures. In a simple CASE expression, Oracle searches for the first WHEN ... THEN pair for which expr is equal to comparison_expr and returns return_expr. If none of the WHEN ... THEN pairs meet this condition, and an ELSE clause exists, then Oracle returns else_expr. Otherwise, Oracle returns null. You cannot specify the literal NULL for all the return_exprs and the else_expr. All of the expressions (expr, comparison_expr, and return_expr) must be of the same data type, which can be CHAR, VARCHAR2, NCHAR, or NVARCHAR2. Syntax: CASE expr WHEN comparison_expr1 THEN return_expr1 [WHEN comparison_expr2 THEN return_expr2

23

END

WHEN comparison_exprn THEN return_exprn ELSE else_expr]

Example: Sql> SELECT ename, job, sal, CASE job WHEN clerk THEN 10*sal WHEN analyst THEN 15*sal WHEN manager THEN 20*sal ELSE sal END "REVISED_SALARY" FROM emp;

2. DECODE function
The DECODE function decodes an expression in a way similar to the IF-THEN-ELSE logic. The DECODE function decodes expression after comparing it to each search value. If the expression is the same as search, result is returned. If the default value is omitted, a null value is returned where a search value does not match any of the result values. Syntax: DECODE (col|expression, search1, result1 [, search2, result2,...,] [, default]) Example: Sql> SELECT ename, job, sal, DECODE (job, clerk, 10*sal, analyst, 15*sal, manager, 20*sal, "REVISED_SALARY") FROM emp;

GROUP FUNCTION.

A GROUP FUNCTION operates on MULTIPLE rows and returns single result.


These functions can appear in SELECT lists and HAVING clause.

24

Syntax: GROUP FUNCTION_NAME (distinct/all/n)

Distinct makes the function to consider only non duplicate values. All makes the function to consider every value including duplicates. The data types for arguments may CHAR, VARCHAR, NUMBER or DATE. All group functions except COUNT (*) ignore NULL values. To substitute a NULL value, use the NVL function. When a group function is declared in Select list, no single row columns should be declared. When a group function is declared in 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. Group functions are not affected by NULL. Explain the use of the WHERE clause. It directs SQL to extract data from rows where the value of the column is the same as the current value of the WHERE clause variable. GROUP BY clause GROUP BY clause is used to divide the rows in a table into groups. It is used in the group functions to return summary information for each group. HAVING clause HAVING clause is used to specify which groups are to be displayed. It restricts the groups on the basis of aggregate information. HAVING clause is used to filter groups and WHERE clause is used to filter rows. You cannot use WHERE clause to filter groups. Order of execution: SELECT FROM WHERE GROUP BY HAVING ORDER BY

25

INTEGRITY RULE & CONSTRAINTS


Define the "integrity rules" DATA INTEGRITY: It is a state in which all the data values stored in the database are correct. Enforcing data integrity ensures the quality of the data in the database. Classification: Entity integrity Domain integrity Referential integrity User defined integrity I. Entity Integrity: States that Primary key cannot have NULL value. It defines a row as a UNIQUE entity for a particular table. Entity integrity enforces the integrity of the identified columns or the PRIMARY KEY of a table. II. 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 using: a) FOREIGN KEY constraint b) CHECK constraint c) DEFAULT key word d) NOT NULL constraint III. Referential Integrity: It preserves the defined relationship between tables when records are entered or deleted. It ensures that key values are consistent across tables. States that Foreign Key can be either a NULL value or should be Primary Key value of other relation. When referential integrity is enforced, it prevents from: Adding (INSERT) records to a related (CHILD) table if there is no associated record in the primary (MASTER) table. Changing (UPDATE) values in a primary table that in orphaned records in a related table. Changing (UPDATE) values in a related table if there is matching related records primary table. Deleting record from a primary table if there is matching related records. EXAMPLE: MASTER/PRIMARY/PARENT : DEPT DETAIL/RELATED/CHILD : EMP IV. User Defined Integrity: It allows defining specific business rules that do not fall into any one of the other integrity categories.

26

These are business rules which can be handled at run time, usually designed using database triggers in PL/SQL. These are rules generally specific to the organizational business process. Can be any situation that looks abnormal to the current system process.

What is constraint? What are various constraints used in SQL? CONSTRAINT: Constraints in database are used to define an integrity constraint, as a rule that restricts the value in the database. There are six type of constraints are present in Oracle: NOT NULL constraint. UNIQUE constraint. PRIMARY KEY constraint. FOREIGN KEY constraint. CHECK constraint. REF constraint. Declaration style: I. COLUMN LEVEL/ INLINE Style They are declared as a part of the definition of an individual column or attribute. Usually applied when the constraint is specific to that column only. II. TABLE LEVEL/ OUT OF LINE Style They are declared as a part of the table definition. Applied when the constraint is applied on combination of columns together. Every constraint is managed by ORACLE with a constraint name in the Meta data. Hence when we declare a constraint if we do not provide a constraint name ORACLE associates the constraint with name. With in a single user no two constraints can have the same name. Rather than depending on the ORACLE supplied constraint name, it is better to define our own constraint name for all constraints. Constraints are named using CONSTRAINT clause. The CONSTRAINT clause can appear in: CREATE & ALTER table statement. CREATE & ALTER view statement. Oracle does not support constraints on columns or attributes whose data type is: USER_DEFINED objects. NESTED TABLE & VARRAY. REF & LOB. Exceptions NOT NULL constraint is supported for an attribute whose data type is USER_DEFINED object, VARRAY, REF, LOB. NOT NUL, FOREIGN KEY, & REF constraints are supported on a column or TYPE REF.

1. NOT NULL Constraint: A NOT NULL constraint prohibits a column from containing Nulls. NOT NULL should be defined using only INLINE specification. The default is NULL (if not specified). To satisfy a NOT NULL constraint, every row in the table must contain a value for the column. Restrictions: NULL or NOT NULL constraint can not be specified as VIEW constraints. NULL or NOT NULL constraint can not be specified for an attribute of an object. Example: Sql > CREATE TABLE student (

27

SNo NUMBER (6) CONSTRAINT SNoNN NOT NULL, SName VARCHAR2 (25) CONSTRAINT SNameNN NOT NULL, CourseName VARCHAR2 (25) CONSTRAINT CourseNameNN NOT NULL, JoinDate Date ); 2. UNIQUE Constraint: The UNIQUE constraint designates a column as a UNIQUE key. 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 style. To satisfy a UNIQUE constraint, no two rows in the table can have the same value for the UNIQUE key. UNIQUE key made of a single column can contain NULL value. Restrictions: 1. A composite UNIQUE key cannot have more than 32 columns. 2. Same column or combination of columns cannot be designate as both UNIQUE key and PRIMARY key. 3. We cannot specify a UNIQUE key when creating a sub-table or sub-view in an inheritance hierarchy. 4. The UNIQUE key can be specified only for the top level (root) table or view. 5. UNIQUE key cannot be implemented on columns having: LOB LONG LONG RAW VARRAY NESTED TABLE OBJECT BFILE REF TIME STAMP WITH TIME ZONE Example: Inline Style: Sql > CREATE TABLE student ( SNo NUMBER (6) CONSTRAINT SNoUNK UNIQUE, SName VARCHAR2 (25) CONSTRAINT SNameNN NOT NULL, CourseName VARCHAR2 (25) CONSTRAINT CourseNameNN NOT NULL, JoinDate Date ); Out of line Style: 1 Sql > CREATE TABLE student ( SNo NUMBER (6), SName VARCHAR2 (25) CONSTRAINT SNameNN NOT NULL, CourseName VARCHAR2 (25) CONSTRAINT CourseNameNN NOT NULL, CONSTRAINT SNoUNK UNIQUE (SNo) ); Out of line Style: 2 (Composite UNIQUE constraint) Sql > CREATE TABLE student ( SNo NUMBER (6), SName VARCHAR2 (25), CourseName VARCHAR2 (25) CONSTRAINT CourseNameNN NOT NULL, CONSTRAINT SNoNameUNK UNIQUE (SNo, SName)); 3. PRIMARY KEY CONSTRAINT: A PRIMARY KEY constraint designates a column as the PRIMARY KEY of a table or view. A composite PRIMARY KEY designates a combination of columns as the PRIMARY KEY. The PRIMARY KEY CONSTRAINT attached to a table column (columns) ensures that:

28

The data entered in the table column(s) is UNIQUE across the entire column(s). None of the cells belonging to the table column(s) are left empty (i.e. NOT NULL). When the CONSTRAINT is declared at column level or inline style only PRIMARY 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: 1. A table or view can have only one PRIMARY key. 2. The size of a PRIMARY KEY cannot exceed approximately one database block. 3. A composite PRIMARY key cannot have more than 32 columns. 4. Same column or combination of columns cannot be designate as both UNIQUE key and PRIMARY key. 5. PRIMARY KEY cannot be specified when creating a sub table or sub view in an inheritance hierarchy. 6. The PRIMARY key can be specified only for the top level (ROOT) table or view. 7. PRIMARY KEY cannot be implemented on column having: LOB LONG LONG RAW VARRAY NESTED TABLE OBJECT BFILE REF TIME STAMP WITH TIME ZONE Example: Inline Style: Sql > CREATE TABLE student ( SNo NUMBER (6) CONSTRAINT SNoPK PRIMARY KEY, SName VARCHAR2 (25) CONSTRAINT SNameNN NOT NULL, CourseName VARCHAR2 (25) CONSTRAINT CourseNameNN NOT NULL );

Out of line Style: 1 Sql > CREATE TABLE student ( SNo NUMBER (6), SName VARCHAR2 (25) CONSTRAINT SNameNN NOT NULL, CourseName VARCHAR2 (25) CONSTRAINT CourseNameNN NOT NULL, CONSTRAINT SNoPK PRIMARY KEY (SNo) ); Out of line Style: 2 (Composite PRIMARY KEY constraint) Sql > CREATE TABLE student ( SNo NUMBER (6), SName VARCHAR2 (25), CourseName VARCHAR2 (25) CONSTRAINT CourseNameNN NOT NULL, CONSTRAINT SNoNamePK PRIMARY KEY (SNo, SName) ); 4. FOREIGN KEY CONSTRAINT: This constraint establishes a relationship between records (i.e. data) across a MASTER (primary) and DETAIL (foreign) table. This relationship ensures that: Records cannot be INSERTED or UPDATED into DETAIL table if corresponding records in the MASTER table do not exist.

29

Record of the MASTER table cannot be UPDATED or DELETED if corresponding records in the DETAIL table exist. If the ON DELETE CASCADE option is set, a DELETE operation in the MASTER table will trigger a DELETE operation for corresponding records in all DETAIL table. It is also known as REFERENTIAL INTEGRITY CONSTRAINT. Must reference a PRIMARY KEY or UNIQUE column(s) in MASTER table. Will automatically reference the PRIMARY KEY of the MASTER table if no column (or group of columns) is specified when creating the FOREIGN KEY but a table name is specified. Requires that the FOREIGN KEY column(s) and the CONSTRAINT column(s) have matching data types. May reference the same table named in the CREATE TABLE statement.

Inline Style: Syntax: <column_name><data_types> (size) REFERENCES <table_name>, [(<column_name>)] [ON DELETE CASCADE] Example: SQL > CREATE TABLE Order_details (Order_no varchar2 (6) REFERENCES Sales_order, Product_no varchar2 (6), Order_date date, Order_status varchar2 (8) PRIMARY KEY (order_no, Product_no)); Out of line Style: Syntax: FOREIGN KEY (<column_name>,<column_name>) REFERENCES <table_name> .<column_name>; Example: SQL > CREATE TABLE Order_details (Detlorder_no varchar2 (6), Product_no varchar2 (6), Qty_order number (8), Product_rate number (8,2), PRIMARY KEY (Detlorder_no, Product_no) FOREIGN KEY (Detlorder_no) REFERENCES Sales_order.Order_no); 5. 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 FALSE. If the expression in a check constraint does not return a true/ false, the value is indeterminate or unknown. Restriction: CHECK CONSTRAINT must be avoided if the constraint can be defined using the NOT NULL, PRIMARY KEY or FOREIGN KEY constraint. The condition cannot contain SUBQUERIES or SEQUENCE. The condition cannot include SYSDATE, UID, USER or USERENV SQL functions. Inline Style: Syntax: <column_name><data_types> (size) CHECK (logical expression) Example:

30

SQL > CREATE TABLE Client_master (Client_no varchar2 (6), Name varchar2 (15) CHECK (Name=UPPER (name)); Out of line Style: Syntax: CHECK (logical expression) Example: SQL > CREATE TABLE Client_master (Client_no varchar2 (6), Name varchar2 (15), CHECK (Name=UPPER (name))); What is difference between UNIQUE and PRIMARY KEY CONSTRAINTS? Both PRIMARY key and UNIQUE key enforces uniqueness of the column on which they are defined. But by default a PRIMARY key creates a CLUSTERED INDEX on the column; where as UNIQUE key creates a NON-CLUSTERED INDEX by default. A table can have only one PRIMARY key whereas there can be any number of UNIQUE keys. The columns that compose PK are automatically define NOT NULL, whereas a column that compose a UNIQUE is not automatically defined to be mandatory must also specify the column is NOT NULL. What is ON DELETE CASCADE? The default behavior of the FOREIGN KEY can be changed by using the ON DELETE CASCADE option. When the ON DELETE CASCADE is specified in the FOREIGN KEY definition, if the user deletes a record in the master table, all corresponding records in the detail table along with the record in the master table will be deleted. Syntax: Sql > <Column name> <data type> (<size>) REFERENCES <table name> [(<column name>)] [ON DELETE CASCADE]

31

JOIN
JOINS: Join is a technique, i.e., used to retrieve data from multiple tables. Row in one table can be joined to row in another table according to common values existing in corresponding columns. That is, usually primary and foreign key columns. When writing a SELECT statement that joins tables, precede the column name with the table name for clarity and so enhance database access. If the same column name appears in more than one table, the column name must be prefixed with the table name that is known as TABLE ALIAS. To join n tables together, you need a minimum of n-1 join conditions. For example, to join four TABLES, a minimum of three joins is required. This rule may not apply if your table has a concatenated primary key, in which case more than one column is required to uniquely identify each row.

EQUIJOINS (Natural Join/ Simple joins/ Inner joins): It is a join condition that retrieves rows from one or more tables in which one or more columns in one table are equal to one or more columns in the second table. An EQUIJOIN is a join with a join condition containing an equality operator (=). It combines rows that have equivalent values for the specified columns.

Example:

32

33

NATURAL JOIN

34

INNER JOIN

NON-EQUIJOINS: It is a join condition that is executed when no column in one table correspondence directly to a column in other table. The data in the tables is directly not related but indirectly or logically related through proper values. It is a condition containing something other than equality operator. Examples:

35

SELF JOINS: It is a join of table to it self. The same table appears twice in the FROM clause and is followed 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:

36

OUTER JOINS: Its a join condition used where One can query all the rows of one of the TABLES in the join condition even though they don't satisfy the join condition. The missing rows can be returned by using an outer join operator in the join condition. The operator is a plus sign enclosed in parentheses (+) and is placed on the side of the join that is deficient in information. To perform an out join of tables A and B and returns all rows from A apply the outer join operator (+) to all column of B. For all rows in A that have no matching rows in B oracle returns NULL for any select list expressions containing columns of B. Rules and Restrictions: The (+) operator can appear only in the WHERE 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 (+) operator 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.

37

Example: FULL OUTER JOIN (FULL JOIN)

LEFT OUTER JOIN (LEFT JOIN)

RIGHT OUTER JOIN (RIGHT JOIN)

38

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.deptno, loc FROM emp, dept WHERE emp.deptno=dept.deptno AND UPPER(job)=MANAGER; Table Aliases: Table aliases can be used instead of table names. A table alias gives an alternative 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. E.g. emp E. A table alias can be up to 30 characters in length. If a table alias is used for a particular table name in the FROM clause, then that table alias must be substituted throughout the SELECT statement. A table alias is valid only for the current SELECT statement. Example:

39

Sql > SELECT E.empno, E.ename, D.deptno, D.dname FROM emp E, dept D WHERE E.deptno=D.deptno CARTESIAN PRODUCT/ CROSS JOIN (Return m X n result. Where m=nos. of row of table1 & n=nos. of row of table2)

SELECT table1.column, table2.column FROM table1 [CROSS JOIN table2] | [NATURAL JOIN table2] | [JOIN table2 USING (column_name)] | [INNER JOIN table2 ON(table1.column_name = table2.column_name)] | [JOIN table2 ON (table1.column_name = table2.column_name)] |

40

[LEFT|RIGHT|FULL OUTER JOIN table2 ON (table1.column_name = table2.column_name)]; Joining Data from 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 > SELECT C.name, O.oldid, I.item, O.total FROM customer C, ord O, item I WHERE C.custid=O.custid AND O.oldid=I.oldid AND C.name=TKB SPORT SHOP; What is difference between Rename and Alias? Rename is a permanent name given to a table or column whereas Alias is a temporary Name given to a table or column which do not exist once the SQL statement is executed.

41

SUBQUERY
A subquery is a SELECT statement that is embedded in a clause of another SELECT statement. Types of operator Single row operators (=, >, >=, <, <=, <>). Multiple row operators (IN, ANY, ALL). Types of subquery Single row subquery WHERE clause HAVING clause FROM clause (Inline views) Multiple row subquery In addition, there are three subtypes of subqueries that may return single or multiple rows. Multiple column subquery Nested subquery Correlated subquery SINGLE ROW SUBQUERY A single-row subquery is one that returns zero or one row from the inner SELECT statement to the outer SQL statement. This type of subquery uses a single-row operator (=, >, >=, <, <=, <>). A subquery may be appear in a WHERE clause, a HAVING clause, or a FROM clause.

Example: Subquery in WHERE clause

Example: Subquery in HAVING clause

42

Example: Subquery in FROM clause (INLINE VIEWS) A subquery in the FROM clause of the main query (outer query) is known as INLINE VIEW because the subquery provides data inline with the FROM clause. An INLINE VIEW is not a schema object.

MULTIPLE ROW SUBQUERY (IN, ALL, ANY) A multiple-row subquery is one that returns one or more row from the inner SELECT statement to the outer SQL statement. IN: Equal to any member in the list. ANY: Compares value to each value returned by the subquery. >ANY means more than the minimum value in the list. <ANY means less than the maximum value in the list. ALL: Compares value to every value returned by the subquery. >ALL means more than the maximum value in the list. <ALL means less than the minimum value in the list. Note: Also you can use the EXIST operator to check if a value is in a list returned by a correlated subquery.

Example of IN:

43

Example of ANY:

Example of ALL:

44

MULTIPLE COLUMN SUBQUERY A multiple-column subquery is one that returns one or more row from the inner SELECT statement to the outer SQL statement. What do you mean by Correlated subquery? Sub-queries, or nested queries, are used to bring back a set of rows to be used by the parent query. Depending on how the subquery is written, it can be executed once for the parent query or it can be executed once for each row returned by the parent query. If the subquery is executed for each row of the parent, this is called a correlated subquery. A correlated subquery can be easily identified if it contains any references to the parent subquery columns in its WHERE clause. Columns from the subquery cannot be referenced anywhere else in the parent query. The following example demonstrates a non-correlated subquery. E.g. Select * From CUST Where '10/03/1990' IN (Select ODATE From ORDER Where CUST.CNUM = ORDER.CNUM) Nth highest salary Find out nth highest salary from EMP table? Using inline view Sql> SELECT MIN (sal) FROM (SELECT DISTINCT (sal) FROM EMP ORDER BY sal DESC) WHERE ROWNUM <= &N; Using Hirerchical query (LEVEL) Sql> SELECT LEVEL, MAX (SAL) FROM EMP WHERE LEVEL=&LEVEL_NO CONNECT BY PRIOR SAL>SAL GROUP BY LEVEL; Using co-related subquery Sql > SELECT distinct (A.Sal) FROM EMP A WHERE &N = (SELECT count (distinct (B.sal)) FROM EMP B WHERE A.sal<=B.sal); Using rank

How can I get the Ename of the employee from EMP table having nth highest salary? SQL> SELECT ENAME FROM EMP WHERE SAL= (SELECT distinct (A.Sal) FROM EMP A WHERE &N = (SELECT count (distinct (B.sal)) FROM EMP B WHERE A.sal<=B.sal));

45

VIEW
What is a VIEW? A view is a virtual table, based on one or more tables. That means view does not really exist in its own right but is instead derived from one or more underlying base table. In other words, there is no stored file that direct represents the view instead a definition of view is stored in data dictionary. Advantages (why use view?): View restricts access to the data because the view can display selective row & columns from the table. View can be used to make simple queries to retrieve the result of complicated queries. View provides data independence for ad-hoc users and application programs. One view can be used to retrieve data from several tables. View provides groups of user access to data according to their particular criteria. Join columns from multiple tables so that they look like a single table. Aggregate information instead of supplying details. Types of view: SIMPLE VIEW is one that: Derives data from one table. Doesnt contain functions or group functions. Can perform DML operations through the view. COMPLEX VIEW is one that: Derives data from multiple tables. Can contain functions or group functions. Can not always perform DML operations through the view. CREATING A SIMPLE VIEW: Syntax: CREATE [OR REPLACE] [FORCE|NOFORCE] VIEW <view_name> (alias,) AS subquery WITH CHECK OPTION CONSTRAINT constraint WITH READ ONLY [CONSTRAINT constraint; Syntax Definition

46

OR REPLACE FORCE NOFORCE Alias Sub query WITH CHECK OPTION Constraint WITH READ ONLY

Recreates the view if it already exists. Creates the view regardless of whether or not the base table exists. Creates the view only if the base table exists (This is default). Specifies names for the expressions selected by the views query. The number of aliases must match the number of expressions selected by the view. Complete select statement. Specifies that only rows accessible to the view can be inserted or updated. Name assigned to the CHECK OPTION constraint. Ensures that no DML operations can be performed on this view.

Example: Sql > CREATE VIEW emp_vu1 AS SELECT empno, ename, sal, job FROM emp WHERE job=CLERK; An ORDER BY clause cannot be used while creating a view. CREATING A SIMPLE VIEW by using column aliases in the subquery: Example: Sql > CREATE VIEW emp_vu2 AS SELECT empno employee_id, ename emp_name, sal*5 ann_sal, job emp_job FROM emp WHERE job=CLERK; Sql > CREATE VIEW emp_vu3 (employee_id, emp_name, ann_sal, emp_job ) AS SELECT empno, ename, sal*5, job FROM emp WHERE job=CLERK; Retrieving data from a view: Example: Sql > SELECT * FROM emp_vu2; Sql > SELECT employee_id, emp_name, ann_sal, emp_job FROM emp_vu2; Modifying a view: Sql > CREATE OR REPLACE VIEW emp_vu3 (Emp_id, ename, annsal, e_job) AS SELECT empno, ename, sal*5, job FROM emp WHERE job=CLERK; CREATING A COMPLEX VIEW: Sql > CREATE VIEW emp_dept_vu4 (name, deptno, dname) AS SELECT e.ename, d.deptno,d.dname FROM emp e, dept d WHERE e.deptno=d.deptno; Sql > CREATE VIEW dept_vu5 (name, minsal, maxsal, avgsal) AS SELECT d.department_name, MIN(e.salary), MAX(e.salary), AVG(e.salary) FROM employees e, departments d WHERE e.department_id=d. department_id GROUP BY d.department_name; RULES FOR PERFORMING DML OPERATIONS ON A VIEW: You cannot REMOVE a row if the view contains: Group functions. A GROUP BY clause.

47

The DISTINCT keyword. The pseudo column ROWNUM keyword. You cannot MODIFY data in a view if the view contains: Group functions. A GROUP BY clause. The DISTINCT keyword. The pseudo column ROWNUM keyword. Columns defined by expressions. You cannot ADD data through a view if the view contains: Group functions. A GROUP BY clause. The DISTINCT keyword. The pseudo column ROWNUM keyword. Columns defined by expressions. NOT NULL columns in the base tables that are not selected by the view. Using the WITH CHECK OPTION clause: To ensure that DML on the view stays within the domain of the VIEW by using the WITH CHECK OPTION clause. Example: Sql > CREATE OR REPLACE VIEW emp_vu6 AS SELECT * FROM emp WHERE deptno=30 WITH CHECK OPTION CONSTRAINT emp_vu6_ck; Any attempt to change the deptno for any row in the view fails because it violates the WITH CHECK OPTION constraint. WITH READ ONLY option: WITH READ ONLY option ensures that no DML operations can do with view. Any attempt to perform a DML on any row in the view results in an Oracle server error. Example: Sql > CREATE OR REPLACE VIEW emp_vu3 (emp_id, ename, annsal, e_job ) AS SELECT empno, ename, sal*5, job FROM emp WHERE job=CLERK WITH READ ONLY; Sql > DELETE FROM emp_vu3 WHERE emp_id=7369; ERROR at line 1: ORA-01752: cannot delete from view without exactly one key-preserved table. REMOVING A VIEW: A view can be removed with out loosing data because a view is based on underlying tables in the database. Syntax: DROP VIEW <view_name>; Can you update the data in a view? A view is created by joining one or more tables. When you update record(s) in a view, it updates the records in the underlying tables that make up the view. So, you can update the data in a view providing you have the proper privileges to the underlying tables. Does the view exist if the table is dropped from the database? Yes, in Oracle, the view continues to exist even after one of the tables (that the view is based on) is dropped from the database. However, if you try to query the view after the table has been dropped, you will

48

receive a message indicating that the view has errors. If you recreate the table (that you had dropped), the view will again be fine. MATERIALISED VIEW A materialized view is a database object that contains the results of a query. The FROM clause of the query can name tables, views, and other materialized views. Collectively these objects are called master tables (a replication term) or detail tables (a data warehousing term). This reference uses "master tables" for consistency. The databases containing the master tables are called the master databases. For replication purposes, materialized views allow you to maintain copies of remote data on your local node. Oracle provides materialized views to store copies (replica) of data or aggregations. Materialized views can be used to replicate all or part of a single table, or to replicate the result of a query against multiple tables; refreshes of the replicated data can be done automatically by the database at time intervals that you specify. Materialized views are copies (also known as replicas) of data, based upon queries.

Materialized view is the view that is physically present in the database. The materialized view is a table whose contents are periodically refreshed using a query against a remote

table. Since when we are woring with various databases running in different system. So sometime we may needed to fetch some records from the remote location so it may quit expensive in terms of resource of fetching data directly from remote location. To minimize to response time and to increase the throughput we may create the copy to that on local database by using data from remote database. This duplicate copy is Known as materialized view which may be refreshed as per as requirement as option available with oracle such as fast complete and refresh. Materialized View stores both - definition of the view and rows resulted from execution of the view. Main disadvantage of materialized view is that its contents get outdated when underlying base table is modified. U can refresh Materialized View using DBMS_MVIEW.REFRESH

Why Use Materialized Views? You can use materialized views to achieve one or more of the following goals:

Ease Network Loads: If one of your goals is to reduce network loads, then you can use materialized views to distribute your corporate database to regional sites. Instead of the entire company accessing a single database server, user load is distributed across multiple database servers. Through the use of multitier materialized views, you can create materialized views based on other materialized views, which enables you to distribute user load to an even greater extent because clients can access materialized view sites instead of master sites. To decrease the amount of data that is replicated, a materialized view can be a subset of a master table or master materialized view. Create a Mass Deployment Environment Deployment templates allow you to precreate a materialized view environment locally. You can then use deployment templates to quickly and easily deploy materialized view environments to support

49

sales force automation and other mass deployment environments. Parameters allow you to create custom data sets for individual users without changing the deployment template. This technology enables you to roll out a database infrastructure to hundreds or thousands of users. Enable Data Subsetting Materialized views allow you to replicate data based on column- and row-level subsetting, while multimaster replication requires replication of the entire table. Data subsetting enables you to replicate information that pertains only to a particular site. For example, if you have a regional sales office, then you might replicate only the data that is needed in that region, thereby cutting down on unnecessary network traffic. Enable Disconnected Computing Materialized views do not require a dedicated network connection. Though you have the option of automating the refresh process by scheduling a job, you can manually refresh your materialized view ondemand, which is an ideal solution for sales applications running on a laptop. For example, a developer can integrate the replication management API for refresh on-demand into the sales application. When the salesperson has completed the day's orders, the salesperson simply dials up the network and uses the integrated mechanism to refresh the database, thus transferring the orders to the main office.

Types of MATERIALISED VIEW A materialized view can be read-only, updatable, or writeable. Users cannot perform data manipulation language (DML) statements on read-only materialized views, but they can perform DML on updatable and writeable materialized views. Read-Only Materialized Views You can make a materialized view read-only during creation by omitting the FOR UPDATE clause or disabling the equivalent option in the Replication Management tool. Read-only materialized views use many of the same mechanisms as updatable materialized views, except that they do not need to belong to a materialized view group. In addition, using read-only materialized views eliminates the possibility of a materialized view introducing data conflicts at the master site or master materialized view site, although this convenience means that updates cannot be made at the remote materialized view site. The following is an example of a read-only materialized view: Sql> CREATE MATERIALIZED VIEW hr.employees AS SELECT * FROM hr.employees@orc1.world;

Updatable Materialized Views


You can make a materialized view updatable during creation by including the FOR UPDATE clause or enabling the equivalent option in the Replication Management tool. For changes made to an updatable materialized view to be pushed back to the master during refresh, the updatable materialized view must belong to a materialized view group. Updatable materialized views enable you to decrease the load on master sites because users can make changes to the data at the materialized view site. The following is an example of an updatable materialized view: Sql> CREATE MATERIALIZED VIEW hr.departments FOR UPDATE AS SELECT * FROM hr.departments@orc1.world; Note:

Do not use column aliases when you are creating an updatable

materialized view. Column aliases cause an error when you attempt to add the materialized view to a materialized view group using the CREATE_MVIEW_REPOBJECT procedure.

50

An updatable materialized view based on a master table or master materialized view that has defined column default values does not automatically use the master's default values. CASCADE constraint.

Updatable materialized views do not support the DELETE Writable Materialized Views
A writeable materialized view is one that is created using the FOR UPDATE clause but is not part of a materialized view group. Users can perform DML operations on a writeable materialized view, but if you refresh the materialized view, then these changes are not pushed back to the master and the changes are lost in the materialized view itself. Writeable materialized views are typically allowed wherever fast-refreshable read-only materialized views are allowed. Note: Most of the documentation about materialized views only refers to read-only and updatable materialized views because writeable materialized views are rarely used.

SEQUENCE
A SEQUENCE is a user created database schema object that is used to generate UNIQUE SEQUENTIAL value (integer). SEQUENCE is used to create a PRIMARY key value & UNIQUE key value, which must be unique for each row. The SEQUENCE is generated and incremented (decremented) by an internal Oracle routine. This can be a timesaving object because it can reduce the amount of application code needed to write a sequence-generating routine. SEQUENCE numbers are stored and generated independently of tables. Therefore, the same SEQUENCE can be used for multiple tables. A SEQUENCE can be shared by multiple users to generate unique integer. CREATING A SEQUENCE: Syntax: CREATE SEQUENCE <sequence_name> INCREMENT BY n START WITH n MAXVALUE n | NOMAXVALUE MINVALUE n | NOMINVALUE CACHE n | NOCACHE CYCLE | NOCYCLE ORDER | NOORDER;

51

Sequence_name INCREMENT BY n

START WITH n MAXVALUE n NOMAXVALUE MINVALUE n NOMINVALUE CYCLE NOCYCLE CATCHE n NOCATCHE ORDER NOORDER

Is the name of the sequence generator. Specifies the interval between sequence numbers, where n is an integer and it can be either +ve or -ve but not zero (0). If the value is +ve then it is incremented sequence else it is decremented sequence. If this clause is omitted, the sequence increments by 1. Specifies the first sequence number to be generated. If this clause is omitted, the sequence starts with 1. Specifies the maximum sequence value. Specifies a maximum value of 10^27 for an ascending sequence and -1 for a descending sequence (This is the default option). Specifies the minimum sequence value. Specifies a minimum value of 1 for an ascending sequence and (10^26) for a descending sequence (This is the default option). Specifies whether the sequence continues to generate values after reaching its maximum or minimum value. Specifies that the sequence cannot generate more value after the target limit. It is default option Specifies how many values the Oracle server pre-allocates and keeps in memory (By default, the Oracle server catches 20 values). Specifies the value of a sequence is not pre-allocated. Guarantees the sequence numbers to be generated in the order of request. It is bydefault Does not guarantee the sequence number with order.

Example1: CREATION OF TABLE WITH PRIMARY KEY: SQL > CREATE TABLE sample ( SAMPLE_ID NUMBER(4) CONSTRAINT SAMP_PK PRIMARY KEY, SAMPLE_NAME VARCHAR2(25), SAMPLE_DATE DATE ); CREATION OF INCREMENTAL SEQUENCE WITH NOCYCLE: SQL > CREATE SEQUENCE sample_seq INCREMENT BY 5 START WITH 1 MAXVALUE 30 NOCACHE NOCYCLE; ACTIVATING AND ATTACHING THE SEQUENCE TO A TABLE: SQL > INSERT INTO sample (SAMPLE_ID, SAMPLE_NAME, SAMPLE_DATE) VALUES (sample_seq.NEXTVAL, S1, 01-JAN-08); Example2: CREATION OF TABLE WITH OUT PRIMARY KEY: SQL > CREATE TABLE sample ( SAMPLE_ID NUMBER(4), SAMPLE_NAME VARCHAR2(25), SAMPLE_DATE DATE ); CREATION OF INCREMENTAL SEQUENCE WITH CYCLE: SQL > CREATE SEQUENCE sample_seq INCREMENT BY 10

52

START WITH 1 MAXVALUE 60 NOCACHE CYCLE; ACTIVATING AND ATTACHING THE SEQUENCE TO A TABLE: SQL > INSERT INTO sample (SAMPLE_ID, SAMPLE_NAME, SAMPLE_DATE) VALUES (sample_seq.NEXTVAL, S1, 01-JAN-08); Example3: CREATION OF TABLE WITH PRIMARY KEY: SQL > CREATE TABLE sample ( SAMPLE_ID NUMBER(4) CONSTRAINT SAMP_PK PRIMARY KEY, SAMPLE_NAME VARCHAR2(25), SAMPLE_DATE DATE ); CREATION OF DECREMENTAL SEQUENCE WITH NOCYCLE: SQL > CREATE SEQUENCE sample_seq INCREMENT BY -2 START WITH 0 MAXVALUE 10 MINVALUE 0 NOCACHE NOCYCLE; ACTIVATING AND ATTACHING THE SEQUENCE TO A TABLE: SQL > INSERT INTO sample(SAMPLE_ID, SAMPLE_NAME, SAMPLE_DATE) VALUES (sample_seq.NEXTVAL, S1, 01-JAN-08); GUIDELINES FOR ALTERING A SEQUENCE: The ALTER privileges should be available. Only the feature sequence numbers are affected by the ALTER SEQUENCE statements. The START WITH options cant be changed using ALTER SEQUENCE. To change the START WITH option, drop the SEQUENCE and then recreate the SEQUENCE. Some validation performed, i.e. A NEW MAXVALUE cant be imposed that is less than the current SEQUENCE number. MODIFYING A SEQUENCE: The ALTER command can be used to change the present status of a SEQUENCE. The ALTER SEQUENCE command can be used to change. Increment value. Maximum value. Minimum value. Cycle option. Cache option. Syntax: SQL > ALTER SEQUENCE <sequence_name> INCREMENT BY n MAXVALUE n | NOMAXVALUE MINVALUE n | NOMINVALUE CACHE n | NOCACHE

53

CYCLE | NOCYCLE; Example: SQL > ALTER SEQUENCE sample_seq INCREMENT BY 7 MAXVALUE 40 MINVALUE 5 CACHE NOCYCLE; CONFIRMING SEQUENCE: All SEQUENCES that have been created are documented in the data dictionary. The data dictionary in which the information of SEQUENCES are stored in USER_OBJECTS. The settings of the sequence can be confirmed by selecting on USER_SEQUENCES.

Example: SQL > SELECT * FROM USER_OBJECTS WHERE OBJECT_TYPE='SEQUENCE'; SQL > SELECT sequence_name, min_value, max_value, increment by, last_number FROM user_sequences;

VIEWING THE CURRENT & NEXT VALUE OF A SEQUENCE:


Syntax: SEQUENCENAME.CURRVAL Returns the current value of the sequence. SEQUENCENAME.NEXTVAL Returns the current value of the sequence. Example: SQL > SELECT sample_seq.CURRVAL FROM dual; SQL > SELECT sample_seq.NEXTVAL FROM dual;

For viewing SEQUENCE on other schema


SCHEMANAME.SEQUENCENAME.CURRVAL SCHEMANAME.SEQUENCENAME.NEXTVAL To refer to the CURRENT or NEXT value of a SEQUENCE in the SCHEMA of another user, use the following privileges. SELECT OBJECT PRIVILEGE

54

SELECT ANY SEQUENCE For viewing SEQUENCE on REMOTE database


SCHEMANAME.SEQUENCENAME.CURRVAL@DBLINK SCHEMANAME.SEQUENCENAME.NEXTVAL@DBLINK

DROPPING AN EXISTING SEQUENCE:


Syntax: SQL > DROP SEQUENCE <sequence_name>; Example: SQL > DROP SEQUENCE sample_seq;

PSEUDO COLUMN
Pseudo column behaves like a table column, but is not actually stored in a table. CURRVAL This pseudo column is applied upon the SEQUENCE schema object. It returns the CURRENT value of a sequence. It can be used only in: The SELECT list of a SELECT statement. The VALUES clause of an INSERT statement. The SET clause of an UPDATE statement. Restriction: It cannot be used in: Subquery View DISTINCT keyword WHERE clause

55

NEXTVAL This pseudo column is applied upon the SEQUENCE schema object. It increments the sequence & returns the NEXT value of a sequence. It can be used only in: The SELECT list of a SELECT statement. The VALUES clause of an INSERT statement. The SET clause of an UPDATE statement. Restriction: It cannot be used in: Subquery View DISTINCT keyword WHERE clause GROUP BY clause ORDERBY clause SET operator (UNION, INTERSECT, MINUS). CREATE/ ALTER table CHECK constraint LEVEL

GROUP BY clause ORDERBY clause SET operator (UNION, INTERSECT, MINUS). CREATE/ ALTER table CHECK constraint

This pseudo column return 1 fro ROOT node, 2 for a CHILD ROOT & so on.
To establish the hierarchical relationship with LEVEL we need START WITH clause: It specifies the ROOT rows of the hierarchy. CONNECT BY clause: It is used to specify the relationship between parent & child rows of the hierarchy.

56

ROWID This pseudo column returns a row address for each row stored in the database ROWID values contain information necessary to locate the physical area of the database row. The row belongs to which data block in the data file. The row belongs to which row in the data block (first file 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 same ROWID. The data type of the values belonging to the ROWID is of ROWID data type. It can not be INSERTED, UPDATED & DELETED manually. It can be used in SELECT & WHERE clause. USED To: Fastest accessing a single row from the database. UNIQUE identifiers for a row in a table. ROWNUM For each row returned by a query, the ROWNUM pseudo column returns a number indicating the order in which oracle selects the rows from a set of joined rows or non-joined rows. The 1st row has ROWNUM of 1, 2nd has 2 & so on. When ORDER BY clause follows a ROWNUM, the rows will be re-ordered. It is generally used to query TOP N records in a table. The right way to use ROWNUM is: SQL> SELECT Empno, Ename, Sal, ROWID FROM (SELECT * from Emp ORDER BY Sal) WHERE ROWNUM<5;

57

58

INDEXING
An index: Is a schema object Is used by the Oracle server to speed up the retrieval of rows by using a pointer. It is used for performing faster access or faster search to the database based on the key value called index value. Can reduce disk I/O by using a rapid path access method to locate data quickly Is independent of the table it indexes Is used and maintained automatically by the Oracle server Indexing is a technique for determining how quickly specific data can be found. An index is an ordered list of the contents of a column, (or a group of columns) of a table. When an index is created, the data of the column(s) on which index created appear in ascending order.

59

When the user defines a primary key or a unique key constraint at column or table level, the oracle engine automatically creates a unique index on the primary key or unique key column(s).

An Index is an optional structure associated with a table to have direct access to rows, which can be created to increase the performance of data retrieval. Index can be created on one or more columns of a table.

How Indexes are created?

Automatically: A unique index is created automatically when you define a PRIMARY KEY or UNIQUE
constraint in a table definition. Manually: Users can create nonunique indexes on columns to speed up access to the rows.

When to Create an Index? You should create an index if: A column contains a wide range of values A column contains a large number of null values One or more columns are frequently used together in a WHERE clause or a join condition The table is large and most queries are expected to retrieve less than 2 to 4 percent of the rows When Not to Create an Index? It is usually not worth creating an index if: The table is small The columns are not often used as a condition in the query Most queries are expected to retrieve more than 2 to 4 percent of the rows in the table The table is updated frequently The indexed columns are referenced as part of an expression How an Index Works An index entry includes a pointer to the actual data row, which is the fastest way to retrieve a data row. Once the Oracle database has used the index to identify target rows, the pointer is used to retrieve the row. Keys The information that makes up the content of an index is known as a key. A key is a logical entity that identifies a particular index entry. Confirming Indexes The USER_INDEXES data dictionary view contains the name of the index and its uniqueness. The USER_IND_COLUMNS view contains the index name, the table name, and the column name. What are the different types of indexes? DUPLICATE INDEX: Index that allow duplicate values for the index columns. UNIQUE INDEX: Index that allow unique values for the index columns. SIMPLE INDEX: An index created on a single column of a table is called a simple index. Duplicate index: Syntax: CREATE INDEX <index_name> ON <table_name> (<column_name>); Example: Sql > CREATE INDEX idx_emp ON emp (ename); Unique index: Syntax:

60

CREATE UNIQUE INDEX <index_name> ON <table_name> (<column_name>); Example: Sql > CREATE UNIQUE INDEX idx_emp ON emp (ename); COMPOSITE INDEX: An index created on more than one column of a table is called a composite index. Duplicate index: Syntax: CREATE INDEX <index_name> ON <table_name> (<column_name1>,<column_name2>); Example: Sql > CREATE INDEX idx_emp ON emp (ename,job); Unique index: Syntax: CREATE UNIQUE INDEX <index_name> ON <table_name> (<column_name1>,<column_name2>); Example: Sql > CREATE UNIQUE INDEX idx_emp ON emp (ename,job);

B*Tree indexes:
The default type of index used in an Oracle database is the B-tree index. A B-tree index is designed to provide both rapid access to individual rows and quick access to groups of rows within a range. The B-tree index does this by performing a succession of value comparisons. Each comparison eliminates many of the rows in the potential result set from consideration, which can significantly improve query performance. They are similar in implementation to a binary search tree. Their goal is to minimize the amount of time Oracle spends searching for data. How It Works A B-tree index has three basic components: 1. A root page, which is the entry point to the index structure. 2. one or more levels of branch block 3. Leaf node/ leaf block, the lowest level of the tree. A single-level index will only have a root page and no levels of branch block. The lowest level blocks in the tree, called leaf nodes or leaf blocks, contain every indexed key and a rowid that points to the row it is indexing. The interior blocks, above the leaf nodes, are known as branch blocks. They are used to navigate through the structure. For example, if we wanted to find the value 42 in the index, we would start at the top of the tree and go to the left. We would inspect that block and discover we needed to go to the block in the range 42..50. This block would be the leaf block and point us to the rows that contained the number 42. It is interesting to note that the leaf nodes of the index are actually a doubly linked list. Once we find out where to start in the leaf nodes (i.e., once we have found that first value), doing an ordered scan of values (also known as an index range scan) is very easy. We dont have to navigate the structure any more; we just go forward or backward through the leaf nodes as needed. That makes satisfying a predicate, such as the following, pretty simple: Where x between 20 and 30 Oracle finds the first index leaf block that contains the lowest key value that is 20 or greater, and then it just walks horizontally through the linked list of leaf nodes until it finally hits a value that is greater than 30. There really is no such thing as a nonunique entry in a B*Tree index. In a nonunique index, Oracle simply stores the rowid by appending it to the key as an extra column with a length byte to make the key unique. For example, an index such as CREATE INDEX I ON T(X,Y) is conceptually CREATE UNIQUE INDEX I ON T(X,Y,ROWID). In a unique index, as defined by you, Oracle does not

61

add the rowid to the index key. In a nonunique index, you will find that the data is sorted first by index key values (in the order of the index key) and then by rowid ascending. In a unique index, the data is sorted only by the index key values. One of the properties of a B*Tree is that all leaf blocks should be at the same level in the tree. This level is also known as the height of the index, meaning that any traversal from the root block of the index to a leaf block will visit the same number of blocks. That is, to get to the leaf block to retrieve the first row for a query of the form "SELECT INDEXED_COL FROM T WHERE INDEXED_COL =: X" will take the same number of I/Os regardless of the value of: X that is used. In other words, the index is height balanced. Most B*Tree indexes will have a height of 2 or 3, even for millions of records. This means that it will take, in general, two or three I/Os to find your key in the indexwhich is not too bad. Note Oracle uses two terms with slightly different meanings when referring to the number of blocks involved in traversing from an index root block to a leaf block. The first is HEIGHT, which is the number of blocks required to go from the root block to the leaf block. The HEIGHT value can be found from the INDEX_STATS view after the index has been analyzed using the ANALYZE INDEX <name> VALIDATE STRUCTURE command. The other is BLEVEL, which is the number of branch levels and differs from HEIGHT by one (it does not count the leaf blocks). The value of BLEVEL is found in the normal dictionary tables such as USER_INDEXES after statistics have been gathered. 0-300

0-100

101-200 Branch Nodes

201-300

0-50

51-100

101-150

151-200

201-250

251-300

0-10 Rowid

11-20 Rowid

21-30 Rowid

31-40 Rowid

41-50 Rowid

Leaf Nodes

Each branch page contains a number of entries, each of which points to either another level of branch pages or a leaf page. Each entry has the maximum value for the next level of pages. For instance, if a request to the index shown in Figure were to ask for a value of aaron, the search would branch to the left at the root page, to the left again at the first level of branch pages, and, using the second level of branch pages, to the leftmost leaf page. The leaf pages contain the actual values for the index and a ROWID that points to the row the index entry represents. An index leaf page also has a pointer to the next and previous index leaf pages, which makes it easy to walk through the index to get a series of rows in a range of values. As leaf pages fill up, they will split into two leaf pages and the branch pages will be modified accordingly. Occasionally, a branch page may also have to be split. The idea behind the B-tree index is to allow the Oracle database to make a series of decisions about the location of a potential index entry. Each decision effectively eliminates half of the remaining potential index entries, which makes finding individual rows quick and efficient. When this performance improvement is added to the virtues of pre-sorting the entries, you can see how a B-tree index can help reduce I/O operations and improve performance.

62

Root Node

A-G

H-P

Branch Nodes

Q-Z

A-C
Ajay Anil Babu Chinu

D-E

F-G

H-J

K-M

N-P

Q-S

T-V

W-Z

Leaf Nodes

A B*Tree index can not be un balanced because it uses the sequential key. When Should You Use a B*Tree Index?

As the means to access rows in a table: You will read the index to get to a row in the table.

Here you want to access a very small percentage of the rows in the table. As the means to answer a query: The index contains enough information to answer the entire querywe will not have to go to the table at all. The index will be used as a thinner version of the table.

Index organized tables (IOT):


Index allows users to get at data with less I/O than performing a complete table scan in many cases. Typically, your queries will require information beyond that found in the index, so once the Oracle database has selected the appropriate index entry, the database still has to use the pointer in the index entry to retrieve the extra information in the row. Although access through the pointer in an index entry is the fastest way to access a row in a table, the retrieval still requires some overhead. Eliminating this overhead could speed up a query even more & thats why the index-organized table. This structure allows Oracle to keep the entire table in an index structure, so the same efficiencies offered by an index are used to retrieve all of the data in the row. An Index organized tables stores both key values and non-key values within its pages. Oracle provides an overflow option that allows you to indicate that some non-key values are stored outside of the index structure, based on storage room available in the actual index block. Because an IOT is organized around a primary key value, you must have a primary key defined for an IOT. Because the IOT does not normally use an index value pointing to the same value in a data row, the storage requirements for the table and index are reduced. You can have additional indexes on an IOT. These indexes can be either standard B-treebased indexes or bitmap indexes and work in the same way as an index on a normal table structure. These additional indexes use a logical row ID, rather than a physical row ID like other index types, to access the data rows in the table. If an IOT row uses the overflow option, the physical row ID to the overflow area is part of the IOT index entry.

63

There are a number of restrictions on the use of IOTs, such as the fact that an IOT cannot contain columns with LONG or any of the varieties of LOB data types. In addition, an IOT cannot be stored in a cluster.

INDEX CLUSTER (B*Tree cluster indexes):


Oracle normally stores the rows added to a table in the order that rows are added to the table, rather than in any particular logical order. A cluster is a way of storing table rows so that their actual storage is related to the logical values in some of the columns. A cluster groups data from one or more tables together in the same data blocks, organized by a cluster key. A cluster can hold either rows from a single table or related rows from more than one table. The following figure shows a block from a clustered table that contains rows from the DEPT table and the EMP table. The cluster is organized using the cluster key, a value that is shared by both tables. In this example, the DEPT_NO column is the cluster key, so the same data block contains the EMP rows that have the same DEPT_NO as a row of the DEPT table. DEPT_NO = 10 DEPT_NO = 10 DEPT_NO = 10 DEPT_NO = 10 DEPT_NO = 10 DEPT_NO = 10 DEPT_NO = 10 DEPT row EMP row This type of organization makes sense if you are frequently accessing the same data together. When Oracle fetches a data block for the DEPT value, the related EMP rows have also been retrieved. A cluster also reduces storage requirements, since the value of the cluster key is only stored once, rather than in both the DEPT and EMP table. To implement a cluster, you have to first create a cluster and then add tables to the cluster. There are limitations to using a cluster, such as the fact that you cannot have partitions in a cluster or do direct-path loads into a cluster. Since each data block holds the rows for tables with the same cluster key, using a cluster that leaves a lot of empty space in the block can waste space and decrease performance. By default, Oracle will only store the rows for one cluster key value in each data block, although you can change this behavior with a parameter when you create the table. You should also only use a cluster when the values for the cluster key are variedusing a key with an extremely low cardinality can negate the value of the cluster, since Oracle will be able to find the first block of the cluster, but then have to go through the same random retrieval for the rest of the blocks for the value. In addition, clusters are only appropriate when the numbers of rows for the different values for the cluster key are similar in size. If the number of rows for some values are much greater than the number for others, the cluster will be skewed, which will decrease the effectiveness of the cluster by adding a lot of empty space on the less populated values and reducing the efficiency of full table scans.

Hash Cluster:
A cluster groups data from one or more tables together in the same data blocks, organized by a cluster key. Retrieving the data is faster because the Oracle database does not have to re-fetch data blocks to get data from related cluster key values. A request for a cluster still goes through the process of locating a value for the cluster key and then fetching blocks. But what if this index retrieval could be eliminated also? Oracle supports another table organization called a hash cluster. This type of table uses the result of a hash function on the cluster key to determine where to store and retrieve the row data in

64

the cluster. A hash cluster lets Oracle find the blocks that contain the rows in the cluster by performing a logical function rather than I/O operations. Oracle can calculate a value and go straight to data blocks containing rows for that value. This capability substitutes some CPU activity for some I/O, which is frequently a good trade-off in terms of overall performance. For a hash cluster to provide optimal value, you should be able to estimate the total number of hash values when you create the cluster, so Oracle can pre-allocate all the space required for each of the values for the hash key in an efficient way. If the size of the hash key entries grows beyond the initial estimate, the performance benefit of the organization is decreased as additional blocks are added to the cluster. You can have a hash cluster that only contains a single table. This type of cluster lets Oracle access rows in the table directly once the hash value is calculated, which reduces I/O and can help performance in appropriate situations, such as a table used for lookups. Oracle Database 10g also supports a sorted hash cluster. This organization stores data based on a hash value, but also in the order that the data was entered. Some types of data, such log records from a phone system, are very appropriate for a sorted hash cluster. In this example, the user would typically want to access rows by customer ID, the cluster key, which could be rapidly retrieved with a hash value, but then want to access the data for that customer based on when it was entered. A sorted hash cluster is not appropriate for all scenarios, but the right situation can produce large performance benefits.

Descending indexes:
Descending indexes were introduced in Oracle8i to extend the functionality of a B*Tree index. They allow for a column to be stored sorted in descending order (from big to small) in the index instead of ascending order (from small to big). Prior releases of Oracle, pre-Oracle8i, always supported the DESC (descending) keyword syntactically, but basically ignored itit had no effect on how the data was stored or used in the index. In Oracle8i and above, however, the DESC keyword changes the way the index is created and used. It is useful, when you have a mixture of columns, and some are sorted ASC (ascending) and some DESC (descending). Reverse key indexes: A reverse key index is designed to address a very specific situation. The situation begins with an index based on an ascending value, such as a sequence. With this key, all new rows will be inserted into the rightmost index leaf block, since each new value is the highest value. If there are a lot of inserts going on at the same time, with all of them reaching to write to the same index leaf, you could end up with performance degradation caused by contention issues. These issues could be made even more apparent in an environment like the old version of clustering, Oracle Parallel Server, which extracted a penalty for concurrent, writes to the same data block. To avoid this situation, Oracle introduced the reverse key index. This index automatically takes the values in a key and reverses their order. The effect would spread sequential key values around, which would, in turn, end up placing them in different index leaf blocks and potentially avoiding some of the contention problem. NORMAL INDEX REVERSE INDEX C00001 00001C C00002 00002C C00003 00003C Since a reverse index does not store values in sorted order, range scans cannot be done with a reverse index. In addition, a reverse key index can cause index blocks to be less compact than standard B-tree indexes. It reverses each byte of the column being indexed while keeping the column order. It helps to avoid Performance degradation in indexes where modifications to the index are concentrated on a small set of blocks. Syntax: CREATE INDEX <index_name> ON <table_name> (<column_name>) REVERSE;

65

Example: Sql > CREATE INDEX idx_emp ON emp (ename) REVERSE; A REVERSE KEY index can be rebuilt into a normal index using the keywords REBUILT NOREVERSE. Syntax: ALTER INDEX <index_name> REBUILT NOREVERSE; Example: Sql > ALTER INDEX idx_emp REBUILT NOREVERSE; A normal index cannot be rebuilt as a reverse key index.

Bitmap indexes: (Features of Oracle 10g Enterprise Edition)


A bitmap index is different from other indexes, which have an entry for each non-NULL row in the table. In a bitmap index, each value has a bitmap, with each bit in the bitmap pointing to each row that contains that value. The bitmap index is used when a query requires selection on several different dimensions. The Oracle database server can perform bitwise AND or OR operations on each bitmap index, which are extremely fast. Compare this with the alternative of locating each value on multiple dimension indexes, and then doing a complex join. Although a bitmap index could also be used with any column or set of columns with a low number of distinct values, or cardinality, in practice bitmap indexes are used almost exclusively with data warehouses. There is also a good reason not to use a bitmap index with a table used for online transaction processing (OLTP). Whenever inserts are done into a table, any index blocks affected have to be locked for the duration of the transaction, just as a data block affected would have to be. In order to use a bitmap index, Oracle has to decompress the values, which takes some time and makes them inappropriate for OLTP scenarios, which can have thousands of small transactions simultaneously. This type of index is designed for a specific purposeto use in a data warehouse. The advantage of using BITMAP indexes is greatest for low cardinality columns i.e. columns in which the number of distinct value is small compared to the number of rows in the table.

To help tune queries that use nonselective columns in their limiting conditions, you can use
bitmap indexes. Bitmap indexes should only be used if the data is infrequently updated, because they add to the cost of all data-manipulation transactions against the tables they index.

Bitmap indexes should not be used for tables involved in online transaction-processing
applications due to the internal mechanisms Oracle uses to maintain them. Restrict their usage to tables involved in batch transactions.

Bitmap indexes are appropriate when nonselective columns are used as limiting conditions in

a query. For example, if there are very few distinct Rating values in a very large BOOKSHELF table, you would not usually create a traditional B*-tree index on Rating, even if it is commonly used in where clauses. However, Rating may be able to take advantage of a bitmap index.

Internally, a bitmap index maps the distinct values for the columns to each record. For this

example, assume there are five Rating values (1, 2, 3, 4, and 5) in a very large BOOKSHELF table. Because there are five Rating values, there are five separate bitmap entries for the Rating bitmap index. If the first five rows in the table have a Rating value of 1, and the next five have a Rating value of 2, then the Rating bitmap entries would resemble those shown in the following listing:

66

Rating bitmaps: 1: 1 1 1 1 1 0 0 0 0 0 2: 0 0 0 0 0 1 1 1 1 1 3: 0 0 0 0 0 0 0 0 0 0 4: 0 0 0 0 0 0 0 0 0 0 5: 0 0 0 0 0 0 0 0 0 0 Syntax: CREATE BITMAP INDEX <index_name> ON <table_name> (<column_name>); Example: SQL > CREATE BITMAP INDEX job_idx ON EMP (Job); Lets say we are creating a bitmap index on the JOB column in the EMP table as follows:

Representation of How Oracle Would Store the JOB-IDX Bitmap Index 1 2 3 4 5 6 7 8 9 10 11 ANALYST 0 0 0 0 0 0 0 1 0 1 0 CLERK 1 0 0 0 0 0 0 0 0 0 1 MANAGER 0 0 0 1 0 1 1 0 0 0 0 PRESIDENT 0 0 0 0 0 0 0 0 1 0 0 SALESMAN 0 1 1 0 1 0 0 0 0 0 0
Value/Row

12 0 1 0 0 0

13 1 0 0 0 0

14 0 1 0 0 0

No rows are null (bitmap indexes store null entries; the lack of a null entry in the index implies there are no null rows). If we wanted to count the rows that have the value MANAGER, the bitmap index would do this very rapidly. If we wanted to find all the rows such that the JOB was CLERK or MANAGER, we could simply combine their bitmaps from the index.
Value/Row
CLERK MANAGER

CLERK/ MANAGER

1 1 0 1

2 0 0 0

3 0 0 0

4 0 1 1

5 0 0 0

6 0 1 1

7 0 1 1

8 0 0 0

9 0 0 0

10 0 0 0

11 1 0 1

12 1 0 1

13 0 0 0

14 1 0 1

The bitmap Oracle stores with each key value are set up so that each position represents a rowid in the underlying table, if we need to actually retrieve the row for further processing. Queries such as the following: Select count (*) from EMP where job = 'CLERK' or job = 'MANAGER' will be answered directly from the bitmap index. A query such as this: Select * from EMP where job = 'CLERK' or job = 'MANAGER' On the other hand, will need to get to the table. Here, Oracle will apply a function to turn the fact that the ith bit is on in a bitmap, into a rowid that can be used to access the table. Bitmap join indexes: A bitmap join index can improve performance in a data warehouse even more than a bitmap index. The bitmap join index uses the same storage scheme as the bitmap index, but the bits in the index indicate how one table, generally the fact table, is joined to another table. Oracle9i introduced a new index type: the bitmap join index. Normally an index is created on a single table, using only columns from that table. A bitmap join index breaks that rule and allows you to index a given table using columns from some other table. In effect, this allows you to denormalize data in an index structure instead of in the tables themselves.

67

Consider the simple EMP and DEPT tables. EMP has a foreign key to DEPT (the DEPTNO column). The DEPT table has the DNAME attribute (the name of the department). The end users will frequently ask questions such as How many people work in sales?, Who works in sales?, Can you show me the top N performing people in sales? Note that they do not ask, How many people work in DEPTNO 30? They dont use those key values; rather, they use the human readable department name. Therefore, they end up running queries such as the following: SQL> select count (*) from EMP, dept Where emp.deptno = dept.deptno and dept.dname = 'SALES'; SQL> select emp.* from EMP, dept Where emp.deptno = dept.deptno and dept.dname = 'SALES'; Those queries almost necessarily have to access the DEPT table and the EMP table using conventional indexes. We might use an index on DEPT.DNAME to find the SALES row(s) and retrieve the DEPTNO value for SALES, and then using an INDEX on EMP.DEPTNO find the matching rows, but by using a bitmap join index we can avoid all of that. The bitmap join index allows us to index the DEPT.DNAME column, but have that index point not at the DEPT table, but at the EMP table. This is a pretty radical conceptto be able to index attributes from other tablesand it might change the way to implement your data model in a reporting system. You can, in effect, have your cake and eat it, too. You can keep your normalized data structures intact, yet get the benefits of denormalization at the same time. SQL> create bitmap index emp_bm_idx on EMP (d.dname) From EMP e, DEPT d Where e.deptno = d.deptno; This CREATE INDEX statement indexes the DEPT.DNAME column, but in the context of the EMP table. Function-based indexes: Function-based indexes, were introduced in Oracle 8i, provide powerful logical and performance benefits. This type of index can use a standard B-tree or bitmap index structure, but instead of using a column as the value for the key, the function-based index uses the results of a function as the value. Function-based indexes give us the ability to index computed columns and use these indexes in a query. In a nutshell, this capability allows you to have case-insensitive searches or sorts, search on complex equations, and extend the SQL language efficiently by implementing your own functions and operators and then searching on them. There are many reasons why you would want to use a function-based index, with the following chief among them:

They are easy to implement and provide immediate value. They can be used to speed up existing applications without changing any of their logic or queries.

By using the results of a function as the value in an index, you can avoid an alternative that could use up a whole lot of resources by having to perform the function on each potential row. For example, you want to allow users to return information from the EMP table sorted without having to worry about the case of the letters. Without a function-based index, your basic SELECT code would look like this: SELECT UPPER (ENAME) FROM EMP WHERE . . . ORDER BY UPPER (ENAME)

68

To return the values from this query, the Oracle database would have to perform the selection and then convert every ENAME column with the UPPER () function. This operation could consume quite a bit of resources, depending on the number of rows returned. SELECT UPPER (ENAME) FROM EMP WHERE UPPER (ENAME) = . . . . This is probably more likely; you want the user to be able to select an employee without caring about the case of the stored value. For this query, Oracle would have to perform the UPPER () function for each and every row in the table, just to see if the row passed the selection criteria. With a function-based index, the result of the UPPER () function is already stored in the index, so there is no need to perform the UPPER () function on the ENAME column. The function-based index stores the result of the function, eliminating the need to perform the function many, many times. The reduction in resources shown in the preceding example is a huge advantage, but not the only one provided by function-based indexes. This capability, coupled with function-based indexes, means that you can create some fairly sophisticated logic that can be utilized by the Oracle database without much query overhead. A columns index will not be used when the same column is expressed in an arithmetic expression or function in the WHERE clause. So when the same column is expressed in an arithmetic expression or function in the WHERE clause we use FUNCTION BASED INDEX. Syntax: CREATE INDEX <index_name> ON <table_name> (<function>(<column_name>)); Example: Sql > CREATE INDEX idx_emp ON emp (UPPER(ename)); The function cannot contain any aggregate function. A FUNCTION BASED INDEX cannot be created on which the object type contains a LOB, REF, or nested table.

Application domain indexes (Domain Indexes):


Domain indexes extend the indexing capabilities of the Oracle database even further than function-based indexes. You can create your own operators to perform specific logical functions and create new index types based on these operators. Domain indexes are used for nonstandard scenarios. Application domain indexes are what Oracle calls extensible indexing. They allow you to create your own index structures that work just like indexes supplied by Oracle. When someone issues a CREATE INDEX statement using your index type, Oracle will run your code to generate the index. If someone analyzes the index to compute statistics on it, Oracle will execute your code to generate statistics in whatever format you care to store them in. When Oracle parses a query and develops a query plan that may make use of your index, Oracle will ask you how costly this function is to perform as it is evaluating the different plans. In short, application domain indexes give you the ability to implement a new index type that does not exist in the database as of yet. The best example of this is Oracles own text index. This index is used to provide keyword searching on large text items. SQL> create index myindex on mytable (docs) indextype is ctxsys.context; Key Compression One of the ways that an index improves performance is to reduce the amount of I/O that the Oracle database must perform to perform a variety of tasks, including imposing selection criteria and joining tables together. Another way to reduce I/O even more is with the use of key compression. Before 1234511 1234512 1234513 After 12345 11 12

69

13 14 15 16 17 Figure: Index without and with key compression. The end result of key compression looks like a report formed with headers on grouping columns, as shown in Figure, and the overall result is to reduce the amount of storage space needed for the index. With this reduction, Oracle can use an index without having to retrieve and examine as much data. You specify key compression on the leading columns of a key. If the overall key is not unique, you can specify all the columns in the key. If the overall key is unique, you cannot compress the last column, which is used to preserve uniqueness. Because of this restriction, key compression cannot be used for all indexes, and may require some modification of your database design to be optimally implemented. DIFFERENCE BETWEEN B-TREE & BITMAP INDEX Bitmap indexes are structures that store pointers to many rows with a single index key entry, as compared to a B*Tree structure where there is parity between the index keys and the rows in a table. In a bitmap index, there will be a very small number of index entries, each of which points to many rows. In a conventional B*Tree, one index entry points to a single row.

1234514 1234515 1234516 1234517

Frequently Asked Questions and Myths about Indexes


How is Indexes Update? Indexes are automatically maintained and used by ORACLE. Changes to table data are automatically incorporated into all relevant indexes. What are Clusters? Clustering is a method of storing tables that are intimately related and often joined together into the same area on disk. Clusters are groups of one or more tables physically stores together to share common columns and are often used together. What is cluster Key? The related column of the tables in a cluster is called the Cluster Key. What is Index Cluster? A Cluster with an index on the Cluster Key. What is Hash Cluster? A row is stored in a hash cluster based on the result of applying a hash function to the rows cluster key value. All rows with the same hash key value are stores together on disk. When can Hash Cluster used? Hash clusters are better choice when a table is often queried with equality queries. For such queries the specified cluster key value is hashed. The resulting hash key value points directly to the area on disk that stores the specified rows. Do Indexes Work on Views? Yes. To index a view, you simply index the base tables. Do Nulls and Indexes Work Together? B*Tree indexes, except in the special case of cluster B*Tree indexes, do not store completely null entries, but bitmap and cluster indexes do. Should Foreign Keys Be Indexed? Yes. Unindexed foreign keys are the biggest single cause of deadlocks, due to the fact that an update to a parent tables primary key or the removal of a parent record will place a table lock on the child table (no modifications to the child table will be allowed until the statement completes). This locks many more rows than it should and decreases concurrency. An unindexed foreign key is bad in the following cases as well:

70

When you have an ON DELETE CASCADE and have not indexed the child table. For example, EMP is
child of DEPT. DELETE FROM DEPT WHERE DEPTNO = 10 should cascade to EMP. If DEPTNO in EMP is not indexed, you will get a full table scan of EMP. This full scan is probably undesirable, and if you delete many rows from the parent table, the child table will be scanned once for each parent row deleted.

When you query from the parent to the child. Consider the EMP/DEPT example again. If you frequently
query to generate a report or something, youll find not having the index in place will slow down the queries. SQL> select * from dept, EMP where emp.deptno = dept.deptno and dept.dname =: X; So, when do you not need to index a foreign key? In general, when the following conditions are met:

You do not delete from the parent table. You do not update the parent tables unique/primary key value, either purposely or by accident (via a
tool). You do not join from the parent table to the child table, or more generally the foreign key columns do not support an important access path to the child table and you do not use them in predicates to select data from this table (such as DEPT to EMP).

If you satisfy all three criteria, feel free to skip the indexit is not needed and will slow down DML on the child table. If you do any of the three, be aware of the consequences.

71

SYNONYMS
A SYNONYM is a schema object, which acts as an alternative name for an existing object. By using a SYNONYM, we can avoid the entry of the schema name, when referencing upon objects that belongs to other schema. The CREATE SYNONYM privilege is necessary to execute the creation of a SYNONYM. Syntax: CREATE [PUBLIC] SYNONYM <synonym_name> FOR <schema_name>.<object_name>; Example: Sql > CREATE SYNONYM emp_info FOR emp; Sql > CREATE SYNONYM emp_dept FOR emp_vu; Sql > CREATE PUBLIC SYNONYM e_info FOR scott . emp; PUBLIC: It is accessible by all users. DROP A SYNONYM: Syntax: DROP SYNONYM <synonym_name>; Example: Sql > DROP SYNONYM emp_info; Sql > DROP PUBLIC SYNONYM e_info;

72

73