Oracle 10g_SQL (Fast n Final )

Embed Size (px)

Citation preview

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    1/73

    ORACLE 10g

    FAST n FINALBEST OF LUCK

    [email protected] Mana Bhanjan Gadua

    1

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    2/73

    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 andANSI standard. SQL is often pronounced as SEQUEL.

    OR

    SQL is a nonprocedural language that is designed specifically for data access operations on normalizedrelational 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 databasestructures.

    The development of SQL is governed by standards. A major revision to the SQL standard was completed in1992, 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 statementsspecify 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 acommand line tool that allows user to type SQL commands to be executed directly against an Oracle database. SQLis a language used to query the relational database (DML, DCL, and DDL). SQL*PLUS commands are used to formatquery result, Set options, Edit SQL commands and PL/SQL.

    Rules of Precedence

    Operator Name Operator Order EvaluatedArithmetic operators *, /, +, - 1

    Concatenation operator || 2

    Relational/Comparison conditions=, !=, >,=,

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    3/73

    TRUNCATE - remove all records from a table, including all spaces allocated for the recordsare removed.

    RENAME - rename to a table.

    DML (Data Manipulation Language): This language that enable user to access or manipulate data asorganized 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 neededwithout 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.

    3

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    4/73

    DDL

    DDL -- create, alter, drop, truncate, rename

    CREATE TABLE SYNTAX

    Create table (col1 datatype1, col2 datatype2 coln datatypen);

    Ex:

    SQL> create table student (no number (2), name varchar (10), marks number (3));

    USING ALTERThis can be used to add or remove columns and to modify the precision of the datatype.

    a) ADDING COLUMN

    Syntax:

    alter table add ;

    Ex:

    SQL> alter table student add sdob date;

    b) REMOVING COLUMN

    Syntax:

    alter table drop ;

    Ex:

    SQL> alter table student drop column sdob;

    c) INCREASING OR DECREASING PRECISION OF A COLUMN

    Syntax:

    alter table modify ;

    Ex:

    SQL> alter table student modify marks number(5);

    * To decrease precision the column should be empty.

    d) MAKING COLUMN UNUSED

    Syntax:

    alter table set unused column ;

    Ex:

    SQL> alter table student set unused column marks;

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

    4

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    5/73

    d) DROPPING UNUSED COLUMNS

    Syntax:

    alter table 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 rename column to ;

    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 ;

    Ex:

    SQL> truncate table student;

    USING DROP

    This will be used to drop the database object;

    Syntax:

    Drop table ;

    Ex:

    SQL> drop table student;

    USING RENAME

    This will be used to rename the database object;

    Syntax:

    rename to ;

    Ex:

    SQL> rename student to stud;

    USER DEFINED TYPE

    SQL> CREATE TYPE IS OBJECT(V_NAME1 DATATYPE (Size)V_NAME2 DATATYPE (Size)V_NAME3 DATATYPE (Size)

    );

    Example:

    5

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    6/73

    DML

    INSERT

    This will be used to insert the records into table.

    We have two methods to insert.

    By value method

    By address method

    a) USING VALUE METHOD

    Syntax:

    insert into 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 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

    6

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    7/73

    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 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 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 set = value1, = value2 where ;

    Ex:

    SQL> update student set marks = 500;

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

    SQL> update student set marks = 500 where no = 2;

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

    DELETE

    This can be used to delete the table data temporarily.

    Syntax:

    Delete where ;

    7

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    8/73

    Ex:

    SQL> delete student;

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

    SQL> delete student where no = 2;

    USING TCL

    USING COMMIT

    This will be used to save the work.

    Commit is of two types.

    Implicit

    Explicit

    a) IMPLICIT

    This will be issued by oracle internally in two situations.

    When any DDL operation is performed.

    When you are exiting from SQL * PLUS.

    b) 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.

    Upto previous commit

    Upto previous rollback

    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.

    8

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    9/73

    Syntax:

    Savepoint ;

    Ex:

    SQL> savepoint s1;

    SQL> insert into student values(1, a, 100);

    SQL>

    savepoint s2; SQL> insert into student values(2, b, 200);

    SQL> savepoint s3;

    SQL> insert into student values(3, c, 300);

    SQL> savepoint s4;

    SQL> insert into student values(4, d, 400);

    Before rollback

    SQL> select * from student;

    NO NAME MARKS

    --- ------- ----------

    1 a 100

    2 b 200

    3 c 300

    4 d 400

    SQL> rollback to savepoint s3;

    Or

    SQL> rollback to s3;

    This will rollback last two records.

    SQL> select * from student;

    NO NAME MARKS

    --- ------- ----------

    1 a 100

    2 b 200

    9

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    10/73

    USING DCL

    DCL commands are used to granting and revoking the permissions.

    1. GRANT : Use to grant privileges to other users or roles.2. REVOKE : Use to take back privileges granted to other users and roles.

    TYPES OF PRIVILEDGE1. System Privileges.

    System Privileges are normally granted by a DBA to users. Examples of system privileges areCREATE 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 DescriptionSelect Ability to query the table with a select statement.

    Insert Ability to add new rows to the table with the insert statement.

    Update Ability to update rows in the table with the update statement.

    Delete Ability to delete rows from the table with the delete statement.

    References Ability to create a constraint that refers to the table.

    Alter Ability to change the table definition with the alter table statement.

    Index 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 on to [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

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    11/73

    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 thecolumns 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 theprivileges.

    Syntax:

    Revoke on from ;

    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 onename column then you have to first take back the wholeinsert privilege and then grant privilege on empno column.

    ROLESA 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 grantselect, update privilege on EMP table, select, delete privilege on dept table. To do this first create a role by giving thefollowing statement:Create role clerksThen grant privileges to this role.grant select,update on emp to clerks;grant select,delete on dept to clerks;

    11

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    12/73

    Now grant this clerks role to users like thisgrant 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 privilegeto 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 PRIVILEGESTo see which table privileges are granted by you to other users.

    SELECT * FROM USER_TAB_PRIVS_MADETo see which table privileges are granted to you by other usersSELECT * FROM USER_TAB_PRIVS_RECD;To see which column level privileges are granted by you to other users.SELECT * FROM USER_COL_PRIVS_MADETo see which column level privileges are granted to you by other usersSELECT * FROM USER_COL_PRIVS_RECD;

    To see which privileges are granted to rolesSELECT * FROM USER_ROLE_PRIVS;

    12

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    13/73

    USING ALIASES

    CREATE WITH SELECT

    We can create a table using existing table [along with data].

    Syntax:

    Create table [col1, col2, col3 ... coln] as select * from

    ;

    Ex:

    SQL> create table student1 as select * from student;

    Creating table with your own column names.

    SQL> create table student2(sno, sname, smarks) as select * from student;

    Creating table with specified columns.

    SQL> create table student3 as select no,name from student;

    Creating table with out table data.

    SQL> create table student2(sno, sname, smarks) as select * from student where 1 = 2;

    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 select * from ;

    Ex: SQL> insert into student1 select * from student;

    Inserting data into specified columns

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

    COLUMN ALIASES

    Syntax:

    Select from ;

    Ex:

    13

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    14/73

    SQL> select no sno from student;

    or

    SQL> select no sno from student;

    TABLE ALIASES

    If you are using table aliases you can use dot method to the columns.

    Syntax:Select ., . . from

    ;

    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.

    SQL> 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)

    14

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    15/73

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    16/73

    -- 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

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    17/73

    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

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    18/73

    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 storedEdit Buffer.

    Oracle Built-in Datatypes

    DATA TYPES DESCRIPTION

    CHAR(size) Stores character string.Maximum number of character- 255.Inserted values will be padded with space.

    NCHAR(size) Fixed-length character data of length size characters. Maximum size idetermined by the national character set definition, with an upper limit of 200bytes. Default and minimum size is 1 character.

    VARCHAR(size)/VARCHAR2(size)

    Stores variable length alphanumeric data.Maximum number of character- 4000.Inserted values will not be padded with space.

    NVARCHAR2(size) Variable-length character string having maximum length size charactersMaximum size is determined by the national character set definition, with aupper limit of 4000 bytes. You must specify size for NVARCHAR2.

    NUMBER(p,q) 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 theMaximum of 38 digits.

    DATE Represents date and time.The standard format is DD-MON-YY.

    18

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    19/73

    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(fractional_ seconds_precision)

    Year, month, and day values of date, as well as hour, minute, and seconvalues of time, where fractional_seconds_precision is the number of digits ithe fractional part of the SECOND datetime field. Accepted values ofractional_seconds_precision are 0 to 9. The default is 6.

    TIMESTAMP

    (fractional_seconds_precision)WITH TIME ZONE

    All values of TIMESTAMP as well as time zone displacement value, wher

    fractional_seconds_precision is the number of digits in the fractional part of theSECOND datetime field. Accepted values are 0 to 9. The default is 6.

    TIMESTAMP(fractional_seconds_precision)WITH LOCAL TIME ZONE

    All values of TIMESTAMP WITH TIME ZONE, with the following exceptions: Data is normalized to the database time zone when it is stored in the databasen When the data is retrieved, users see the data in the session time zone.

    INTERVALYEAR(year_precision)TO MONTH

    Stores a period of time in years and months, where year_precision is thenumber of digits in the YEAR datetime field. Accepted values are 0 to 9. Thedefault is 2.

    INTERVAL DAY(day_precision)TO SECOND(fractional_seconds_precision)

    Stores a period of time in days, hours, minutes, and seconds, where day_precision is the maximum number of digits in the DAY datetime fieldAccepted values are 0 to 9. The default is 2. n fractional_seconds_precision ithe number of digits in the fractional part of the SECOND field. Accepted valueare 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 musspecify 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. Thidatatype 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-organizetable. The optional size is the size of a column of type UROWID. The maximumsize and default is 4000 bytes.

    Object Type

    LOB They hold values called locations, specifying the location of large objects thaare stored out of line.

    CLOB A character large object containing single-byte characters. Both fixed-width anvariable-width character sets are supported, both using the CHAR databascharacter set. Maximum size is 4 gigabytes.

    NCLOB A character large object containing Unicode characters. Both fixed-width anvariable-width character sets are supported, both using the NCHAR databascharacter 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. Enablebyte stream I/O access to external LOBs residing on the database serveMaximum 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

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    20/73

    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 empGROUP BY empno, ename, job, mgr, hiredate, sal, comm., deptno);

    What are different Oracle database objects?

    TYPES OBJECT DESCRIPTION

    Independent Object TABLE Basic unit of storage; composed of row and columns.

    VIEW Logically represents subsets of data from one or more tables.

    SEQUENCE Generates primary key values.

    SYNONYMS Alternative name for an object.

    Dependent Object INDEX Improves the Performance of queries.

    CONSTRAINT Used to define the Integrity rule

    20

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    21/73

    FUNCTION

    SINGLE ROW FUNCTION GROUP FUNCTION

    CHARACTERFUNCTION

    NUMBERFUNCTION

    DATEFUNCTION

    CASECONVERSION

    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)

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

    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)DECODECHR (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

    MISCELLANEOUS FUNCTION

    UIDUSERLEAST (expr1, expr2)GREATEST (expr1, expr2)VSIZE (expr)SOUNDEX (char)USERNV (option)

    ****************************************************Where OPTION are:

    ISDBALANGUAGETERMINALSESSIONIDENTRYIDLANGINSTANCECLIENT_INFO

    **********************************************************

    TO_CHAR (Number, Format, nlsparmTO_CHAR (Date, Format, nlsparms)TO_NUMBER (char, Format, nlsparmsTO_DATE (char, Format, nlsparms)

    GENERAL FUNCTION

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

    21

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    22/73

    DATE FORMAT

    TO_CHAR (DATE, format,nlsparameters);

    Sysdate=27.DEC.2009Time=12:01:55 AM

    EXAMPLE:Sql> SELECT sysdate, TO_CHAR (sysdate, 'D') FROM DUAL

    DATE FORMAT: EXPLANATION RESULT

    D Numeric week day indicator (1-7) 1

    DD Month day indicator (1-31) 27

    DDD Year day indicator (1-366) 361

    THSPSPTH

    Date format suffixes 27TH

    TWENTY-SEVENTWENTY-SEVENTH

    FM Fill mode indicator

    FX Format exact

    DY Abbreviated weak day indicator SUN

    DAY Week day spelling indicator (SUNDAY-SATURDAY) SUNDAY

    W Week of the month indicator 4

    WW Year week indicator (1-53) 52IW ISO standard year week indicator (1-53) 52

    MM Numeric month indicator (01-12) 12

    MON Abbreviated month indicator (JAN-DEC) DEC

    MONTH Month spelling indicator (JANYUARY-DECEMBER) DECEMBER

    Q Quarter of the year indicator (1-4) 4

    J Julian day indicator 2455193

    CCSCC

    Century indicatorS prefixes BC date with -

    2121 AD

    IY ISO standard 2 digit year indicator 09

    YY 2 digit year indicator 09

    IYYY ISO standard 4 digit year indicator 2009

    YYYY

    SYYY

    4 digit year indicator 2009

    YEARSYEAR

    Spelled year indicator THO THOUSAND NINE

    AMA.M.PMP.M.

    Meridian indicator

    HHHH12

    12 hour clock mode 12

    HH24 24 hour clock mode

    MI Minute indicator 01

    SS Second indicator 55

    SSSSS Second past mid night (0-86399) 115

    HH:MI:SS- / !, ., ;, : Date format punctuator

    12:01:55

    22

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    23/73

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    24/73

    WHEN comparison_exprnTHEN return_exprnELSE else_expr]

    END

    Example:Sql> SELECT ename, job, sal,

    CASE job WHEN clerk THEN 10*salWHEN analyst THEN 15*salWHEN manager THEN 20*salELSE salEND "REVISED_SALARY"

    FROM emp;

    2. DECODE functionThe 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 sameas search, resultis 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

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    25/73

    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 NVLfunction.

    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 groupedcolumns, 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 BYclauseGROUP 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.

    HAVINGclauseHAVING 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. Youcannot use WHERE clause to filter groups.

    Order of execution: SELECT FROM WHERE GROUP BY HAVING ORDER BY

    25

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    26/73

    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 constraintb) CHECK constraintc) DEFAULT key wordd) 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 otherrelation.

    When referential integrity is enforced, it prevents from:

    Adding (INSERT) records to a related (CHILD) table if there is no associated record in theprimary (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 primarytable.

    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

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    27/73

    These are business rules which can be handled at run time, usually designed using database triggersin 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 thedatabase.

    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 theconstraint 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 constraintname 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 orNOT NULL constraint can not be specified as VIEW constraints.

    NULL orNOT NULL constraint can not be specified for an attribute of an object.Example:Sql > CREATE TABLE student

    (

    27

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    28/73

    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 UNIQUEkey.

    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: 1Sql > 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

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    29/73

    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 isenough.

    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: 1Sql > 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 orUPDATED into DETAIL table if corresponding records inthe MASTER table do not exist.

    29

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    30/73

    Record of the MASTER table cannot be UPDATED orDELETED if corresponding records inthe DETAIL table exist.

    If the ON DELETE CASCADE option is set, a DELETE operation in the MASTER table will trigger aDELETE operation for corresponding records in all DETAIL table.

    It is also known as REFERENTIAL INTEGRITY CONSTRAINT.

    Must reference a PRIMARY KEY orUNIQUE column(s) in MASTER table.

    Will automatically reference the PRIMARY KEY of the MASTER table if no column (or group ofcolumns) 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 datatypes.

    May reference the same table named in the CREATE TABLE statement.

    Inline Style:Syntax:

    (size) REFERENCES ,[()][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 (,)REFERENCES .;

    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 orunknown.

    Restriction:

    CHECK CONSTRAINT must be avoided if the constraint can be defined using the NOTNULL, 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:

    (size) CHECK (logical expression)

    Example:

    30

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    31/73

    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 PRIMARYkey and UNIQUEkey enforces uniqueness of the column on which they are defined.

    But by default a PRIMARYkey creates a CLUSTERED INDEXon the column; where as UNIQUEkeycreates a NON-CLUSTERED INDEXby default.

    A table can have only one PRIMARYkey whereas there can be any number ofUNIQUEkeys.

    The columns that compose PK are automatically define NOT NULL, whereas a column that compose aUNIQUEis 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 CASCADEoption. When the ON DELETE CASCADE is specified in the FOREIGN KEY definition, if the user deletes arecord in the master table, all corresponding records in the detail table along with the record in the mastertable will be deleted.

    Syntax:Sql > ()

    REFERENCES [()][ON DELETE CASCADE]

    31

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    32/73

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    33/73

    33

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    34/73

    NATURAL JOIN

    34

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    35/73

    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 propervalues.

    It is a condition containing something other than equality operator.Examples:

    35

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    36/73

    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 joincondition.

    Example:

    36

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    37/73

    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 isdeficient in information.

    To perform an out join of tables A and B and returns all rows from A apply the outer join operator (+) to allcolumn of B.

    For all rows in A that have no matching rows in B oracle returns NULL for any select list expressionscontaining 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 logicaloperator.

    A condition cannot use the IN comparison operator to compare a column marked with the (+) operatorwith an expression.

    A condition cannot compare any column marked with the (+) operator with a sub query.

    37

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    38/73

    Example: FULL OUTER JOIN (FULL JOIN)

    LEFT OUTER JOIN (LEFT JOIN)

    RIGHT OUTER JOIN (RIGHT JOIN)

    38

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    39/73

    Qualifying Ambiguous Column Names:

    The names of the column names should be qualified in the WHERE clause, with the table name to avoidambiguity.

    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, deptWHERE 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 besubstituted throughout the SELECT statement.

    A table alias is valid only for the current SELECT statement.

    Example:

    39

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    40/73

    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)

    SELECTtable1.column, table2.columnFROM table1[CROSS JOIN table2] |[NATURAL JOINtable2] |[JOINtable2USING (column_name)] |[INNERJOIN table2ON(table1.column_name= table2.column_name)] |[JOIN table2ON (table1.column_name= table2.column_name)] |

    40

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    41/73

    [LEFT|RIGHT|FULL OUTER JOIN table2ON (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=TKBSPORT 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

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    42/73

    SUBQUERY

    A subquery is a SELECT statement that is embedded in a clause of another SELECT statement.

    Types of operator

    Single row operators (=, >, >=, =,

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    43/73

    Example: Subquery in FROM clause (INLINE VIEWS)

    A subquery in the FROM clause of the main query (outer query) is known as INLINE VIEW becausethe 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. ALL means more than the maximum value in the list.

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    44/73

    Example ofANY:

    Example ofALL:

    44

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    45/73

    MULTIPLE COLUMN SUBQUERY

    A multiple-column subquery is one that returns one or more row from the inner SELECT statement to theouter 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 executedonce for each row returned by the parent query. If the subquery is executed for each row of the parent, this iscalled a correlated subquery.

    A correlated subquery can be easily identified if it contains any references to the parent subquerycolumns in its WHERE clause. Columns from the subquery cannot be referenced anywhere else in the parentquery. 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 SELECT LEVEL, MAX (SAL)

    FROM EMPWHERE LEVEL=&LEVEL_NO CONNECT BY PRIOR SAL>SAL GROUP BY LEVEL;

    Using co-related subquerySql > SELECT distinct (A.Sal)FROM EMP A

    WHERE &N = (SELECT count (distinct (B.sal)) FROM EMP B WHERE A.sal SELECT ENAMEFROM EMPWHERE SAL= (SELECT distinct (A.Sal) FROM EMP A

    WHERE &N = (SELECT count (distinct (B.sal)) FROM EMP B WHERE A.sal

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    46/73

    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 underlyingbase table.

    In other words, there is no stored file that direct represents the view instead a definition of view is stored indata dictionary.

    Advantages (why use view?):

    View restricts access to the data because the view can display selective row & columns from thetable.

    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 (alias,)AS subqueryWITH CHECK OPTION CONSTRAINT constraintWITH READ ONLY [CONSTRAINT constraint;

    Syntax Definition

    46

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    47/73

    OR REPLACE Recreates the view if it already exists.

    FORCE Creates the view regardless of whether or not the base table exists.

    NOFORCE Creates the view only if the base table exists (This is default).

    Alias Specifies names for the expressions selected by the views query. The number of aliases must match the number of expressions selected by the view.

    Sub query Complete select statement.

    WITH CHECK OPTION Specifies that only rows accessible to the view can be inserted or updated.

    Constraint Name assigned to the CHECK OPTION constraint.

    WITH READ ONLY Ensures that no DML operations can be performed on this view.

    Example:Sql > CREATE VIEW emp_vu1

    ASSELECT empno, ename, sal, jobFROM empWHERE 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_jobFROM empWHERE job=CLERK;

    Sql > CREATE VIEW emp_vu3 (employee_id, emp_name, ann_sal, emp_job )AS SELECT empno, ename, sal*5, jobFROM empWHERE 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, jobFROM empWHERE job=CLERK;

    CREATING A COMPLEX VIEW:

    Sql > CREATE VIEW emp_dept_vu4(name, deptno, dname)AS SELECT e.ename, d.deptno,d.dnameFROM emp e, dept dWHERE 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 dWHERE e.department_id=d. department_idGROUP 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

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    48/73

    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 theWITH CHECK OPTION clause.

    Example:Sql > CREATE OR REPLACE VIEW emp_vu6

    AS SELECT * FROM empWHERE deptno=30WITH CHECK OPTION CONSTRAINT emp_vu6_ck;

    Any attempt to change the deptno for any row in the view fails because it violates theWITH 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 empWHERE job=CLERKWITH READ ONLY;

    Sql > DELETE FROM emp_vu3WHERE 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 ;

    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 theproper 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

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    49/73

    receive a message indicating that the view has errors. If you recreate the table (that you had dropped), the viewwill again be fine.

    MATERIALISED VIEWA 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" forconsistency. 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 viewscan 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 remotetable.

    Since when we are woring with various databases running in different system. So sometime we mayneeded to fetch some records from the remote location so it may quit expensive in terms of resource offetching 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 duplicatecopy is Known as materialized view which may be refreshed as per as requirement as option availablewith oracle such as fast complete and refresh.

    Materialized View stores both - definition of the view and rows resulted from execution of the view. Maindisadvantage of materialized view is that its contents get outdated when underlying base table ismodified. 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 yourcorporate 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 distributeuser load to an even greater extent because clients can access materialized view sites instead of mastersites. To decrease the amount of data that is replicated, a materialized view can be a subset of a mastertable or master materialized view.

    Create a Mass Deployment EnvironmentDeployment 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

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    50/73

    sales force automation and other mass deployment environments. Parameters allow you to create customdata sets for individual users without changing the deployment template. This technology enables you toroll out a database infrastructure to hundreds or thousands of users.

    Enable Data SubsettingMaterialized 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 replicateinformation 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 unnecessarynetwork traffic.

    Enable Disconnected ComputingMaterialized 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 on-demand, which is an ideal solution for sales applications running on a laptop. For example, a developercan integrate the replication management API for refresh on-demand into the sales application. When thesalesperson has completed the day's orders, the salesperson simply dials up the network and uses theintegrated mechanism to refresh the database, thus transferring the orders to the main office.

    Types of MATERIALISED VIEWA 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 andwriteable materialized views.

    Read-Only Materialized ViewsYou 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 usemany of the same mechanisms as updatable materialized views, except that they do not need to belongto a materialized view group.

    In addition, using read-only materialized views eliminates the possibility of a materialized viewintroducing data conflicts at the master site or master materialized view site, although this conveniencemeans that updates cannot be made at the remote materialized view site. The following is an example ofa read-only materialized view:

    Sql> CREATE MATERIALIZED VIEW hr.employeesAS SELECT * FROM [email protected];

    Updatable Materialized ViewsYou 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 anupdatable materialized view to be pushed back to the master during refresh, the updatable materializedview must belong to a materialized view group.

    Updatable materialized views enable you to decrease the load on master sites because userscan make changes to the data at the materialized view site. The following is an example of an updatablematerialized view:

    Sql> CREATE MATERIALIZED VIEW hr.departmentsFOR UPDATE AS SELECT * FROM [email protected];

    Note:

    Do not use column aliases when you are creating an updatablematerialized view. Column aliases cause an error when youattempt to add the materialized view to a materialized viewgroup using the CREATE_MVIEW_REPOBJECT procedure.

    50

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    51/73

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

    Updatable materialized views do not support the DELETECASCADE constraint.

    Writable Materialized Views

    A writeable materialized view is one that is created using the FOR UPDATE clause but is not partof a materialized view group. Users can perform DML operations on a writeable materialized view, but ifyou refresh the materialized view, then these changes are not pushed back to the master and thechanges are lost in the materialized view itself. Writeable materialized views are typically allowedwherever fast-refreshable read-only materialized views are allowed.

    Note: Most of the documentation about materialized views only refersto read-only and updatable materialized views because writeablematerialized 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 time-saving object because it can reduce the amount of application code needed to write a sequence-generatingroutine.

    SEQUENCE numbers are stored and generated independently of tables. Therefore, the same SEQUENCE canbe used for multiple tables.

    A SEQUENCE can be shared by multiple users to generate unique integer.

    CREATING A SEQUENCE :Syntax:

    CREATE SEQUENCE INCREMENT BY nSTART WITH nMAXVALUE n | NOMAXVALUEMINVALUE n | NOMINVALUECACHE n | NOCACHECYCLE | NOCYCLEORDER | NOORDER;

    51

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    52/73

    Sequence_name Is the name of the sequence generator.

    INCREMENT BY n Specifies the interval between sequence numbers, where n is an integer and it can be either+veor-ve but not zero (0). If the value is +ve then it is incremented sequence else it is decrementedsequence. If this clause is omitted, the sequence increments by 1.

    START WITH n Specifies the first sequence number to be generated. If this clause is omitted, the sequencestarts with 1.

    MAXVALUE n Specifies the maximum sequence value.

    NOMAXVALUE Specifies a maximum value of 10^27 for an ascending sequence and -1 for a descendingsequence (This is the default option).

    MINVALUE n Specifies the minimum sequence value.

    NOMINVALUE Specifies a minimum value of 1 for an ascending sequence and (10^26) for a descendingsequence (This is the default option).

    CYCLE Specifies whether the sequence continues to generate values after reaching its maximum orminimum value.

    NOCYCLE Specifies that the sequence cannot generate more value after the target limit. Itis default option

    CATCHE n Specifies how many values the Oracle server pre-allocates and keeps in memory (By default,the Oracle server catches 20 values).

    NOCATCHE Specifies the value of a sequence is not pre-allocated.

    ORDER Guarantees the sequence numbers to be generated in the order of request. It is bydefault

    NOORDER 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_seqINCREMENT BY 5START WITH 1MAXVALUE 30NOCACHENOCYCLE;

    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_seqINCREMENT BY 10

    52

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    53/73

    START WITH 1MAXVALUE 60NOCACHECYCLE;

    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_seqINCREMENT BY -2START WITH 0MAXVALUE 10MINVALUE 0NOCACHENOCYCLE;

    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 currentSEQUENCE 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

    INCREMENT BY nMAXVALUE n | NOMAXVALUEMINVALUE n | NOMINVALUECACHE n | NOCACHE

    53

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    54/73

    CYCLE | NOCYCLE;Example:SQL > ALTER SEQUENCE sample_seq

    INCREMENT BY 7MAXVALUE 40MINVALUE 5CACHENOCYCLE;

    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 FROMuser_sequences;

    VIEWING THE CURRENT & NEXT VALUE OF A SEQUENCE :

    Syntax:SEQUENCENAME.CURRVAL

    Returns the current value of the sequence.

    SEQUENCENAME.NEXTVALReturns 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 thefollowing privileges.

    SELECT OBJECT PRIVILEGE

    54

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    55/73

    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 ;

    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

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    56/73

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

    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 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 thehierarchy.

    56

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    57/73

    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

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    58/73

    58

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    59/73

    INDEXINGAn 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 calledindex 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

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    60/73

    When the user defines a primary key or a unique key constraint at column or table level, the oracle engineautomatically 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 canbe created to increase the performance of data retrieval. Index can be created on one or more columns of atable.

    How Indexes are created?

    Automatically: A unique index is created automatically when you define a PRIMARY KEY or UNIQUEconstraint 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 WorksAn 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.

    KeysThe 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 ON ();Example:

    Sql > CREATE INDEX idx_emp ON emp (ename);

    Unique index:Syntax:

    60

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    61/73

    CREATE UNIQUE INDEX ON ();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 ON (,);Example:

    Sql > CREATE INDEX idx_emp ON emp (ename,job);

    Unique index:Syntax:

    CREATE UNIQUE INDEX ON (,);

    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 arange. The B-tree index does this by performing a succession of value comparisons. Eachcomparison eliminates many of the rows in the potential result set from consideration, which cansignificantly improve query performance.

    They are similar in implementation to a binary search tree. Their goal is to minimize theamount of time Oracle spends searching for data.

    How It WorksA 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 ofbranch 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 orleaf blocks, contain every indexed keyand a rowid that points to the row it is indexing. The interior blocks, above the leaf nodes, are knownas branch blocks. They are used to navigate through the structure. For example, if we wanted to findthe value 42 in the index, we would start at the top of the tree and go to the left. We would inspectthat block and discover we needed to go to the block in the range 42..50. This block would be theleaf block and point us to the rows that contained the number 42. It is interesting to note that the leafnodes 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 indexrange scan) is very easy. We dont have to navigate the structure any more; we just go forward orbackward through the leaf nodes as needed. That makes satisfying a predicate, such as the

    following, pretty simple:

    Where x between 20 and 30Oracle 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 isgreater 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 tomake the key unique. For example, an index such as CREATE INDEX I ON T(X,Y) is conceptuallyCREATE UNIQUE INDEX I ON T(X,Y,ROWID). In a unique index, as defined by you, Oracle does not

    61

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    62/73

    add the rowid to the index key. In a nonunique index, you will find that the data is sorted first by indexkey values (in the order of the index key) and then by rowid ascending. In a unique index, the data issorted 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 heightof the index, meaning that any traversal from the root block ofthe 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. Inother words, the index is height balanced. Most B*Tree indexes will have a height of 2 or 3, even formillions of records. This means that it will take, in general, two or three I/Os to find your key in theindexwhich is not too bad.

    Note Oracle uses two terms with slightly different meanings when referring to thenumber of blocks involved in traversing from an index root block to a leaf block. The first isHEIGHT, 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 beenanalyzed using the ANALYZE INDEX VALIDATE STRUCTURE command. The other isBLEVEL, which is the number of branch levels and differs from HEIGHT by one (it does notcount the leaf blocks). The value of BLEVEL is found in the normal dictionary tables such asUSER_INDEXES after statistics have been gathered.

    Each branch page contains a number of entries, each of which points to either another levelof branch pages or a leaf page. Each entry has the maximum value for the next level of pages. Forinstance, if a request to the index shown in Figure were to ask for a value of aaron, the searchwould branch to the left at the root page, to the left again at the first level of branch pages, and, usingthe 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 theindex entry represents. An index leaf page also has a pointer to the next and previous index leafpages, 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 modifiedaccordingly. 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 ofdecisions about the location of a potential index entry. Each decision effectively eliminates half of theremaining potential index entries, which makes finding individual rows quick and efficient. When thisperformance improvement is added to the virtues of pre-sorting the entries, you can see how a B-treeindex can help reduce I/O operations and improve performance.

    0-300

    0-100 101-200 201-300

    0-50 51-100

    Branch Nodes

    101-150 151-200 201-250 251-300

    0-10Rowid

    11-20Rowid

    21-30Rowid

    31-40Rowid

    41-50Rowid Leaf Nodes

    62

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    63/73

    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 theentire querywe will not have to go to the table at all. The index will be used as a thinnerversion 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 manycases. Typically, your queries will require information beyond that found in the index, so once theOracle database has selected the appropriate index entry, the database still has to use the pointer inthe index entry to retrieve the extra information in the row. Although access through the pointer in anindex 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 sameefficiencies offered by an index are used to retrieve all of the data in the row. An Index organizedtables stores both key values and non-key values within its pages. Oracle provides an overflow optionthat allows you to indicate that some non-key values are stored outside of the index structure, basedon storage room available in the actual index block.

    Because an IOT is organized around a primary key value, you must have a primary keydefined for an IOT. Because the IOT does not normally use an index value pointing to the same valuein 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-tree-based 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, toaccess the data rows in the table. If an IOT row uses the overflow option, the physical row ID to theoverflow area is part of the IOT index entry.

    Root Node

    A-G H-P Q-Z

    A-C D-E F-G H-J K-M N-P Q-S T-V W-Z

    Ajay

    Anil

    BabuLeaf Nodes

    Branch Nodes

    Chinu

    63

  • 8/6/2019 Oracle 10g_SQL (Fast n Final )

    64/73

    There are a number of restrictions on the use of IOTs, such as the fact that an IOT cannotcontain columns with LONG or any of the varieties of LOB data types. In addition, an IOT cannot bestored 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 theiractual 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 bya cluster key.

    A cluster can hold either row