Oracle Database 11g Controlling User Access and Managing Schema Objects

Embed Size (px)

Citation preview

  • 8/10/2019 Oracle Database 11g Controlling User Access and Managing Schema Objects

    1/54

    System and Object Privileges

    Learning objective

    After completing this topic, you should be able to identify the steps for granting andrevoking system and object privileges.

    1. Introducing privileges

    Disclaimer

    Although certain aspects of Oracle Database 11g are case and spacing insensitive, acommon coding convention has been used throughout all aspects of this course.

    This convention uses lowercase characters for schema, role, user, and constraint names,and for permissions, synonyms, and table names (with the exception of the D A! table".!owercase characters are also used for column names and user#defined procedure,function, and variable names shown in code.

    ppercase characters are used for Oracle $eywords and functions, for view, table,schema, and column names shown in text, for column aliases that are not shown in%uotes, for pac$ages, and for data dictionary views.

    The spacing convention re%uires one space after a comma and one space before andafter operators that are not Oracle#specific, such as &, #, ', and . There should be no

    space between an Oracle#specific $eyword or operator and an opening brac$et, a closingbrac$et and a comma, between the last part of a statement and the closing semicolon, orbefore a statement.

    )tring literals in single %uotes are an exception to all convention rules provided. *leaseuse this convention for all interactive parts of this course.############################################################################################

    +n a multiple#user environment, you want to maintain security of the database access anduse.

    ith Oracle server database security, you can

    control database access

    give access to specific ob-ects in the database confirm given and received privileges with the Oracle data dictionary

    Database security can be classified into two categories

  • 8/10/2019 Oracle Database 11g Controlling User Access and Managing Schema Objects

    2/54

    system security

    database security

    system security

    )ystem security covers access and use of the database at the system level, such as the

    username and password, the dis$ space allocated to users, and the system operationsthat users can perform.

    database security

    Database security covers access and use of the database ob-ects and the actions thatusers can perform on the ob-ects.

    A privilege is the right to execute particular )/! statements. The database administrator(D0A" is a high#level user with the ability to create users and grant users access to thedatabase and its ob-ects.

    sers re%uire system privileges to gain access to the database and object privileges tomanipulate the content of the ob-ects in the database.

    sers can also be given the privilege to grant additional privileges to other users or toroles , which are named groups of related privileges.

    A schema is a collection of ob-ects such as tables, views, and se%uences. The schema isowned by a database user and has the same name as that user.

    These are the types of privileges that allow actions to be performed on schemas

    system privilege

    ob-ect privilege

    system privilege

    A system privilege is the right to perform a particular action or to perform an action on anyschema ob-ect of a particular type.

    object privilege

    An ob-ect privilege provides the user the ability to perform a particular action on a specificschema ob-ect.

    2. Granting system privileges

    There are more than 1 distinct system privileges available for users and roles.Typically, system privileges are provided by the D0A.

    These are some typical D0A privileges

    CREATE USER

  • 8/10/2019 Oracle Database 11g Controlling User Access and Managing Schema Objects

    3/54

  • 8/10/2019 Oracle Database 11g Controlling User Access and Managing Schema Objects

    4/54

  • 8/10/2019 Oracle Database 11g Controlling User Access and Managing Schema Objects

    5/54

    this sample code, the demo user has been assigned the privileges to create sessions,tables, se%uences, and views.

    GRANT crea e !e!!"o#$ crea e a%&e$crea e !e'(e#ce$ crea e )"e*TO demo;

    A role is a named group of related privileges that can be granted to the user. This methodma$es it easier to revo$e and maintain privileges.

    A user can have access to several roles, and several users can be assigned the samerole. 5oles are typically created for a database application.

    8irst, the D0A must create the role. Then the D0A can assign privileges to the role andassign the role to users.

    +n the syntax, role is the name of the role to be created.

    456AT6 5O!6 role :

    After the role is created, the D0A can use the GRANT statement to assign the role to usersas well as to assign privileges to the role.

    This sample code creates a ma#a+er role and then enables the manager to create tablesand views. +t then grants Be&& and Koc,,ar the role of managers. 7ow Be&& andKoc,,ar can create tables and views.

    +f users have multiple roles granted to them, they receive all the privileges associated withall the roles.

    --code .or crea "#+ a ro&eCREATE ROLE ma#a+er;--code .or +ra# "#+ /r")"&e+e! o a ro&eGRANT crea e a%&e$ crea e )"e*TO ma#a+er;--code .or +ra# "#+ a ro&e o (!er!GRANT ma#a+er TO BELL$ KOC00AR;

    The D0A creates an account and initiali2es a password for every user. 9ou can changeyour password by using the ALTER USER statement.

    +n the syntax for the ALTER USER statement

    user is the name of the user

    password specifies the new password

  • 8/10/2019 Oracle Database 11g Controlling User Access and Managing Schema Objects

    6/54

    A!T65 )65 user +D67T+8+6D 09 password :

    Note

    S$!%Plus has a PASSWORD command & PASSW & that can be used to change the password of a user when the user is logged in. 'his command is not available inS$! Developer.

    Although the ALTER USER statement can be used to change your password, there aremany other options. 9ou must have the ALTER USER privilege to change any otheroption.

    This sample code shows that the demo user changes the password by using the ALTERUSER statement.

    ALTER USER demoIDENTIFIED BY em/&o1;

    uestion

    hich privilege allows a user to connect to the database@

    Options

    1. CREATE PROCEDURE

    . CREATE SEQUENCE

    B. CREATE SESSION

    C. CREATE TABLE

    !ns"er

    The CREATE SESSION privilege allows a user to connect to the database.

    Option 1 is incorrect. 'he CREATE PROCEDURE system privilege authori(es theuser to create a stored procedure, function, or pac)age in a schema.

    Option * is incorrect. 'he CREATE SEQUENCE system privilege authori(es theuser to create a se+uence in a schema.

    Option is correct. 'he CREATE SESSION privilege authori(es a user to connectto the database.

    Option - is incorrect. 'he CREATE TABLE system privilege authori(es users tocreate a table in a schema.

  • 8/10/2019 Oracle Database 11g Controlling User Access and Managing Schema Objects

    7/54

    #. Granting and revo$ing object privileges

    An object privilege is a privilege or right to perform a particular action on a specific table,view, se%uence, or procedure. 6ach ob-ect has a particular set of grantable privileges.This Ob-ect *rivileges table lists privileges for various ob-ects.

    The only privileges that apply to a se%uence are SELECT and ALTER. UPDATE,REFERENCES, and INSERT can be restricted by specifying a subset of updatablecolumns.

    A SELECT privilege can be restricted by creating a view with a subset of columns andgranting the SELECT privilege only on the view.

    A privilege granted on a synonym is converted to a privilege on the base table referencedby the synonym.

    Note

    ith the REFERENCES privilege, you can ensure that other users can createFOREIGN KEY constraints that reference your table.

    Different ob-ect privileges are available for different types of schema ob-ects. A userautomatically has all ob-ect privileges for schema ob-ects contained in the user;s schema.

    A user can grant any ob-ect privilege on any schema ob-ect that the user owns to anyother user or role.

    +f the grant includes WIT0 GRANT OPTION , the grantee can further grant the ob-ectprivilege to other users otherwise, the grantee can use the privilege but cannot grant itto other users.

  • 8/10/2019 Oracle Database 11g Controlling User Access and Managing Schema Objects

    8/54

    ON object TO PUBLIC WIT0 GRANT OPTION

    object_priv

    object#priv is an ob-ect privilege to be granted.

    ALL

    ALL specifies all ob-ect privileges.

    columns

    columns specifies the column from a table or view on which the privileges are granted.

    ON object

    ON object is the ob-ect on which the privileges are granted.

    TO

    TO identifies to whom the privilege is granted.

    PUBLIC

    PUBLIC grants ob-ect privileges to all users.

    WITH GRANT OPTION

    WIT0 GRANT OPTION enables the grantee to grant ob-ect privileges to other users androles.

    These are the guidelines for granting ob-ect privileges

    to grant privileges on an ob-ect, the ob-ect must be in your own schema, or you must have beengranted the ob-ect privileges using WIT0 GRANT OPTION

    an ob-ect owner can grant any ob-ect privilege on the ob-ect to any other user or role of thedatabase

    the owner of an ob-ect automatically ac%uires all ob-ect privileges on that ob-ect

    Note

    D s generally allocate system privileges2 any user who owns an object can grant

    object privileges.

    These are some examples where ob-ect privileges are granted to users

    grant %uery privileges on a table grant privileges to update specific columns

    use a SELECT statement

  • 8/10/2019 Oracle Database 11g Controlling User Access and Managing Schema Objects

    9/54

    create a synonym for a table and issue a SELECT statement

    grant %uery privileges on a table

    This sample code grants the demo user the privilege to %uery the E2PLOYEES table.

    codeH--code o +ra# '(er1 /r")"&e+e! o# a a%&eGRANT !e&ecON em/&o1ee!TO demo;

    grant privileges to update speci&ic columns

    This sample code grants UPDATE privileges on specific columns in the DEPART2ENTS table to the demo user and to the ma#a+er role.

    codeH

    --code o +ra# /r")"&e+e! o (/da e !/ec"."c co&(m#!GRANT (/da e 3de/ar me# _#ame$ &oca "o#_"d4ON de/ar me# !TO demo$ ma#a+er;

    use a SELECT statement

    This sample code should be used if the schema is ORA55, and the demo user wants to usea SELECT statement to obtain data from the E2PLOYEES table.

    codeH--code o (!e a SELECT ! a eme#

    SELECT 6 FRO2 ora778em/&o1ee!; create a synonym &or a table and issue a SELECT statement

    +n this sample code, the demo user creates a synonym for the E2PLOYEES table andissues a SELECT statement from the synonym.

    codeH--code o crea e a !1#o#1m .or a a%&e a#d "!!(e a SELECT ! a eme#CREATE SYNONY2 em/ FOR ora778em/&o1ee!;SELECT 6 FRO2 em/;

    A privilege that is granted with the WIT0 GRANT OPTION clause can be passed on toother users and roles by the grantee. Ob-ect privileges granted with the WIT0 GRANTOPTION clause are revo$ed when the grantor;s privilege is revo$ed.

    This sample code gives the demo user access to the DEPART2ENTS table with theprivileges to %uery the table and add rows to the table. The code also shows that demo can give others these privileges.

  • 8/10/2019 Oracle Database 11g Controlling User Access and Managing Schema Objects

    10/54

    GRANT !e&ec $ "#!erON de/ar me# !TO demoWIT0 GRANT OPTION;

    An owner of a table can grant access to all users by using the PUBLIC $eyword.

    This sample code allows all users on the system to %uery data from Alice;sDEPART2ENTS table.

    GRANT !e&ecON a&"ce8de/ar me# !TO PUBLIC;

    +f you attempt to perform an unauthori2ed operation, such as deleting a row from a tablefor which you do not have the DELETE privilege, the Oracle server does not permit the

    operation to ta$e place.

    +f you receive the Oracle server error message ITable or view does not exist,I then youhave

    named a table or view that does not exist

    attempted to perform an operation on a table or view for which you do not have the appropriateprivilege

    The data dictionary is organi2ed in tables and views and contains information about thedatabase. 9ou can access the data dictionary to view the privileges that you have.

    These are various data dictionary views

    ROLE_SYS_PRIVS ROLE_TAB_PRIVS USER_ROLE_PRIVS USER_SYS_PRIVS USER_TAB_PRIVS_2ADE USER_TAB_PRIVS_RECD

    USER_COL_PRIVS_2ADE USER_COL_PRIVS_RECD

    ROLE_SYS_PRIVS

    The ROLE_SYS_PRIVS view displays system privileges granted to roles.

    ROLE_TAB_PRIVS

    The ROLE_TAB_PRIVS view shows table privileges granted to roles.

  • 8/10/2019 Oracle Database 11g Controlling User Access and Managing Schema Objects

    11/54

    USER_ROLE_PRIVS

    The USER_ROLE_PRIVS view displays the roles accessible by the user.

    USER_SYS_PRIVS

    The USER_SYS_PRIVS view displays system privileges granted to the user.

    USER_TAB_PRIVS_MADE

    The USER_TAB_PRIVS_2ADE view displays ob-ect privileges granted on the user;sob-ects.

    USER_TAB_PRIVS_RECD

    The USER_TAB_PRIVS_RECD view displays ob-ect privileges granted to the user.

    USER_COL_PRIVS_MADE

    The USER_COL_PRIVS_2ADE view displays ob-ect privileges granted on the columns ofthe user;s ob-ects.

    USER_COL_PRIVS_RECD The USER_COL_PRIVS_RECD view displays ob-ect privileges granted to the user onspecific columns.

    The ALL_TAB_PRIVS_2ADE dictionary view describes all the ob-ect grants made by theuser or made on the ob-ects owned by the user.

    9ou can remove privileges granted to other users by using the REVOKE statement. henyou use the REVOKE statement, the privileges that you specify are revo$ed from the usersyou name and from any other users to whom those privileges were granted by therevo$ed user.

    Note

    "f a user were to leave the company and you revo)e his or her privileges, youmust regrant any privileges that this user may have granted to other users. "f youdrop the user account without revo)ing privileges from it, then the system

    privileges granted by this user to other users are not affected by this action.

    +n the syntax for revo$ing ob-ect privileges, CASCADE is re%uired to remove any referentialintegrity constraints made to the CONSTRAINTS ob-ect by means of the REFERENCES privilege.

    56JOK6 E privilege =, privilege ...>?A!!GO7 object 85OL E user =,user ...>?role ?* 0!+4G=4A)4AD6 4O7)T5A+7T)>:

  • 8/10/2019 Oracle Database 11g Controlling User Access and Managing Schema Objects

    12/54

    This sample code revo$es SELECT and INSERT privileges given to the demo user on theDEPART2ENTS table.

    REVOKE !e&ec $ "#!erON de/ar me# !

    FRO2 demo;

    +f a user is granted a privilege with the WIT0 GRANT OPTION clause, the user can alsogrant the privilege with the WIT0 GRANT OPTION clause, so that a long chain ofgrantees is possible. 3owever, no circular grants granting to a grant ancestor arepermitted. +f the owner revo$es a privilege from a user who granted the privilege to otherusers, then the revo$ing cascades to all the privileges granted.

    8or example, if user A grants a SELECT privilege on a table to user B including the WIT0GRANT OPTION clause, user B can grant to user C the SELECT privilege with the WIT0GRANT OPTION clause, and user C can then grant to user D the SELECT privilege. +f

    user A revo$es privileges from user B , then the privileges granted to user C and user D are also revo$ed.

    uestion

    hen this code is run, what will the user To#1 be able to do as a result@

    GRANT selectON emp_ !e"TO t#$%&

    Options

    1. 4reate indexes on the view

    .

  • 8/10/2019 Oracle Database 11g Controlling User Access and Managing Schema Objects

    13/54

    Option * is incorrect. 'ony has not been granted the privilege with the WIT0GRANT OPTION clause, which would have given him the ability to grant the

    privilege to others.

    Option is correct. 'he SELECT privilege is an available privilege to views, and

    this code would give 'ony the ability to +uery or select from the em/_)"e* view.

    Option - is incorrect. 3iews can be used to restrict a SELECT privilege byincluding only a subset of the columns of the table that it is based on and grantingthe SELECT privilege only on the view. 'herefore, 'ony will not be given full

    permissions to select any column on the table that the em/_)"e* view is basedon as a result of this statement.

    uestion

    hich %uery provides information on the ob-ect privileges granted to the user@

    Options

    1. SELECT 6 .rom USER_ROLE_PRIVS;

    . SELECT 6 .rom USER_SYS_PRIVS;

    B. SELECT 6 .rom USER_TAB_PRIVS_2ADE;

    C. SELECT 6 .rom USER_TAB_PRIVS_RECD;

    !ns"er

    This %uery provides information on the ob-ect privileges granted to the user

    SELECT 6 .rom USER_TAB_PRIVS_RECD;

    Option 1 is incorrect. 'he USER_ROLE_PRIVS data dictionary view providesdetails on the roles accessible by the user.

    Option * is incorrect. 'he USER_SYS_PRIVS data dictionary view provides detailson the system privileges granted to the user.

    Option is incorrect. 'he USER_TAB_PRIVS_2ADE data dictionary view is used to

    provide information on the object privileges granted on the user0s objects.

    Option - is correct. 'he USER_TAB_PRIVS_RECD data dictionary view is used to provide information on the object privileges granted to the user.

    uestion

    hich statement is true about ob-ect privileges@

  • 8/10/2019 Oracle Database 11g Controlling User Access and Managing Schema Objects

    14/54

    Options

    1.

  • 8/10/2019 Oracle Database 11g Controlling User Access and Managing Schema Objects

    15/54

    !bstract

    $his article discusses the use of the A $%& $AB % statement to add, modify, and drop acolumn. $his article also discusses the '%$ U(U'%) and )&*P U(U'%) "* U+('options to mark and delete one or more columns marked as unused.

    !L()* (!+L) statement

    After you create a table, you may need to change the table structure because you omitteda column, your column definition needs to be changed, or you need to remove columns.9ou can do this by using the ALTER TABLE statement. sing the ALTER TABLE statement you can

    add a new column

    modify an existing column define a default value for the new column

    drop a column 9ou can add columns to a table, modify columns, and drop columns from a table by using the

    ALTER TABLE statement. This is the syntax for the ALTER TABLE statement.

    ALTER TABLE tableADD (column datatype =D68A !T e/pr >=,column datatype >...":

    ALTER TABLE table2ODIFY (column datatype =D68A !T e/pr >=,column datatype >...":

    ALTER TABLE tableDROP (column ":

    +n the syntax

    table is the name of the table

    ADD92ODIFY9DROP is the type of modification column is the name of the column

    datatype is the data type and length of the column

    DEFAULT expr specifies the default value for a column

    !dding a column

    These are the guidelines for adding a column to a table

  • 8/10/2019 Oracle Database 11g Controlling User Access and Managing Schema Objects

    16/54

    9ou can add or modify columns.

    9ou cannot specify where the column is to appear. The new column becomes the last column.

    This sample code adds a column named :OB F ID to the DEPT < table. The :OB F ID column becomes the last column in the table.

    ALTER TABLE deptMADD 3=o%_"d VARC0AR>3?44;

    ,igure 1- !dding a column

    Note +f a table already contains rows when a column is added, then the new column isinitially null or ta$es the default value for all the rows. 9ou can add a mandatory NOTNULL column to a table that contains data in other columns only if you specify a defaultvalue. 9ou can add a NOT NULL column to an empty table without the default value.

    odi&ying a column

    9ou can modify a column definition by using the ALTER TABLE statement with the

    2ODIFY clause. 4olumn modification can include changes to a column;s data type, si2e,and default value.

    These are some guidelines for modifying a column

    9ou can increase the width or precision of a numeric column. 9ou can increase the width of character columns.

    9ou can also decrease the width of a column if

    the column contains only null values the table has no rows

    the decrease in column width is not less than the existing values in that column

    o 9ou can change the data type if the column contains only null values. The exception tothis is C0AR #to#VARC0AR> conversions, which can be done with data in the columns.

  • 8/10/2019 Oracle Database 11g Controlling User Access and Managing Schema Objects

    17/54

    o 9ou can also convert a C0AR column to the VARC0AR> data type or convert a VARC0AR> column to the C0AR data type only if the column contains null values or if you do not change thesi2e.

    A change to the default value of a column affects only subse%uent insertions to the table.

    This sample code uses the ALTER TABLE statement to modify a column.

    ALTER TABLE de/ 3@

  • 8/10/2019 Oracle Database 11g Controlling User Access and Managing Schema Objects

    18/54

    ,igure #- Dropping a column

    S)( /N/S)D option

    The SET UNUSED option mar$s one or more columns as unused so that they can bedropped when the demand on system resources is higher. )pecifying this clause does notactually remove the target columns from each row in the table # that is, it does not restorethe dis$ space used by these columns. Therefore, the response time is faster than if you

    executed the DROP clause.

    nused columns are treated as if they were dropped, even though their column dataremains in the table;s rows. After a column has been mar$ed as unused, you have noaccess to that column. A SELECT N %uery will not retrieve data from unused columns. +naddition, the names and types of columns mar$ed unused will not be displayed during aDESCRIBE statement, and you can add to the table a new column with the same name asan unused column. The SET UNUSED information is stored in the USER F UNUSED F COL

    F TABS dictionary view.

    This is the syntax for the SET UNUSED option.

    ALTER TABLE table F name HSET UNUSED ( column F name H":

    O5

    ALTER TABLE table5name HSET UNUSED COLU2N column5name H:

    Note The guidelines for setting a column to UNUSED are similar to those for dropping acolumn.

    D*OP /N/S)D 0OL/ NS option

    DROP UNUSED COLU2NS removes from the table all columns currently mar$ed asunused. 9ou can use this statement when you want to reclaim the extra dis$ space fromunused columns in the table. +f the table contains no unused columns, the statementreturns with no errors.

  • 8/10/2019 Oracle Database 11g Controlling User Access and Managing Schema Objects

    19/54

    This is the syntax for the DROP UNUSED COLU2NS option.

    ALTER TABLE table5name HDROP UNUSED COLU2NS :

    ALTER TABLE deptMSET UNUSED (lastFname ":

    ,igure - /sing t e S)( /N/S)D option

    ALTER TABLE deptMDROP UNUSED COLU2NS :

    ,igure 3- /sing t e /N/S)D 0OL/ NS option

    Summary

    9ou can add, modify, and drop columns from a table by using the ALTER TABLE statement.

    hen a new column is added, it automatically becomes the last column. A column;s data

    type, si2e, and default value can be modified. A column with or without data can bedropped and after a column is dropped, it cannot be recovered.

    The SET UNUSED option mar$s one or more columns as unused so that they can bedropped when the demand on system resources is lower. The DROP UNUSED COLU2NS option removes from the table all columns currently mar$ed as unused.

    anaging Inde'es and 0onstraints

    Learning objective

    After completing this topic, you should be able to recogni e the steps for adding andmanipulating constraints and for creating inde-es.

    1. !dding and de&erring constraints

  • 8/10/2019 Oracle Database 11g Controlling User Access and Managing Schema Objects

    20/54

    9ou can add a constraint for existing tables by using the ALTER TABLE statement withthe ADD clause.

    +n the syntax, table is the name of the table, constraint is the name of the constraint, type is the constraint type, and column is the name of the column affected by the constraint.

    A!T65 TA0!6 table5name H ADD =4O7)T5A+7T constraint5name H>type ( column5name H":

    The constraint name syntax is optional, although recommended. +f you do not name yourconstraints, the system generates constraint names.

    3ere are the guidelines for adding a constraint

    you can add, drop, enable, or disable a constraint, but you cannot modify its structure

    you can add a NOT NULL constraint to an existing column by using the 2ODIFY clause of theALTER TABLE statement

    Note

    6ou can define a NOT NULL column only if the table is empty or if the column hasa value for every row.

    This sample code modifies the E2P> table to add a PRI2ARY KEY constraint on theE2PLOYEE_ID column. 0ecause no constraint name is provided, the constraint isautomatically named by the Oracle server.

    ALTER TABLE em/>2ODIFY em/&o1ee_"d PRI2ARY KEY;

    This sample code creates a FOREIGN KEY constraint on the E2P> table. The constraintensures that a manager exists as a valid employee in the E2P> table.

    ALTER TABLE em/>ADD CONSTRAINT em/_m+r_.FOREIGN KEY3ma#a+er_"d4REFERENCES em/>3em/&o1ee_"d4;

    The ON DELETE CASCADE action allows parent $ey data that is referenced from the childtable to be deleted, but not updated. hen data in the parent $ey is deleted, all rows inthe child table that depend on the deleted parent $ey values are also deleted.

    To specify this referential action, include the ON DELETE CASCADE option in thedefinition of the FOREIGN KEY constraint.

  • 8/10/2019 Oracle Database 11g Controlling User Access and Managing Schema Objects

    21/54

    ALTER TABLE Em/> ADD CONSTRAINT em/_d _.FOREIGN KEY 3De/ar me# _"d4REFERENCES de/ar me# !3de/ar me# _"d4 ON DELETE CASCADE;

    4onstraints can have these attributes

    DEFERRABLE or NOT DEFERRABLE INITIALLY DEFERRED or INITIALLY I22EDIATE

    These attributes can be different for each constraint.

    9ou can defer chec$ing constraints for validity until the end of the transaction. A constraintis deferred if the system chec$s that it is satisfied only on commit.

    +f a deferred constraint is violated, then commit causes the transaction to roll bac$.

    ALTER TABLE de/ >ADD CONSTRAINT de/ >_"d_/PRI2ARY KEY 3de/ar me# _"d4DEFERRABLE INITIALLY DEFERRED

    +f a constraint is immediate, that is it is not deferred, it is chec$ed at the end of eachstatement. +f it is violated, the statement is rolled bac$ immediately.

    +f a constraint causes an action for example, DELETE CASCADE that action is alwaysta$en as part of the statement that caused it, whether the constraint is deferred orimmediate.

    SET CONSTRAINTS de/ >_"d_/ I22EDIATE

    9ou use the SET CONSTRAINTS statement to specify for a particular transaction whethera deferrable constraint is chec$ed following each Data Lanipulation !anguage (DL!"statement or when the transaction is committed.

    To create deferrable constraints, you must create a nonuni%ue index for that constraint.

    SET CONSTRAINTS de/ >_"d_/ I22EDIATE

    This sample code changes all constraints for a session.

    ALTER SESSIONSET CONSTRAINTS I22EDIATE

    3ere is a scenario where constraints need to be deferred.

    4ompany policy dictates that department number C should be changed to C . 4hanging

  • 8/10/2019 Oracle Database 11g Controlling User Access and Managing Schema Objects

    22/54

  • 8/10/2019 Oracle Database 11g Controlling User Access and Managing Schema Objects

    23/54

  • 8/10/2019 Oracle Database 11g Controlling User Access and Managing Schema Objects

    24/54

    SET CONSTRAINTS ALL I22EDIATE;INSERT INTO em/_#e*_!a& VALUES3 3>

  • 8/10/2019 Oracle Database 11g Controlling User Access and Managing Schema Objects

    25/54

    when it attempts to commit the transaction. 'hese constraints are not chec)ed atthe end of statement e/ecution.

    Option * is correct. constraint that is defined as deferrable can be specified aseither INITIALLY DEFERRED or INITIALLY I22EDIATE . "f defined as

    INITIALLY DEFERRED , the Oracle server waits until the transaction ends tochec) the constraint.

    Option is incorrect. 'he INSERT statement would initially be permitted becausethe constraint is DEFERRABLE INITIALLY DEFERRED . "t is only upon an attempt to commit the transaction that the constraint would be chec)ed. "n this situation,the value of ?< would be found to violate the constraint.

    Option - is correct. 'he value being inserted violates the !a&_c constraint. Uponattempting to commit the transaction, the constraint would be chec)ed and thetransaction would be rolled bac).

    2. anipulating constraints

    To drop a constraint, you can identify the constraint name from the USER_CONSTRAINTS and USER_CONS_COLU2NS data dictionary views. Then, you use the ALTER TABLE statement with the DROP clause. The CASCADE option of the DROP clause causes anydependent constraints also to be dropped.

    +n the syntax, table is the name of the table, column is the name of the column affectedby the constraint, and constraint is the name of the constraint.

    A!T65 TA0!6 tableD5O* *5+LA59 K69 ? 7+/ 6 ( column " ?4O7)T5A+7T constraint =4A)4AD6>:

    hen you drop an integrity constraint, that constraint is no longer enforced by the Oracleserver and is no longer available in the data dictionary.

    This sample code removes the manager constraint from the E2P> table.

    ALTER TABLE em/>

    DROP CONSTRAINT em/_m+r_. ;

    This sample code removes the PRI2ARY KEY constraint on the DEPT> table and dropsthe associated FOREIGN KEY constraint on the E2P>8DEPART2ENT_ID column.

    ALTER TABLE de/ >DROP PRI2ARY KEY CASCADE;

  • 8/10/2019 Oracle Database 11g Controlling User Access and Managing Schema Objects

    26/54

    9ou can disable a constraint without dropping it or recreating it by using the ALTERTABLE statement with the DISABLE clause.

    +n the syntax for disabling a constraint, table is the name of the table and constraint is thename of the constraint.

    A!T65 TA0!6 tableD+)A0!6 4O7)T5A+7T constraint =4A)4AD6>:

    These are the guidelines for disabling constraints

    you can use the DISABLE clause in both the CREATE TABLE statement and the ALTER TABLE statement

    the CASCADE clause disables dependent integrity constraints disabling a UNIQUE KEY or PRI2ARY KEY constraint removes the uni%ue index

    This sample code disables the constraint em/_d _. .

    ALTER TABLE em/>DISABLE CONSTRAINT em/_d _. ;

    9ou can enable a constraint without dropping it or re#creating it by using the ALTERTABLE statement with the ENABLE clause.

    +n the syntax for enabling a constraint, table is the name of the table and constraint is thename of the constraint.

    A!T65 TA0!6 table67A0!6 4O7)T5A+7T constraint :

    3ere are the guidelines for enabling constraints

    constraint applies to all table data

    enabling a UNIQUE or PRI2ARY KEY constraint creates a UNIQUE or PRI2ARY KEY index the ENABLE clause can be used in CREATE TABLE and ALTER TABLE enabling a PRI2ARY KEY constraint does not enable foreign $eys

    enabling a UNIQUE KEY constraint or a PRI2ARY KEY constraint re%uires privilegesconstraint applies to all table data

    +f you enable a constraint, that constraint applies to all the data in the table. All the data inthe table must comply with the constraint.

    enabling a UNIQUE or PRIMARY KEY constraint creates a UNIQUE or PRIMARY KEY inde'

  • 8/10/2019 Oracle Database 11g Controlling User Access and Managing Schema Objects

    27/54

    +f you enable a UNIQUE $ey or a PRI2ARY KEY constraint, a UNIQUE or PRI2ARY KEY index is created automatically. +f an index already exists, then it can be used by these$eys.

    t e ENABLE clause can be used in CREATE TABLE and ALTER TABLE

    9ou can use theENABLE

    clause in both theCREATE TABLE

    statement and theALTERTABLE statement.

    enabling a PRIMARY KEY constraint does not enable &oreign $eys

    6nabling a PRI2ARY KEY constraint that was disabled with the CASCADE option does notenable any foreign $eys that are dependent on the primary $ey.

    enabling a UNIQUE KEY constraint or a PRIMARY KEY constraint re%uires privileges

    To enable a UNIQUE KEY constraint or a PRI2ARY KEY constraint, you must have theprivileges necessary to create an index on the table.

    To cascade constraints, the CASCADE CONSTRAINTS clause is used along with the DROPCOLU2N clause. The CASCADE CONSTRAINTS clause drops all referential integrityconstraints that refer to the primary and uni%ue $eys defined on the dropped columns.

    The CASCADE CONSTRAINTS clause also drops all multicolumn constraints defined onthe dropped columns.

    3ere is a sample code that uses the CASCADE CONSTRAINTS clause. Assume that theTEST table is created by using this sample code.

    CREATE TABLE e! 3co& _/ NU2BER PRI2ARY KEY$co&>_. NU2BER$co& NU2BER$co&> NU2BER$CONSTRAINT . _co#! ra"# FOREIGN KEY 3co&>_. 4 REFERENCES

    e! $CONSTRAINT c C0ECK 3co& _/ < a#d co& C0ECK 3co&>_. table.

  • 8/10/2019 Oracle Database 11g Controlling User Access and Managing Schema Objects

    28/54

    ALTER TABLE em/> DROP COLU2N em/&o1ee_"d CASCADE CONSTRAINTS;

    This sample code drops the co& _/ $ co&>_. $ co& $eys and any FOREIGN KEY constraints referencing the PRI2ARY KEY constraint for the TEST table.

    ALTER TABLE e!DROP 3co& _/ $ co&>_. $ co& 4 CASCADE CONSTRAINTS;

    +f all columns referenced by the constraints defined on the dropped columns are alsodropped, then CASCADE CONSTRAINTS is not re%uired.

    8or example, assuming that no other referential constraints from other tables refer to theCOL _PK column, it is valid to submit this statement without the CASCADECONSTRAINTS clause for the TEST table.

    ALTER TABLE e! DROP 3co& _/ $ co&>_. $ co& 4;

    9ou can rename columns and constraints of existing tables by using the ALTER TABLE statement. This sample code creates the mar e "#+ table with the primary $eym +_/ defined on the TEA2_ID column.

    CREATE TABLE mar e "#+ 3 eam_"d NU2BER3 3

  • 8/10/2019 Oracle Database 11g Controlling User Access and Managing Schema Objects

    29/54

    hich clause is used to drop all referential integrity constraints referring to theprimary and uni%ue $eys defined on dropped columns@

    Options

    1. CASCADE CONSTRAINTS

    . ENABLE CONSTRAINT

    B. RENA2E COLU2N

    C. RENA2E CONSTRAINT

    !ns"er

    The CASCADE CONSTRAINTS clause is used to drop all referential integrityconstraints that refer to the primary $ey and uni%ue $eys defined on the droppedcolumns.

    Option 1 is correct. 'he CASCADE CONSTRAINTS clause is used along with theDROP COLU2N clause to drop all referential integrity constraints that refer to the

    primary )ey and uni+ue )eys defined on the dropped columns.

    Option * is incorrect. 'he ENABLE CONSTRAINT clause is used to activate anintegrity constraint that is currently disabled.

    Option is incorrect. 'he RENA2E COLU2N clause of the ALTER TABLE statement is used to rename table columns.

    Option - is incorrect. 'he RENA2E CONSTRAINT clause of the ALTER TABLE statement is used to rename any e/isting constraint for a table.

    #. 0reating and removing inde'es

    9ou can create indexes in two ways

    manually

    automatically

    Two types of indexes can be created

    uni%ue index

    nonuni%ue index

    uni%ue inde'

  • 8/10/2019 Oracle Database 11g Controlling User Access and Managing Schema Objects

    30/54

    The Oracle server automatically creates a uni%ue index when you define a column orgroup of columns in a table to have a PRI2ARY KEY or a UNIQUE $ey constraint. Thename of the index is the name given to the constraint.

    nonuni%ue inde'

    A nonuni%ue index can be created by a user. 8or example, you can create an index for aFOREIGN KEY column to be used in -oins to improve retrieval speed.

    9ou can create an index on one or more columns by issuing the CREATE INDE5 statement or during the creation of a table using the CREATE TABLE statement. 9ou canmanually create a uni%ue index, but it is recommended that you create a uni%ueconstraint, which implicitly creates a uni%ue index.

    +n this sample code, the CREATE INDE5 clause is used with the CREATE TABLE statement to create a primary $ey index explicitly.

    9ou can name your indexes at the time of primary $ey creation to be different from thename of the PRI2ARY KEY constraint.

    CREATE TABLE #e*_em/3em/&o1ee_"d NU2BER3 4 PRI2ARY KEY USING INDE5 3CREATE INDE5 em/_"d_"d7 ON #e*_em/3em/&o1ee_"d44$."r! _#ame VARC0AR>3>3> 44;

    9ou can %uery the USER_INDE5ES data dictionary view for information about yourindexes.

    SELECT "#de7_#ame$ a%&e_#ameFRO2 (!er_"#de7e!W0ERE TABLE_NA2E #e*_em/ ;

    3ere is an example of database behavior when you create an index that is not explicitlynamed.

    This sample code creates an unnamed primary $ey index.

    CREATE TABLE em/_(##amed_"#de73em/&o1ee_"d NU2BER3 4 PRI2ARY KEY $."r! _#ame VARC0AR>3>3> 44;

  • 8/10/2019 Oracle Database 11g Controlling User Access and Managing Schema Objects

    31/54

    9ou can then %uery the USER_INDE5ES data dictionary view using this code to see theOracle server generic name that was given to the index that was created for the PRI2ARYKEY column.

    SELECT "#de7_#ame$ a%&e_#ame

    FRO2 (!er_"#de7e!W0ERE TABLE_NA2E em/_(##amed_"#de7 ;

    9ou can also use an existing index for your PRI2ARY KEY column for example, whenyou are expecting a large data load and want to speed up the operation. 9ou may want todisable the constraints while performing the load and then enable them, in which casehaving a uni%ue index on the primary $ey will still cause the data to be verified during theload.

    9ou can first create a nonuni%ue index on the column designated as PRI2ARY KEY , andthen create the PRI2ARY KEY column and specify that it should use the existing index.

    3ere are the steps

    Step 1 4reate the table.

    Step 2 4reate the index.

    Step # 4reate the primary $ey.

    A function#based index is based on expressions. The index expression is built from tablecolumns, constants, )/! functions, and user#defined functions.

    CREATE INDE5 (//er_de/ _#ame_"d7ON de/ >3UPPER3de/ar me# _#ame44;

    8unction#based indexes defined with the UPPER3 column5name 4 orLOWER3column5name 4 $eywords allow non#case#sensitive searches.

    3ere is the sample code for defining a function#based index with anUPPER3 column5name 4 $eyword.

    CREATE INDE5 (//er_&a! _#ame_"d7 ON em/> 3UPPER3&a! _#ame44;

    SELECT 6FRO2 de/ >W0ERE UPPER3de/ar me# _#ame4 SALES ;

    4onsider this second example of creating a function#based index to facilitate processing%ueries.

  • 8/10/2019 Oracle Database 11g Controlling User Access and Managing Schema Objects

    32/54

    CREATE INDE5 (//er_&a! _#ame_"d7 ON em/> 3UPPER3&a! _#ame44;SELECT 6 FRO2 em/> W0ERE UPPER3&a! _#ame4 KING ;

    The Oracle server uses the index only when that particular function is used in a %uery.8or example, this sample code may use the index, but without the W0ERE clause, the

    Oracle server may perform a full table scan.

    SELECT 6FRO2 em/&o1ee!W0ERE UPPER 3&a! _#ame4 IS NOT NULLORDER BY UPPER 3&a! _#ame4;

    Note

    'he QUERY_REWRITE_ENABLED initiali(ation parameter must be set to TRUE for afunction7based inde/ to be used.

    The Oracle server treats indexes with columns mar$ed DESC as function#based indexes.The columns mar$ed DESC are sorted in descending order.

    9ou cannot modify indexes. To change an index, you must drop it and then recreate it.9ou can remove an index definition from the data dictionary by issuing the DROP INDE5 statement.

    To drop an index, you must be the owner of the index or have the DROP ANY INDE5 privilege.

    +n the syntax for dropping an index, inde/ is the name of the index.

    D5O* +7D6P inde/ :

    +f you drop a table, then indexes, constraints, and triggers are automatically dropped, butviews and se%uences remain.

    3ere is a sample code for dropping an index.

    DROP INDE5 (//er_de/ _#ame_"d7;

    Oracle Database provides a feature for dropping tables. hen you drop a table, thedatabase does not immediately release the space associated with the table. 5ather, thedatabase renames the table and places it in a recycle bin, where it can later be recoveredwith the FLAS0BACK TABLE statement if you find that you dropped the table in error.

    +f you want to immediately release the space associated with the table at the time youissue the DROP TABLE statement, then include the PURGE clause as in this sample code.

  • 8/10/2019 Oracle Database 11g Controlling User Access and Managing Schema Objects

    33/54

    DROP TABLE de/ < PURGE;

    9ou specify PURGE only if you want to drop the table and release the space associatedwith it in a single step. +f you specify PURGE, then the database does not place the tableand its dependent ob-ects into the recycle bin.

    sing the PURGE clause is e%uivalent to first dropping the table and then purging it fromthe recycle bin. This clause saves you one step in the process. +t also provides enhancedsecurity if you want to prevent sensitive material from appearing in the recycle bin.

    Note

    6ou cannot roll bac) a DROP TABLE statement with the PURGE clause, and youcannot recover the table if you drop it with the PURGE clause. 'his feature was notavailable in earlier releases.

    uestion

    hat can you do to create indexes manually@

    Options

    1. 4reate a PRI2ARY KEY constraint

    . 4reate a UNIQUE KEY constraint

    B. +ssue a CREATE INDE5 statement

    C. +ssue a CREATE TABLE statement

    !ns"er

    9ou can use the CREATE INDE5 or CREATE TABLE statement to create an indexmanually.

    Option 1 is incorrect. 'his is considered automatic inde/ creation. 'he Oracleserver automatically creates a uni+ue inde/ when you define a column or group of columns in a table to have a PRI2ARY KEY constraint.

    Option * is incorrect. 'his is considered automatic inde/ creation. 'he Oracle

    server automatically creates a uni+ue inde/ when you define a column or group of columns in a table to have a UNIQUE KEY constraint.

    Option is correct. 6ou can create an inde/ on one or more columns by issuingthe CREATE INDE5 statement.

    Option - is correct. 'he CREATE TABLE statement can be used to e/plicitlycreate an inde/.

  • 8/10/2019 Oracle Database 11g Controlling User Access and Managing Schema Objects

    34/54

    uestion

    hich statements are true about using the PURGE clause of the DROP TABLE statement@

    Options

    1. +t enhances security

    . )pace is released immediately

    B. The statement can be rolled bac$

    C. The table is placed in a recycle bin

    !ns"er

    sing the PURGE clause of the DROP TABLE statement enhances security andreleases space immediately.

    Option 1 is correct. 'he PURGE clause of the DROP TABLE command enhancessecurity if you want to prevent sensitive material from appearing in the recycle bin.

    Option * is correct. hen you drop a table using the PURGE clause, the databaseimmediately releases the space associated with the table.

    Option is incorrect. 6ou cannot roll bac) a DROP TABLE statement with the purge clause, and you cannot recover the table if you drop it with the PURGE clause.

    Option - is incorrect. "f you use the PURGE clause of the DROP TABLE statement,the table and its dependent objects do not go to the recycle bin.

    Summary

    9ou can add constraints by using the ALTER TABLE statement with the ADD clause.4onstraints can be DEFERRABLE, NOT DEFERRABLE , INITIALLY DEFERRED , orINITIALLY I22EDIATE . 9ou can use the SET CONSTRAINTS statement to specify, fora particular transaction, whether a deferrable constraint is chec$ed.

    9ou use ALTER TABLE with the DROP clause to drop constraints, with the DISABLE clause to disable constraints, or with the ENABLE clause to enable constraints. 9ou usethe CASCADE CONSTRAINTS clause with DROP COLU2N to cascade constraints. 9ou canuse ALTER TABLE to rename columns and constraints.

    9ou can create uni%ue or nonuni%ue indexes. The CREATE INDE5 clause is used with

  • 8/10/2019 Oracle Database 11g Controlling User Access and Managing Schema Objects

    35/54

    the CREATE TABLE statement to create a primary $ey index explicitly. To change anindex, you must drop it and recreate it. 9ou use DROP INDE5 to drop an index.

    ,las bac$ Operations and )'ternal (ables

    Learning objective

    After completing this topic, you should be able to identify the steps for recovering yourdatabase using flashback, and for manipulating e-ternal data.

    1. Per&orming t e ,L!S4+!05 (!+L) operation

    Oracle 8lashbac$ Table enables you to recover tables to a specified point in time with asingle statement. 9ou can restore table data along with associated indexes, andconstraints, when the database is online, undoing changes to only the specified tables.

    The 8lashbac$ Table feature is similar to a self#service repair tool. 8or example, if youhave accidentally deleted important rows from a table and then wanted to recover thedeleted rows, you can use the FLAS0BACK TABLE statement to restore the table to thetime before the deletion and see the missing rows in the table.

    hen using the FLAS0BACK TABLE statement, you can revert the table and its contentsto a certain time or to a system change number ()47".

    Note

    S#8 is an integer value associated with each change in the database. "t is auni+ue incremental number in the database. 4very time you commit a transaction,a new S#8 is recorded.

    Oracle Database provides a )/! data definition language (DD!" command, FLAS0BACKTABLE, to restore the state of a table to an earlier point in time in case it is inadvertentlydeleted or modified. The FLAS0BACK TABLE command is a self#service repair tool torestore data in a table along with associated attributes such as indexes or views. This isdone when the database is online by rolling bac$ only the subse%uent changes to thegiven table.

    As compared to traditional recovery mechanisms, the self#service repair feature offerssignificant benefits such as ease of use, availability, and faster restoration. +t also ta$esthe burden off the database administrator (D0A" to find and restore application#specificproperties. The 8lashbac$ Table feature does not address physical corruption caused bya bad dis$.

  • 8/10/2019 Oracle Database 11g Controlling User Access and Managing Schema Objects

    36/54

    9ou can invo$e a FLAS0BACK TABLE operation on one or more tables, and even ontables in different schemas. 9ou specify the point in time to which you want to revert byproviding a valid time stamp. 0y default, database triggers are disabled during theflashbac$ operation for all tables involved. 9ou can override this default behavior byspecifying the ENABLE TRIGGERS clause.

    8!A)30A4K TA0!6 =schema.>table=,= schema.>table >...TO E T+L6)TAL* ? )47 G expr = E 67A0!6 ? D+)A0!6 G T5+

  • 8/10/2019 Oracle Database 11g Controlling User Access and Managing Schema Objects

    37/54

    +dentify the true statements about the Oracle 8lashbac$ Table feature.

    Options

    1. +t enables you to recover only to a specified point in time

    . The database must be offline when performing a flashbac$ operation

    B. The operation can be performed on one or more tables at once

    C. 9ou can use it to restore table data

    !ns"er

    9ou can perform the 8lashbac$ Table operation on one or more tables and usethis feature to restore table data.

    Option 1 is incorrect. Oracle 9lashbac) 'able enables you to revert the table andits content to a certain time or to an S#8. Oracle 9lashbac) table is not limited to

    recovering only to a specified point in time.

    Option * is incorrect. 6ou can restore table data along with associated inde/es,and constraints, when the database is online, undoing changes to only thespecified tables.

    Option is correct. 6ou can invo)e a FLAS0BACK TABLE operation on one ormore tables, and even on tables in different schemas.

    Option - is correct. 'he FLAS0BACK TABLE command is a self7service repair tool to restore data in a table along with associated attributes such as inde/es or

    views.

    2. 0reating and using e'ternal tables

    An external table is a read#only table whose metadata is stored in the database and thedata is stored outside the database. This external table definition can be thought of as aview that is used for running any )/! %uery against external data without re%uiring thatthe external data first be loaded into the database. The external table data can be %ueriedand -oined directly and in parallel without re%uiring that the external data first be loaded inthe database. 9ou can use )/!, *!')/!, and Qava to %uery the data in an external table.

    The main differences between external tables and regular tables are

    externally organi2ed tables are read#only no data manipulation language (DL!" operations are possible in external tables

    no indexes can be created on external tables

  • 8/10/2019 Oracle Database 11g Controlling User Access and Managing Schema Objects

    38/54

    3owever, you can create an external table and unload data using the CREATE TABLEAS SELECT command.

    The Oracle server provides these two ma-or access drivers for external tables

    ORACLE_LOADER ORACLE_DATAPU2P

    ORACLE_LOADER

    The ORACLE_LOADER or loader access driver is used for reading data from external fileswhose format can be interpreted by the )/!N!oader utility. 7ote that all )/!N!oaderfunctionalities are not supported with external tables.

    ORACLE_DATAPUMP

    The ORACLE_DATAPU2P access driver can be used to both import and export data using aplatform#independent format. The ORACLE_DATAPU2P access driver writes rows from a

    SELECT statement to be loaded into an external table as part of a CREATETABLE888ORGANIHATION E5TERNAL888AS SELECT statement. 9ou can then use aSELECT statement to read data out of that data file. 9ou can also create an external tabledefinition on another system and use that data file. This allows data to be moved betweenOracle databases.

    9ou use the CREATE DIRECTORY statement to create a directory ob-ect. A directoryob-ect specifies an alias for a directory on the server;s file system where an external datasource resides. 9ou can use directory names when referring to an external data source,rather than hard code the operating system path name, for greater file managementflexibility.

    CREATE OR REPLACE DIRECTORY em/_d"rAS J em/_d"r ;

    9ou must have the CREATE ANY DIRECTORY system privileges to create directories.hen you create a directory, you are automatically granted the READ and WRITE ob-ect

    privileges and can grant READ and WRITE privileges to other users and roles. The D0Acan also grant these privileges to other users and roles.

    GRANT READ ON DIRECTORY em/_d"r TO ,r;

    A user needs READ privileges to access all directories used in external tables and WRITE privileges for the log, bad, and discard file locations being used. +n addition, a WRITE privilege is necessary when the external table framewor$ is being used to unload data.

    Oracle also provides the ORACLE_DATAPU2P type, with which you can unload data (thatis, read data from a table in the database and insert it into an external table" and thenreload it into an Oracle database. This is a one#time operation that can be done when the

  • 8/10/2019 Oracle Database 11g Controlling User Access and Managing Schema Objects

    39/54

    table is created. After the creation and initial population is done, you cannot update,insert, or delete any rows.

    3ere is the syntax for creating the directory ob-ect.

    456AT6 =O5 56*!A46> D+564TO59 directory A) ; path5name ;:

    +n the directory ob-ect syntax, these items are used

    OR REPLACE directory

    path#name

    OR REPLACE

    9ou can specify OR REPLACE to re#create the directory database ob-ect if it already exists.9ou can use this clause to change the definition of an existing directory without dropping,

    re#creating, and re#granting database ob-ect privileges previously granted on the directory.sers who were previously granted privileges on a redefined directory can continue to

    access the directory without re%uiring that the privileges be re#granted.

    directory

    9ou use directory to specify the name of the directory ob-ect to be created. The maximumlength of the directory name is B bytes. 9ou cannot %ualify a directory ob-ect with aschema name.

    path_name

    9ou use path#name to specify the full path name of the operating system directory to be

    accessed. The path name is case#sensitive.

    9ou create external tables using the ORGANIHATION E5TERNAL clause of the CREATETABLE statement. 9ou are not, in fact, creating a table. 5ather, you are creating metadatain the data dictionary that you can use to access external data. 9ou use theORGANIHATION clause to specify the order in which the data rows of the table are stored.0y specifying E5TERNAL in the ORGANIHATION clause, you indicate that the table is aread#only table located outside the database.

    CREATE TABLE table_name 3 col_name datatype $ J 4

    ORGANIHATION E5TERNAL 3TYPE access_driver_type DEFAULT DIRECTORY directory_name ACCESS PARA2ETERS 3J 4 4 LOCATION 3 location_specifier 4 4RE:ECT LI2IT < 9 number 9 UNLI2ITEDM;

  • 8/10/2019 Oracle Database 11g Controlling User Access and Managing Schema Objects

    40/54

    Note

    'he e/ternal files must already e/ist outside the database.

    The clauses used in the CREATE TABLE command are

    TYPE DEFAULT DIRECTORY ACCESS PARA2ETERS LOCATION RE:ECT LI2IT

    TYPE

    TYPE access#driver#type indicates the access driver of the external table. The accessdriver is the application programming interface (A*+" that interprets the external data for

    the database. +f you do not specify TYPE, Oracle uses the default access driver,ORACLE_LOADER. The other option is ORACLE_DATAPU2P .

    DE'AULT DIRECTORY

    The DEFAULT DIRECTORY clause is used to specify one or more Oracle databasedirectory ob-ects that correspond to directories on the file system where the external datasources may reside.

    ACCESS PARAMETERS

    The optional ACCESS PARA2ETERS clause enables you to assign values to theparameters of the specific access driver for this external table.

    LOCATION The LOCATION clause is used to specify one external locator for each external datasource. sually, location#specifier is a file, but it need not be.

    RE2ECT LIMIT

    The RE:ECT LI2IT clause enables you to specify how many conversion errors can occur during a %uery of the external data before an Oracle error is returned and the %uery isaborted. The default value is

  • 8/10/2019 Oracle Database 11g Controlling User Access and Managing Schema Objects

    41/54

    A))6!64T N 85OL S:

    )uppose that there is a flat file that has records in this format.

    +n this format the records are delimited by new lines, and the fields are all terminated by acomma ( , ". The name of the file is em/_d"r em/8da .

    To convert this file as the data source for an external table, whose metadata will reside inthe database, you need to create a directory ob-ect, em/_d"r .

    CREATE DIRECTORY em/_d"r AS em/_d"r ;

    7ext you need to run this CREATE TABLE command. This sample code illustrates thetable specification to create an external table for the file em/_d"r em/8da .

    CREATE TABLE o&dem/ 3 .#ame c,ar3> 4$ ame C0AR3> 44 ORGANIHATION E5TERNAL 3TYPE ORACLE_LOADER DEFAULT DIRECTORY em/_d"r ACCESS PARA2ETERS 3RECORDS DELI2ITED BY NEWLINE NOBADFILE NOLOGFILE FIELDS TER2INATED BY $ 3.#ame POSITION 3 >> 4 C0AR44 LOCATION 3 em/8da 44 PARALLEL RE:ECT LI2IT >

  • 8/10/2019 Oracle Database 11g Controlling User Access and Managing Schema Objects

    42/54

    PARALLEL

    The PARALLEL clause enables five parallel execution servers to simultaneously scan theexternal data sources (files" when executing the INSERT INTO TABLE statement. 8orexample, if PARALLEL were specified, then more than one parallel execution server canbe wor$ing on a data source. 0ecause external tables can be very large, for performancereasons, it is advisable to specify the PARALLEL clause, or a parallel hint for the %uery.

    RE2ECT LIMIT

    The RE:ECT LI2IT clause specifies that if more than conversion errors occur duringa %uery of the external data, then the %uery is aborted and an error is returned. Theseconversion errors can arise when the access driver tries to transform the data in the datafile to match the external table definition.

    After the CREATE TABLE command executes successfully, the OLDE2P external tablecan be described and %ueried li$e a relational table.

    An external table does not describe any data that is stored in the database and how datais stored in the external source. +nstead, it describes how the external table layer mustpresent the data to the server. +t is the responsibility of the access driver and the externaltable layer to do the necessary transformations re%uired on the data in the data file sothat it matches the external table definition.

    hen the database server accesses data in an external source, it calls the appropriateaccess driver to get the data from an external source in a form that the database serverexpects. +t is important to remember that the description of the data in the data source isseparate from the definition of the external table. The source file can contain more orfewer fields than there are columns in the table. Also, the data types for fields in the data

    source can be different from the columns in the table. The access driver ensures that thedata from the data source is processed so that it matches the definition of the externaltable.

    9ou can perform the unload and reload operations with external tables using theORACLE_DATAPU2P access driver.

    Note

    "n the conte/t of e/ternal tables, loading data refers to the act of data being readfrom an e/ternal table and loaded into a table in the database. Unloading datarefers to the act of reading data from a table and inserting it into an e/ternal table.

    This sample code illustrates the table specification to create an external table by usingthe ORACLE_DATAPU2P access driver. Data is then populated into the two filesem/ 8e7/ and em/>8e7/ .

    CREATE TABLE em/_e7 3em/&o1ee_"d$ ."r! _#ame$ &a! _#ame4

  • 8/10/2019 Oracle Database 11g Controlling User Access and Managing Schema Objects

    43/54

    ORGANIHATION E5TERNAL 3 TYPE ORACLE_DATAPU2P DEFAULT DIRECTORY em/_d"r LOCATION 3 em/ 8e7/ $ em/>8e7/ 4 4 PARALLELASSELECT em/&o1ee_"d$ ."r! _#ame$ &a! _#ameFRO2 em/&o1ee!;

    To populate data read from the E2PLOYEES table into an external table, you first create adirectory ob-ect, em/_d"r .

    CREATE DIRECTORY em/_d"r AS em/_d"r ;

    7ext, you need to run the CREATE TABLE command.

    CREATE TABLE em/_e7 3em/&o1ee_"d$ ."r! _#ame$ &a! _#ame4 ORGANIHATION E5TERNAL 3 TYPE ORACLE_DATAPU2P DEFAULT DIRECTORY em/_d"r LOCATION 3 em/ 8e7/ $ em/>8e7/ 4 4 PARALLELASSELECT em/&o1ee_"d$ ."r! _#ame$ &a! _#ameFRO2 em/&o1ee!;

    Note

    'he em/_d"r directory is the same as that created in the previous e/ample usingORACLE_LOADER.

    9ou can %uery the external table by executing this code.

    SELECT 6 FRO2 em/_e7 ;

    uestion

    hich are true statements about the characteristics of external tables@

  • 8/10/2019 Oracle Database 11g Controlling User Access and Managing Schema Objects

    44/54

    Options

    1. Their data is stored inside the database

    . Their metadata is stored outside the database

    B. They are read'write tables

    C. They cannot have indexes created on them

    !ns"er

    9ou cannot create indexes on external tables.

    Option 1 is incorrect. 'he data of an e/ternal table is stored outside the database.

    Option * is incorrect. 'he metadata of an e/ternal table is stored in the database.

    Option is incorrect. ll e/ternally organi(ed tables are read7only. 8o D

    operations are possible.

    Option - is correct. ll e/ternally organi(ed tables do not allow D

  • 8/10/2019 Oracle Database 11g Controlling User Access and Managing Schema Objects

    45/54

    Option is incorrect. 'he RE:ECT LI2IT clause is not used to indicate theaccess driver of the e/ternal table. "t is used to specify how many conversionerrors can occur during a +uery of the e/ternal data before an Oracle error isreturned and the +uery is aborted.

    Option - is correct. TYPE is used to indicate the access driver of the e/ternaltable. "f you do not specify TYPE, Oracle uses the default access driver,ORACLE_LOADER.

    Summary

    Oracle 8lashbac$ Table enables you to recover tables to a specified point in time with asingle statement. 9ou can restore table data along with associated indexes andconstraints by using FLAS0BACK mechanics.

    9ou can create an external table by using thee7 er#a&_ a%&e

    clause. An externaltable is a read#only table whose metadata is stored in the database and the data is storedoutside the database. 9ou can use )/!, *!')/!, and Qava to %uery the data in anexternal table.

    6or$ing "it (ables7 Inde'es and 0onstraints

    Learning objective

    After completing this topic, you should be able to alter a table by dropping columns andadding constraints and inde-es.

    )'ercise overvie"

    +n this exercise, you are re%uired to use the CREATE TABLE or ALTER TABLE commands to add, modify, drop, and restore columns.

    This involves the following tas$s

    creating tables and modifying columns

    dropping and restoring tables dropping columns and using constraints

    removing tables and creating indexes

    9ou are an Oracle )/! administrator for a company. As part of your responsibilities toupdate the employee information, you have to modify the structure of the table, createnew columns, copy information to the existing tables, and delete the tables created forupdating information.

  • 8/10/2019 Oracle Database 11g Controlling User Access and Managing Schema Objects

    46/54

  • 8/10/2019 Oracle Database 11g Controlling User Access and Managing Schema Objects

    47/54

    9ou should use this code to create the table

    CREATE TABLE em/>3"d NU2BER3 4$&a! _#ame VARC0AR>3> 4$."r! _#ame VARC0AR>3> 4$de/ _"d NU2BER3 44;DESCRIBE em/>

    Option 1 is incorrect. 'he VARC0AR> data type for the LAST_NA2E column shouldhave a variable7length character value of *=, and the NU2BER data type for theDEPT_ID column should have a length value of >.

    Option * is correct. 'his statement will create a table called E2P> with an ID column having a ma/imum number of > digits, a LAST_NA2E column having ama/imum of *= characters, a FIRST_NA2E column having a ma/imum of *=

    characters, and a DEPT_ID column having a NU2BER data type value of >.

    Option is incorrect. 'his statement is missing parentheses around the values forthe NU2BER and VARC0AR> data types.

    Option - is incorrect. 'he ID column should be created with a number data typeand the LAST_NA2E column should be created with the VARC0AR> data type.

    Step 2 o& #

    hich statement will modify the E2P> table to allow for longer employee lastnames, and verify that the table was created@

    Options

    1. ALTER TABLE em/>2ODIFY 3."r! _#ame NU2BER3

    . ALTER TABLE em/>2ODIFY 3."r! _#ame VARC0AR>

    B. ALTER TABLE em/>

    2ODIFY 3&a! _#ame VARC0AR>3> 44;DESCRIBE em/>

    C. ALTER TABLE em/>2ODIFY 3&a! _#ame VARC0AR>3

    *esult

  • 8/10/2019 Oracle Database 11g Controlling User Access and Managing Schema Objects

    48/54

    9ou should use this code to allow for longer employee last names

    ALTER TABLE em/>2ODIFY 3&a! _#ame VARC0AR>3

    Option 1 is incorrect. 'he data type should be a VARC0AR> data type not aNU2BER data type. "t should also allow for longer character values on theLAST_NA2E column and not the FIRST_NA2E column as indicated.

    Option * is incorrect. 'his statement is missing the parentheses around the valuefor VARC0AR> data type. "t should also allow for longer character values on theLAST_NA2E column and not the FIRST_NA2E column as indicated.

    Option is incorrect. 'his statement will not allow for longer employee last namesas the VARC0AR> data type is still set to a length value of *=.

    Option - is correct. 'his statement will alter the E2P> table by modifying the valueof the data type for the LAST_NA2E column to =? characters instead of the original ma/imum value of *=.

    Step # o& #

    4reate the E2PLOYEES> table based on the structure of the E2PLOYEES table.+nclude only the E2PLOYEE_ID , FIRST_NA2E , LAST_NA2E , SALARY, andDEPART2ENT_ID columns. 7ame the columns in your new table ID ,FIRST_NA2E , LAST_NA2E , SALARY, and DEPT_ID , respectively.

    Options

    1. CREATE TABLE em/&o1ee!> ASSELECT em/&o1ee_"d "d$ ."r! _#ame$ &a! _#ame$de/ar me# _"d de/ _"dFRO2 em/&o1ee!;

    . CREATE TABLE em/&o1ee!> ASSELECT em/&o1ee_"d "d$ ."r! _#ame$ &a! _#ame$ !a&ar1$de/ar me# _"d de/ _"dFRO2 em/&o1ee!;

    B. CREATE TABLE em/&o1ee! ASSELECT em/&o1ee_"d "d$ ."r! _#ame$ &a! _#ame$ !a&ar1$de/ar me# _"d de/ _"dFRO2 em/&o1ee!>;

    C. CREATE TABLE em/&o1ee!> ASSELECT em/&o1ee_"d$ ."r! _#ame$ &a! _#ame$ !a&ar1$de/ar me# _"dFRO2 em/&o1ee!;

  • 8/10/2019 Oracle Database 11g Controlling User Access and Managing Schema Objects

    49/54

    *esult

    9ou should use this code to create the table

    CREATE TABLE em/&o1ee!> AS

    SELECT em/&o1ee_"d "d$ ."r! _#ame$ &a! _#ame$ !a&ar1$de/ar me# _"d de/ _"dFRO2 em/&o1ee!;

    Option 1 is incorrect. 'his statement is missing the re+uested SALARY columnwithin the SELECT statement.

    Option * is correct. 'his statement will create a table called E2PLOYEES> basedon the structure of the E2PLOYEES table. "t will only include the E2PLOYEE_ID ,FIRST_NA2E , LAST_NA2E , SALARY, and DEPART2ENT_ID columns. "t will alsorename the E2PLOYEE_ID column to ID and the DEPART2ENT_ID column to

    DEPT_ID .

    Option is incorrect. 'he CREATE TABLE statement should be followed by thetable name E2PLOYEES> and the FRO2 clause should be followed by the tablename E2PLOYEES .

    Option - is incorrect. 'his statement is missing the column aliases of ID andDEPT_ID for the E2PLOYEE_ID and DEPART2ENT_ID columns.

    (as$ 2- Dropping and restoring tables

    9ou now want to delete the E2P> table that you previously created and then view therecycle bin to see if the table is present.

    Step 1 o& #

    9ou need to delete the E2P> table that stored longer employee last names.

    Type the code to drop the E2P> table that was previously created.

    MISSING CODE

    *esult

    9ou use the code

    DROP TABLE em/>;

  • 8/10/2019 Oracle Database 11g Controlling User Access and Managing Schema Objects

    50/54

    to drop a table. Oracle Database provides this feature for dropping tables. henyou drop a table, the database does not immediately release the space associatedwith the table. 5ather, the database renames the table and places it in a recyclebin.

    Step 2 o& #

    9ou now want to verify that the E2P> table is present in the recyclin bin. 9ou wantto view the original name, the operation on how the table was deleted, and at whattime it was dropped.

    Type the code to %uery the recycle bin.

    MISSING CODE

    *esult

    9ou use the code

    SELECT or"+"#a&_#ame$ o/era "o#$ dro/ "me FRO2 rec1c&e%"#;to %uery the recycle bin. The recycle bin is actually a data dictionary tablecontaining information about dropped ob-ects. Dropped tables and any associatedob-ects such as indexes, constraints, nested tables, and so on are notremoved and still occupy space. They continue to count against user space %uotasuntil specifically purged from the recycle bin.

    9ou now want to restore the E2P> table to a state before the DROP statement.

    Step # o& #

    9ou need to restore the E2P> table to a state before the DROP statement andverify that is was restored.

    Type the code to restore the E2P> table.

    3M!ss!$4 c#5e.

    DESC emp6&

    *esult

    9ou use the codeFLAS0BACK TABLE em/> TO BEFORE DROP;DESC em/>;to restore a table to a state before the DROP statement. Oracle 8lashbac$ Table

  • 8/10/2019 Oracle Database 11g Controlling User Access and Managing Schema Objects

    51/54

    enables you to recover tables to a specified point in time with a single statement.9ou can restore table data along with associated indexes, and constraints, whilethe database is online, undoing changes to only the specified tables.

    (as$ #- Dropping columns and using constraints

    9ou now want to drop the FIRST_NA2E column and mar$ the DEPT_ID column asUNUSED in the E2PLOYEES> table. 9ou will also add a PRI2ARY KEY constraint and aC0ECK constraint to a table.

    Step 1 o&

    9ou need to drop the FIRST_NA2E column from the E2PLOYEES> table andconfirm your modification by chec$ing the description of the table.

    Type the code to drop the FIRST_NA2E column from the table.

    ALTER TABLE empl#%ees6 MISSING CODE

    DESCRIBE empl#%ees6

    *esult

    9ou use the codeDROP COLU2N ."r! _#ame;

    to drop the FIRST_NA2E column from the E2PLOYEES> table. 9ou can drop acolumn from a table by using the ALTER TABLE statement with the DROPCOLU2N clause. 5emember, dropping a column can ta$e some time if the columnhas a large number of values. +n this case, it may be better to set it to be unusedand drop it when there are fewer users on the system to avoid extended loc$s.

    Step 2 o&

    9ou need to mar$ the DEPT_ID column as UNUSED in the E2PLOYEES> table.

    4omplete the code.

    ALTER TABLE empl#%ees6 MISSING CODE

    DESCRIBE empl#%ees6

    *esult

  • 8/10/2019 Oracle Database 11g Controlling User Access and Managing Schema Objects

    52/54

    9ou use the codeALTER TABLE em/&o1ee!>SET UNUSED 3de/ _"d4;DESCRIBE em/&o1ee!>to mar$ the DEPT_ID column as UNUSED in the E2PLOYEES> table. The SET

    UNUSED option mar$s one or more columns as unused so that they can bedropped when the demand on system resources is lower. )pecifying this clausedoes not actually remove the target columns from each row in the table (that is, itdoes not restore the dis$ space used by these columns".

    Step # o&

    9ou need to add a table#level PRI2ARY KEY constraint to the E2P> table on the IDcolumn. The name of the constraint should be m1_em/_"d_/ and should benamed at creation.

    +dentify the code that successfully completes this tas$.

    Options

    1. ALTER TABLE em/>ADD CONSTRAINT m1_em/_"d_/ PRI2ARY KEY 3"d4;

    . ALTER TABLE em/>ADD CONSTRAINT m1_em/"d_/ PRI2ARY KEY em/&o1ee_"d;

    B. ALTER TABLE em/>2ODIFY CONSTRAINT m1_em/_"d_/ PRI2ARY KEY 3em/&o1ee_"d4;

    C. ALTER TABLE em/>

    2ODIFY CONSTRAINT m1_em/_"d_/ PRI2ARY KEY 3"d4;

    *esult

    9ou should use this code to add a table#level PRI2ARY KEY constraint to theE2P> table on the ID column.

    ALTER TABLE em/>ADD CONSTRAINT m1_em/_"d_/ PRI2ARY KEY 3"d4;

    Option 1 is correct. 'his statement will add a table7level PRI2ARY KEY constraint

    to the E2P> table on the ID column.

    Option * is incorrect. 'he name of the constraint should be m1_em/_"d_/ , notm1_em/"d_/ . 'his statement is also missing the parentheses around the ID column.

    Option is incorrect. 6ou add a constraint to an e/isting table by using the ALTERTABLE statement with the ADD clause not the 2ODIFY clause. 'he 2ODIFY clause

  • 8/10/2019 Oracle Database 11g Controlling User Access and Managing Schema Objects

    53/54

    is used to add a NOT NULL constraint to an e/isting column. 'his statement isalso missing the parentheses around the ID column.

    Option - is incorrect. 6ou add a constraint to an e/isting table by using the ALTERTABLE statement with the ADD clause, not the 2ODIFY clause. 'he 2ODIFY

    clause is used to add a NOT NULL constraint to an e/isting column.

    Step o&

    9ou need to modify the E2P> table by adding a CO22ISSION column of theNU2BER data type, precision , scale , and add a constraint calledm1_em/_comm_c to the CO22ISSION column that ensures that a commissionvalue is greater than 2ero.

    4omplete the code.

    ALTER TABLE emp6 MISSING CODE

    *esult

    9ou use the codeALTER TABLE em/>ADD comm"!!"o# NU2BER3>$>4 CONSTRAINT m1_em/_comm_c C0ECK3comm"!!"o# table by using the ADD clause in an ALTER TABLE statement, which at the same time adds the m1_em/_comm_c chec$ constrainton the CO22ISSION column.

    (as$ - *emoving tables and creating inde'es

    9ou now want to completely remove the E2P> table from the database. 9ou then need tocreate an index for a PRI2ARY KEY column.

    Step 1 o& 2

    9ou need to drop the E2P> table so that it cannot be restored and chec$ therecycle bin.

    4omplete the code.

  • 8/10/2019 Oracle Database 11g Controlling User Access and Managing Schema Objects

    54/54

    3M!ss!$4 C#5e. SELECT #-!4!$(l_$(me7 #pe-(t!#$7 5-#pt!me'ROM -ec%cle*!$&

    *esult

    9ou use the codeDROP TABLE em/> PURGE;SELECT or"+"#a&_#ame$ o/era "o#$ dro/ "meFRO2 rec1c&e%"#;to drop the E2P> table so that it cannot be restored. 9ou specify PURGE only if youwant to drop the table and release the space associated with it in a single step. +fyou specify PURGE, then the database does not place the table and its dependentob-ects into the recycle bin.

    Step 2 o& 2

    9ou need to create the DEPT_NA2ED_INDE5 table with a PRI2ARY KEY constraint on the DEPTNO column. 9ou want to create an index namedde/ _/ _"d7 for the PRI2ARY KEY column.

    4omplete the code.

    CREATE TABLE DEPT_NAMED_INDE8,5ept$# NUMBER,91

    MISSING CODE

    ,CREATE INDE8 5ept_p)_!5: ONDEPT_NAMED_INDE8,5ept$#1175$(me VARCHAR6,;011&

    *esult

    9ou use the codePRI2ARY KEY USING INDE5to create the DEPT_NA2ED_INDE5 table with a PRI2ARY KEY constraint. 9ouuse the PRI2ARY KEY USING INDE5 clause to create an index for the PRI2ARYKEY column with the CREATE INDE5 statement.