d17111 gc30 sg1

Download D17111 gc30 sg1

If you can't read please download the document

Upload: myonlineworld

Post on 01-Nov-2014

32 views

Category:

Technology


9 download

DESCRIPTION

 

TRANSCRIPT

  • 1. Unauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates. SQL Star International Limiteda) hasc om ail uide gm 10g:Oracle Database nt G SQL@rale tudeFundamentals IIa hlk his S (r Guide A OStudente t Volume 1sNKR to uI e LMA icensA HU ble l L E R nsfera RA -tra KA nonD17111GC30Edition 3.0January 2009D57873

2. SQL Star International LimitedAuthorsCopyright 2009, Oracle. All rights reserved. DisclaimerSalome ClementChaitanya KoratamaddiThis document contains proprietary information and is protected by copyright andPriya Vennapusaother intellectual property laws. You may copy and print this document solely for your own use in an Oracle training course. The document may not be modified or altered in any way. Except where your use constitutes "fair use" under copyright law, you mayTechnical Contributors not use, share, download, upload, copy, print, display, perform, reproduce, publish,Unauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates. license, post, transmit, or distribute this document in whole or in part without theand Reviewers express authorization of Oracle.Claire Bennett The information contained in this document is subject to change without notice. If you find any problems in the document, please report them in writing to: Oracle University,Brian Boxx 500 Oracle Parkway, Redwood Shores, California 94065 USA. This document is notZarko Cesljaswarranted to be error-free.Laurent Dereac Restricted Rights NoticeNancy GreenbergYash JainIf this documentation is delivered to the United States Government or anyone using the documentation on behalf of the United States Government, the following notice isAngelika Krupp applicable:ahasMalika MarghadiPriya Nathan U.S. GOVERNMENT RIGHTS)Narayanan Radhakrishnanc om The U.S. Governments rights to use, modify, reproduce, release, perform, display, orail uide disclose these training materials are restricted by the terms of the applicable OracleBryan Robertslicense agreement and/or the applicable U.S. Government contract.Lata Shivaprasad Trademark Notice gm t G @ n rale tudeNaoko Susuki a Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Otherhlk his S names may be trademarks of their respective owners.r Editors A O ( se t Nita Pavitran I KR to u Atanu RaychaudhuriAN nse U L M lice AH rable Graphic Designer RL Sharmansfe SanjeevEAAR on-tra K nPublishersJobi VargheseGiri Venugopal 3. SQL Star International LimitedContentsUnauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates.PrefaceI IntroductionObjectives I-2Course Objectives I-3Course Overview I-4Course Application I-5aSummary I-6) hasc om 1 Controlling User Accessail uide Objectives 1-2gm t G @ n Controlling User Access 1-3 a rale tude Privileges 1-4r hlk his S System Privileges 1-5 AO ( se t Creating Users 1-6I KR to u AN ns User System Privileges 1-7 eL M lice Granting System Privileges 1-8 U What Is a Role? le R AHandrab 1-9 Privileges to a Role 1-10 LE ansfe Granting 1-11 CreatingA Changing Your PasswordAR on-tr Privileges 1-12 K n ObjectGranting Object Privileges 1-14Passing On Your Privileges 1-15Confirming Privileges Granted 1-16Revoking Object Privileges 1-17Summary 1-19Practice 1: Overview 1-202 Managing Schema ObjectsObjectives 2-2ALTER TABLE Statement 2-3Adding a Column 2-5Modifying a Column 2-6Dropping a Column 2-7SET UNUSED Option 2-8 iii 4. SQL Star International LimitedAdding a Constraint Syntax 2-10Adding a Constraint 2-11ON DELETE CASCADE 2-12Deferring Constraints 2-13Unauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates.Dropping a Constraint 2-14Disabling Constraints 2-15Enabling Constraints 2-16Cascading Constraints 2-18Overview of Indexes 2-20CREATE INDEX with the CREATE TABLE Statement 2-21Function-Based Indexes 2-23Removing an Index 2-24 aDROP TABLE PURGE 2-25 ) hasFLASHBACK TABLE Statement 2-26 c om External Tables 2-28 ail uideCreating a Directory for the External Table 2-30gm t GCreating an External Table 2-32 le@ nra2-34 tudea hlk his SCreating an External Table by Using ORACLE_LOADER rQuerying External Tables 2-36 A O ( se tSummary 2-37Practice 2: Overview 2-38 NI KR to u A nse UL M lice3 Manipulating Large DataeAH rabl Sets RObjectives 3-2 fe LE ans to Manipulate Data 3-3 A trAR onSubqueries Another Table 3-4Using - K Copying Rows from nInserting Using a Subquery as a Target 3-5Retrieving Data with a Subquery as Source 3-7Updating Two Columns with a Subquery 3-8Updating Rows Based on Another Table 3-9Deleting Rows Based on Another Table 3-10Using the WITH CHECK OPTION Keyword on DML Statements 3-11Overview of the Explicit Default Feature 3-12Using Explicit Default Values 3-13Overview of Multitable INSERT Statements 3-14Types of Multitable INSERT Statements 3-16Multitable INSERT Statements 3-17Unconditional INSERT ALL 3-19Conditional INSERT ALL 3-20Conditional INSERT FIRST 3-22iv 5. SQL Star International LimitedPivoting INSERT 3-24MERGE Statement 3-27MERGE Statement Syntax 3-28Merging Rows 3-29Unauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates.Tracking Changes in Data 3-31Example of the Flashback Version Query 3-32VERSIONS BETWEEN Clause 3-34Summary 3-35Practice 3: Overview 3-364 Generating Reports by Grouping Related DataObjectives 4-2 aReview of Group Functions 4-3 ) hasReview of the GROUP BY Clause 4-4 c om Review of the HAVING Clause 4-5 ail uide GROUP BY with ROLLUP and CUBE Operators 4-6gm t G @ n ROLLUP Operator 4-7a rale tude ROLLUP Operator: Example 4-8 r hlk his S CUBE Operator 4-9O ( se tA u CUBE Operator: ExampleKRNI se to 4-10A GROUPING Function 4-11 n L M Example 4-12U le e GROUPING Function: lic HRA ferab GROUPING SETS 4-13E nsAL GROUPING SETS: Example 4-15ra R Composite Columns 4-17 KA non-t Composite Columns: Example 4-19Concatenated Groupings 4-21Concatenated Groupings: Example 4-22Summary 4-23Practice 4: Overview 4-245 Managing Data in Different Time ZonesObjectives 5-2Time Zones 5-3TIME_ZONE Session Parameter 5-4CURRENT_DATE, CURRENT_TIMESTAMP, and LOCALTIMESTAMP 5-5CURRENT_DATE 5-6CURRENT_TIMESTAMP 5-7LOCALTIMESTAMP 5-8v 6. SQL Star International LimitedDBTIMEZONE and SESSIONTIMEZONE 5-9TIMESTAMP Data Type 5-10TIMESTAMP Data Types 5-11TIMESTAMP Fields 5-12Unauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates.Difference Between DATE and TIMESTAMP 5-13TIMESTAMP WITH TIME ZONE Data Type 5-14TIMESTAMP WITH TIMEZONE: Example 5-15TIMESTAMP WITH LOCAL TIMEZONE 5-16TIMESTAMP WITH LOCAL TIMEZONE: Example 5-17INTERVAL Data Types 5-18INTERVAL Fields 5-20ahasINTERVAL YEAR TO MONTH Data Type 5-21 INTERVAL YEAR TO MONTH: Example 5-22 )c om ail uide INTERVAL DAY TO SECOND Data Type 5-23 INTERVAL DAY TO SECOND Data Type: Example 5-24 gm t G @ n rale tude EXTRACT 5-25 TZ_OFFSET 5-26ar hlk his SO ( se t TO_TIMESTAMP_TZ 5-29 TIMESTAMP Conversion Using FROM_TZ 5-28A KR to u 5-30 Converting to TIMESTAMP Using TO_TIMESTAMP andI eAN n5-31 Time Interval Conversion with TO_YMINTERVALsL M lice Using TO_DSINTERVAL: ExampleU AH rable Daylight Saving Time 5-32 SummaryRA LE 5:ansfe 5-355-34AR on-tr Practice Overview K n6 Retrieving Data Using SubqueriesObjectives 6-2Multiple-Column Subqueries 6-3Column Comparisons 6-4Pairwise Comparison Subquery 6-5Nonpairwise Comparison Subquery 6-6Scalar Subquery Expressions 6-7Scalar Subqueries: Examples 6-8Correlated Subqueries 6-10Using Correlated Subqueries 6-12Using the EXISTS Operator 6-14Find Employees Who Have At Least One Person Reporting to Them 6-15Find All Departments That Do Not Have Any Employees 6-16Correlated UPDATE 6-17 vi 7. SQL Star International LimitedUsing Correlated UPDATE 6-18Correlated DELETE 6-20Using Correlated DELETE 6-21WITH Clause 6-22Unauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates.WITH Clause: Example 6-23Summary 6-25Practice 6: Overview 6-277 Hierarchical RetrievalObjectives 7-2Sample Data from the EMPLOYEES Table 7-3Natural Tree Structure 7-4 aHierarchical Queries 7-5 ) hasWalking the Tree 7-6 c om Walking the Tree: From the Bottom Up 7-8 ail uideWalking the Tree: From the Top Down 7-9@ ngm t G rale tudeRanking Rows with the LEVEL Pseudocolumn 7-10 ahlk his S Formatting Hierarchical Reports Using LEVEL and LPAD 7-11r Pruning Branches 7-13AO ( se t Summary 7-14 I KR to u Practice 7: Overview NA 7-15nse UL M lice AH rable 8 Regular Expression Support R LE ansfe 8-2 ObjectivesA Regular Expression: Overview 8-3AR on-tr Characters 8-4 K n MetaUsing Meta Characters 8-5Regular Expression Functions 8-7REGEXP Function Syntax 8-8Performing Basic Searches 8-9Checking the Presence of a Pattern 8-10Example of Extracting Substrings 8-11Replacing Patterns 8-12Regular Expressions and Check Constraints 8-13Summary 8-14Practice 8: Overview 8-15Appendix A: Practice SolutionsAppendix B: Table Descriptions and Data vii 8. SQL Star International LimitedAppendix C: Writing Advanced ScriptsObjectives C-2Using SQL to Generate SQL C-3Creating a Basic Script C-4Unauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates.Controlling the Environment C-5The Complete Picture C-6Dumping the Contents of a Table to a File C-7Generating a Dynamic Predicate C-9Summary C-11Appendix D: Oracle Architectural ComponentsObjectives D-2aOracle Database Architecture: Overview D-3Database Physical Architecture D-4) hasc om Control Files D-5ail uideRedo Log Files D-6 gm t G @ n rale tudeTablespaces and Data Files D-7 aSegments, Extents, and Blocks D-8r hlk his S O ( se tOracle Instance Management D-9 AOracle Memory Structures D-10 I KR to uAN nseOracle Processes D-12 L M liceOther Key Physical Structures D-13 U AH rableProcessing a SQL Statement D-14 RConnecting to an Instance D-15A LE ansfeProcessing a Query D-17AR on-tr K nShared Pool D-18Database Buffer Cache D-20Program Global Area (PGA) D-21Processing a DML Statement D-22Redo Log Buffer D-24Rollback Segment D-25COMMIT Processing D-26Summary D-28Appendix E: Using SQL DeveloperObjectives E-2What Is Oracle SQL Developer? E-3Key Features E-4Installing SQL Developer E-5Menus for SQL Developer E-6Creating a Database Connection E-7 viii 9. SQL Star International LimitedBrowsing Database Objects E-9Creating a Schema Object E-10Creating a New Table: Example E-11Using SQL Worksheet E-12Unauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates.Executing SQL Statements E-14Viewing the Execution Plan E-15Formatting the SQL Code E-16Using Snippets E-17Using Snippets: Example E-18Using SQL*Plus E-19Database Reporting E-20Creating a User Defined Report E-21aSummary E-22) hasc om Indexail uide gm t G @ n rale tude Additional Practices ar hlk his S O ( se t Additional Practice Solutions A I KR to uAN nse UL M liceR AH rableA LE ansfeAR on-tr K nix 10. Unauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates.SQL Star International Limiteda) hasc om ail uide gm t G @ n a rale tuder hlk his S A O ( se t I KR to uAN nse U L M lice R AH rableA LE ansfeAR on-tr K nx 11. SQL Star International Limited PrefaceUnauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates. a) hasc om ail uide gm t G @ n a rale tuder hlk his S A O ( se t I KR to uAN nse U L M lice R AH rableA LE ansfeAR on-tr K n 12. Unauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates.SQL Star International Limiteda) hasc om ail uide gm t G @ n a rale tuder hlk his S A O ( se t I KR to uAN nse U L M lice R AH rableA LE ansfeAR on-tr K n 13. SQL Star International LimitedProfile Before You Begin This Course Before you begin this course, you should have working experience with SQL. PrerequisitesOracle Database 10g: SQL Fundamentals IUnauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates. How This Course Is Organized Oracle Database 10g: SQL Fundamentals II is an instructor-led course featuring lectures and hands-on exercises. Online demonstrations and written practice sessions reinforce the concepts and skills that are introduced.a) hasc om ail uide gm t G @ n a rale tuder hlk his S A O ( se t I KR to uAN nse U L M lice R AH rableA LE ansfeAR on-tr K nPreface - 3 14. SQL Star International Limited Related PublicationsOracle PublicationsTitle Part NumberOracle Database Reference 10g Release 2 (10.2)B14237-02Oracle Database SQL Reference 10g Release 2 (10.2)B14200-02Unauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates.Oracle Database Concepts 10g Release 2 (10.2) B14220-02Oracle Database Application Developers Guide -Fundamentals 10g Release 2 (10.2)B14251-01SQL*Plus Users Guide and Reference B14357-01 Additional Publications System release bulletinsa Installation and users guides ) hasc om ail uide read.me files International Oracle Users Group (IOUG) articles gm t G @ n Oracle Magazinearale tuder hlk his SA O ( se t I KR to uAN nse UL M liceRAH rableA LE ansfeAR on-tr K nPreface - 4 15. SQL Star International LimitedTypographic ConventionsThe following two lists explain Oracle University typographical conventions forwords that appear within regular text or within code samples.1. Typographic Conventions for Words Within Regular TextUnauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates.Convention Object or TermExampleCourier NewUser input; Use the SELECT command to view commands; information stored in the LAST_NAME column, table, andcolumn of the EMPLOYEES table. schema names; functions;Enter 300. PL/SQL objects; paths Log in as scotta) hasAssign a When-Validate-Itemc om to ail uide Initial capTriggers;triggeruser interface object the ORD block.names, such as @ n gm t Gbutton namesa rale tudClick the Cancel button.er hlk his S O ( se t A For Italic Titles ofcoursesNIKR to umore information on the subject seee Oracle SQL ReferenceMA icens Manual andULemphasizedmanuals; A H ble l L aE R nsfera or phrases; Do not save changes to the database.words RA -trplaceholders or KA non variables Enter hostname, wherehostname is the host on which the password is to be changed.Quotation marksLesson or moduleThis subject is covered in Lesson 3, titles referenced Working with Objects. within a coursePreface - 5 16. SQL Star International Limited Typographic Conventions (continued)2. Typographic Conventions for Words Within Code SamplesConvention Object or Term ExampleUppercaseCommands,SELECT employee_idUnauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates. functionsFROM employees;Lowercase, Syntax variables CREATE ROLE role;italicInitial capForms triggers Form module: ORDTrigger level: S_ITEM.QUANTITYitemTrigger name: When-Validate-Item a. . .h as Lowercase Column names,. . . o m)OG_ACTIVATE_LAYER ilc table names,a uide filenames,gm t G(OG_GET_LAYER (prod_pie_layer)) @ nrale tude PL/SQL objects . . .SELECT arhlk employees; S last_name(FROM t his Text that must RAO use USER scottNIK se to Bold CREATE MA icen be entered by aIDENTIFIED BY tiger;L user A HU ble lL E R nsfera RA -tra KA nonPreface - 6 17. Unauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates. SQL Star International LimitedIntroductiona) hasc om ail uide@ n gm t G arale tude r hlk his SAO ( se tI KR to uAN nse L M Copyright 2009, Oracle. All rights reserved.U le liceH E RA ferab R AL trans KA non- 18. SQL Star International Limited Objectives After completing this lesson, you should be able to do theUnauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates. following: List the course objectives Describe the sample tables used in the coursea) hasc om ail uide@ n gm t G arale tude r hlk his SAO ( se tI KR to uAN nse L M Copyright 2009, Oracle. All rights reserved.U le liceH E RA ferab R AL trans KA non-Oracle Database 10g: SQL Fundamentals II I - 2 19. SQL Star International Limited Course Objectives After completing this course, you should be able to do theUnauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates. following: Use advanced SQL data retrieval techniques to retrievedata from database tables Apply advanced techniques in a practice that simulatesreal lifea) hasc om ail uide@ n gm t G arale tude r hlk his SAO ( se tI KR to uAN nse L M Copyright 2009, Oracle. All rights reserved.U le liceH E RA ferab R AL trans KA non-Oracle Database 10g: SQL Fundamentals II I - 3 20. SQL Star International Limited Course Overview In this course, you use advanced SQL data retrieval techniquesUnauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates. such as: Datetime functions ROLLUP, CUBE operators, and GROUPING SETSHierarchical queriesCorrelated subqueriesMultitable inserts aMerge operation) hasc om External tables ail uide@ n gm t G Regular expression usage arale tude r hlk his SAO ( se tI KR to u AN nse L M Copyright 2009, Oracle. All rights reserved.U le liceH E RA ferab R AL trans KA non- Oracle Database 10g: SQL Fundamentals II I - 4 21. SQL Star International Limited Course ApplicationUnauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates.EMPLOYEES DEPARTMENTS LOCATIONS a) hasc om ail uide @ engm t G rale COUNTRIESdREGIONS lka is Stu O (rh thRA to use ANIK se L M Copyright n2009, Oracle. All rights reserved. U le lice H RA ferab Tables UsedE the Course L in ans RA -tables are used in this course:TheA no n r K following t EMPLOYEES: The EMPLOYEES table contains information about all the employees such astheir first and last names, job IDs, salaries, hire dates, department IDs, and manager IDs. Thistable is a child of the DEPARTMENTS table. DEPARTMENTS: The DEPARTMENTS table contains information such as the department ID,department name, manager ID, and location ID. This table is the primary key table to theEMPLOYEES table. LOCATIONS: This table contains department location information. It contains location ID,street address, city, state province, postal code, and country ID information. It is the primary keytable to the DEPARTMENTS table and is a child of the COUNTRIES table. COUNTRIES: This table contains the country names, country IDs, and region IDs. It is a childof the REGIONS table. This table is the primary key table to the LOCATIONS table. REGIONS: This table contains region IDs and region names of the various countries. It is aprimary key table to the COUNTRIES table.Oracle Database 10g: SQL Fundamentals II I - 5 22. SQL Star International LimitedSummary In this lesson, you should have learned the following:Unauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates. The course objectives The sample tables used in the coursea) hasc om ail uide@ n gm t G arale tude r hlk his SAO ( se tI KR to uAN nse L M Copyright 2009, Oracle. All rights reserved.U le liceH E RA ferab R AL trans KA non-Oracle Database 10g: SQL Fundamentals II I - 6 23. Unauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates. SQL Star International Limited Controlling User Accessa) hasc om ail uide@ n gm t G arale tude r hlk his SAO ( se tI KR to uAN nse L M Copyright 2009, Oracle. All rights reserved.U le liceH E RA ferab R AL trans KA non- 24. SQL Star International Limited ObjectivesAfter completing this lesson, you should be able to do theUnauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates.following: Differentiate system privileges from object privileges Grant privileges on tables View privileges in the data dictionary Grant roles Distinguish between privileges and roles a h aso m)a ilc ide@ n gm t Gu arale tude r hlk his SAO ( se tI KR to uAN nse L M Copyright 2009, Oracle. All rights reserved.U le lice HRA ferab Objectives LEsranRA -you learn how to control database access to specific objects and add new users withIn this lesson, t KA nondifferent levels of access privileges.Oracle Database 10g: SQL Fundamentals II 1 - 2 25. SQL Star International LimitedControlling User AccessUnauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates.Databaseadministrator Username and password Privilegesah as Users o m) a ilc ide @ n gm t Guarale tuder hlk his S AO ( se tI KR to uAN nseL M Copyright 2009, Oracle. All rights reserved.U le lice H ERA ferabAL trans Controlling User AccessR -In aA K multiple-user environment, you want to maintain security of the database access and use. With nonOracle server database security, you can do the following: Control database access. Give access to specific objects in the database. Confirm given and received privileges with the Oracle data dictionary. Create synonyms for database objects.Database security can be classified into two categories: system security and data security. Systemsecurity covers access and use of the database at the system level such as the username and password,the disk space allocated to users, and the system operations that users can perform. Database securitycovers access and use of the database objects and the actions that those users can have on the objects. Oracle Database 10g: SQL Fundamentals II 1 - 3 26. SQL Star International Limited PrivilegesDatabase security:Unauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates. System security Data securitySystem privileges: Gaining access to the databaseObject privileges: Manipulating the content of the database objectsSchemas: Collection of objects such as tables, views, and a sequences) hasoma ilc ide@ n gm t Gu arale tude r hlk his SA O ( se t I KR to uAN nse L M Copyright 2009, Oracle. All rights reserved.U le liceHRA ferab Privileges LEsRAare -tran to execute particular SQL statements. The database administrator (DBA) is a KA noPrivileges n the righthigh-level user with the ability to create users and grant users access to the database and its objects.Users require system privileges to gain access to the database and object privileges to manipulate thecontent of the objects in the database. Users can also be given the privilege to grant additionalprivileges to other users or to roles, which are named groups of related privileges.SchemasA schema is a collection of objects such as tables, views, and sequences. The schema is owned by adatabase user and has the same name as that user.For more information, see the Oracle Database10g Application Developers GuideFundamentalsreference manual. Oracle Database 10g: SQL Fundamentals II 1 - 4 27. SQL Star International Limited System PrivilegesMore than 100 privileges are available.Unauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates.The database administrator has high-level system privileges for tasks such as: Creating new users Removing users Removing tables Backing up tablesah as o m) a ilc ide @ n gm t Guarale tuder hlk his S AO ( se t I KR to u AN nseL M Copyright 2009, Oracle. All rights reserved. U le liceH E RA ferab AL tra System Privilegesns R KA non-More than 100 distinct system privileges are available for users and roles. System privileges typicallyare provided by the database administrator.Typical DBA PrivilegesSystem PrivilegeOperations AuthorizedCREATE USER Grantee can create other Oracle users.DROP USER Grantee can drop another user.DROP ANY TABLEGrantee can drop a table in any schema.BACKUP ANY TABLEGrantee can back up any table in any schema with the exportutility.SELECT ANY TABLEGrantee can query tables, views, or materialized views in anyschema.CREATE ANY TABLEGrantee can create tables in any schema.Oracle Database 10g: SQL Fundamentals II 1 - 5 28. SQL Star International Limited Creating UsersThe DBA creates users with the CREATE USER statement.Unauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates. CREATE USER user IDENTIFIED BYpassword; CREATE USER USER1 IDENTIFIED BY USER1;a CREATE USER succeeded. h aso m)a ilc ide@ n gm t Gu arale tude r hlk his SAO ( se tI KR to uAN nse L M Copyright 2009, Oracle. All rights reserved.U le lice HRA ferab Creating ALEa User s R createsan by executing the CREATE USER statement. The user does not have anyr a user K DBA on-tTheA nprivileges at this point. The DBA can then grant privileges to that user. These privileges determinewhat the user can do at the database level.The slide gives the abridged syntax for creating a user.In the syntax:userIs the name of the user to be createdPasswordSpecifies that the user must log in with this passwordFor more information, see Oracle Database10g SQL Reference. Oracle Database 10g: SQL Fundamentals II 1 - 6 29. SQL Star International Limited User System Privileges After a user is created, the DBA can grant specific systemUnauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates.privileges to that user. GRANT privilege [, privilege...] TO user [, user| role, PUBLIC...]; An application developer, for example, may have thefollowing system privileges: CREATE SESSIONa CREATE TABLE) has c om CREATE SEQUENCE ail uide CREATE VIEW @ n gm t G CREATE PROCEDURE arale tuder hlk his S AO ( se t I KR to u AN nseL M Copyright 2009, Oracle. All rights reserved.U le liceH RA ferab Typical UserE L Privilegess ranRA -tcreates a user, the DBA can assign privileges to that user. KA nonAfter the DBASystem Privilege Operations AuthorizedCREATE SESSION Connect to the database.CREATE TABLE Create tables in the users schema.CREATE SEQUENCECreate a sequence in the users schema.CREATE VIEWCreate a view in the users schema.CREATE PROCEDURE Create a stored procedure, function, or package in the users schema.In the syntax:privilege Is the system privilege to be granteduser |role|PUBLIC Is the name of the user, the name of the role, or PUBLIC designates that every user is granted the privilegeNote: Current system privileges can be found in the SESSION_PRIVS dictionary view. Oracle Database 10g: SQL Fundamentals II 1 - 7 30. SQL Star International LimitedGranting System PrivilegesThe DBA can grant specific system privileges to a user.Unauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates. GRANTcreate session, create table,create sequence, create view TO scott; GRANT CREATE succeeded.ah as o m) a ilc ide @ n gm t Guarale tuder hlk his SA O ( se t I KR to uAN nseL M Copyright 2009, Oracle. All rights reserved.U le liceH RA ferab GrantingALE PrivilegesSystem nsTheA R uses-traGRANT statement to allocate system privileges to the user. After the user has been K DBA on the ngranted the privileges, the user can immediately use those privileges.In the example in the slide, user Scott has been assigned the privileges to create sessions, tables,sequences, and views.Oracle Database 10g: SQL Fundamentals II 1 - 8 31. SQL Star International Limited What Is a Role?Unauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates. Users Manager ah as o m) Privilegesa ilc ide@ n gm t GuAllocating privileges arale tude privilegesAllocatingwithout a roler hlk his S with a roleAO ( se tI KR to uAN nse L M Copyright 2009, Oracle. All rights reserved. U le lice HE RA ferab AL tra What Is a Role? nsR KA non-A role is a named group of related privileges that can be granted to the user. This method makes iteasier to revoke and maintain privileges.A user can have access to several roles, and several users can be assigned the same role. Roles aretypically created for a database application.Creating and Assigning a RoleFirst, the DBA must create the role. Then the DBA can assign privileges to the role and assign therole to users.SyntaxCREATEROLE role;In the syntax:roleIs the name of the role to be createdAfter the role is created, the DBA can use the GRANT statement to assign the role to users as well asassign privileges to the role.Oracle Database 10g: SQL Fundamentals II 1 - 9 32. SQL Star International Limited Creating and Granting Privileges to a Role Create a role:Unauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates. CREATE ROLE manager; CREATE ROLE succeeded. Grant privileges to a role: GRANT create table, create view TO manager;a GRANT succeeded. h as Grant a role to users:o m)a ilc ideGRANT manager TO BELL, KOCHHAR;@ n gm t GuGRANT succeeded. arale tude r hlk his SAO ( se tI KR to uAN nse L M Copyright 2009, Oracle. All rights reserved. U le liceHRA ferab Creating ALEa Role sTheA R intran creates a manager role and then enables managers to create tables and K example - the slide nonviews. It then grants Bell and Kochhar the role of managers. Now Bell and Kochhar can create tablesand views.If users have multiple roles granted to them, they receive all the privileges associated with all theroles.Oracle Database 10g: SQL Fundamentals II 1 - 10 33. SQL Star International LimitedChanging Your Password The DBA creates your user account and initializes yourUnauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates.password. You can change your password by using the ALTER USERstatement. ALTER USER HR IDENTIFIED BY employ;ahas ALTER USER HR succeeded.)c om ail uide@ n gm t G arale tude r hlk his S AO ( se t I KR to uAN nse L M Copyright 2009, Oracle. All rights reserved.U le liceHERA ferabAL trans Changing Your Password R createsTheA K DBA on- an account and initializes a password for every user. You can change yournpassword by using the ALTER USER statement.SyntaxALTER USER user IDENTIFIED BY password;In the syntax:user Is the name of the userpassword Specifies the new passwordAlthough this statement can be used to change your password, there are many other options. Youmust have the ALTER USER privilege to change any other option.For more information, see the Oracle Database10g SQL Reference manual.Note: SQL*Plus has a PASSWORD command (PASSW) that can be used to change the password of auser when the user is logged in. This command is not available in SQL Developer.Oracle Database 10g: SQL Fundamentals II 1 - 11 34. SQL Star International LimitedObject PrivilegesUnauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates. Object Privilege TableViewSequenceProcedure ALTER DELETE EXECUTE a INDEX h as o m)INSERT a ilc ideREFERENCES @ n gm t GuSELECT lka S rale tude(rh thisUPDATE AO se RuA NIK se to L M Copyright n2009, Oracle. All rights reserved.U le liceHE RA ferab AL tra Object Privileges ns R privilegeAn A K object on- is a privilege or right to perform a particular action on a specific table, view, nsequence, or procedure. Each object has a particular set of grantable privileges. The table in the slidelists the privileges for various objects. Note that the only privileges that apply to a sequence areSELECT and ALTER. UPDATE, REFERENCES, and INSERT can be restricted by specifying asubset of updatable columns. A SELECT privilege can be restricted by creating a view with a subsetof columns and granting the SELECT privilege only on the view. A privilege granted on a synonymis converted to a privilege on the base table referenced by the synonym. Oracle Database 10g: SQL Fundamentals II 1 - 12 35. SQL Star International Limited Object PrivilegesObject privileges vary from object to object.Unauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates.An owner has all the privileges on the object.An owner can give specific privileges on that owners object.GRANTobject_priv [(columns)] aON objecth asTO {user|role|PUBLIC} o m)[WITH GRANT OPTION]; a ilc ide @ n gm t Guarale tuder hlk his SAO ( se tI KR to uAN nseL M Copyright 2009, Oracle. All rights reserved.U le lice H RA ferab GrantingALE Privileges Object ns aR objecttrprivileges are available for different types of schema objects. A user automatically KA noDifferent n-has all object privileges for schema objects contained in the users schema. A user can grant anyobject privilege on any schema object that the user owns to any other user or role. If the grantincludes WITH GRANT OPTION, then the grantee can further grant the object privilege to otherusers; otherwise, the grantee can use the privilege but cannot grant it to other users.In the syntax:object_priv Is an object privilege to be grantedALL Specifies all object privilegescolumns Specifies the column from a table or view on which privileges are grantedON object Is the object on which the privileges are grantedTOIdentifies to whom the privilege is grantedPUBLICGrants object privileges to all usersWITH GRANT OPTION Enables the grantee to grant the object privileges to otherusers and roles Oracle Database 10g: SQL Fundamentals II 1 - 13 36. SQL Star International LimitedGranting Object Privileges Grant query privileges on the EMPLOYEES table:Unauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates. GRANT select ON employees TO sue, rich; GRANT succeeded. Grant privileges to update specific columns to users androles: sa)haGRANT update (department_name, location_id)moONdepartments a ilc ideTOscott, manager; @ n gm t GuGRANT succeeded. arale tude r hlk his SAO ( se tI KR to u AN nse L M Copyright 2009, Oracle. All rights reserved.U le liceHRA ferab GuidelinesLE A trans Rgrant privileges on an object, the object must be in your own schema, or you must have been KA non- object privileges WITH GRANT OPTION. Togranted the An object owner can grant any object privilege on the object to any other user or role of the database. The owner of an object automatically acquires all object privileges on that object.The first example in the slide grants users Sue and Rich the privilege to query your EMPLOYEEStable. The second example grants UPDATE privileges on specific columns in the DEPARTMENTStable to Scott and to the manager role.If Sue or Rich now want to use a SELECT statement to obtain data from the EMPLOYEES table, thesyntax they must use is:SELECT* FROM HR.employees;Alternatively, they can create a synonym for the table and issue a SELECT statement from thesynonym:CREATE SYNONYM emp FOR HR.employees;SELECT * FROM emp;Note: DBAs generally allocate system privileges; any user who owns an object can grant objectprivileges.Oracle Database 10g: SQL Fundamentals II 1 - 14 37. SQL Star International LimitedPassing On Your Privileges Give a user authority to pass along privileges:Unauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates. GRANT select, insert ON departments TO scott WITH GRANT OPTION; GRANT succeeded. Allow all users on the system to query data from AlicesaDEPARTMENTS table: ) hasom GRANT select a ilc ide ONalice.departments@ n gm t Gu TOPUBLIC; arale tude GRANT succeeded.r hlk his SAO ( se tI KR to uAN nse L M Copyright 2009, Oracle. All rights reserved. U le liceH E RA ferab AL trans Passing On Your PrivilegesWITHR n- OPTION Keyword KA GRANTnoA privilege that is granted with the WITH GRANT OPTION clause can be passed on to other usersand roles by the grantee. Object privileges granted with the WITH GRANT OPTION clause arerevoked when the grantors privilege is revoked.The example in the slide gives user Scott access to your DEPARTMENTS table with the privileges toquery the table and add rows to the table. The example also shows that Scott can give others theseprivileges.PUBLIC KeywordAn owner of a table can grant access to all users by using the PUBLIC keyword.The second example allows all users on the system to query data from Alices DEPARTMENTS table.Oracle Database 10g: SQL Fundamentals II 1 - 15 38. SQL Star International Limited Confirming Privileges Granted Data Dictionary ViewDescriptionUnauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates. ROLE_SYS_PRIVSSystem privileges granted to roles ROLE_TAB_PRIVSTable privileges granted to roles USER_ROLE_PRIVS Roles accessible by the user USER_TAB_PRIVS_MADE Object privileges granted on the users objects Object privileges granted to the user aas USER_TAB_PRIVS_RECDUSER_COL_PRIVS_MADE Object privileges granted on the columns om )hof thec users objects ail uide@ n gm t Grale tudeUSER_COL_PRIVS_RECD Object privileges granted to the user on specific columns a r hlk his S SystemO ( A use tprivileges granted to the userUSER_SYS_PRIVSRA NIK se toL M Copyright n2009, Oracle. All rights reserved.U le liceH E RA ferab AL tran Privileges Confirming GrantedsR KA notohave the DELETE privilege, the Oracle server does not permit the operation to take place.If you attempt-to perform an unauthorized operation, such as deleting a row from a table for whichyou do nnIf you receive the Oracle server error message Table or view does not exist, then you have doneeither of the following: 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 appropriate privilegeYou can access the data dictionary to view the privileges that you have. The chart in the slidedescribes various data dictionary views.Oracle Database 10g: SQL Fundamentals II 1 - 16 39. SQL Star International LimitedRevoking Object Privileges You use the REVOKE statement to revoke privilegesUnauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates.granted to other users. Privileges granted to others through the WITH GRANTOPTION clause are also revoked. REVOKE {privilege [, privilege...]|ALL} ONobjecta FROM {user[, user...]|role|PUBLIC} h as [CASCADE CONSTRAINTS];o m) a ilc ide @ n gm t Guarale tuder hlk his SA O ( se tI KR to uAN nseL M Copyright 2009, Oracle. All rights reserved.U le lice H ERA ferab AL trans Revoking Object Privileges R KA non-You can remove privileges granted to other users by using the REVOKE statement. When you use theREVOKE statement, the privileges that you specify are revoked from the users you name and fromany other users to whom those privileges were granted by the revoked user.In the syntax:CASCADE is required to remove any referential integrity constraints made to the CONSTRAINTSobject by means of the REFERENCES privilegeFor more information, see Oracle Database10g SQL Reference.Note: If a user were to leave the company and you revoke his privileges, you must regrant anyprivileges that this user may have granted to other users. If you drop the user account withoutrevoking privileges from it, then the system privileges granted by this user to other users are notaffected by this action. Oracle Database 10g: SQL Fundamentals II 1 - 17 40. SQL Star International LimitedRevoking Object PrivilegesAs user Alice, revoke the SELECT and INSERT privileges givenUnauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates.to user Scott on the DEPARTMENTS table. REVOKE select, insert ONdepartments FROMscott; REVOKE succeeded. a ) has c om ail uide @ n gm t Garale tuder hlk his S AO ( se t I KR to u AN nseL M Copyright 2009, Oracle. All rights reserved.U le lice HERA ferabAL trans Revoking Object Privileges (continued)TheAR nin the slide revokes SELECT and INSERT privileges given to user Scott on the K example -noDEPARTMENTS table.Note: If a user is granted a privilege with the WITH GRANT OPTION clause, that user can also grantthe privilege with the WITH GRANT OPTION clause, so that a long chain of grantees is possible, butno circular grants (granting to a grant ancestor) are permitted. If the owner revokes a privilege from auser who granted the privilege to other users, then the revoking cascades to all the privileges granted.For example, if user A grants a SELECT privilege on a table to user B including the WITH GRANTOPTION clause, user B can grant to user C the SELECT privilege with the WITH GRANT OPTIONclause as well, and user C can then grant to user D the SELECT privilege. If user A revokes privilegesfrom user B, then the privileges granted to users C and D are also revoked. Oracle Database 10g: SQL Fundamentals II 1 - 18 41. SQL Star International LimitedSummary In this lesson, you should have learned about statements thatUnauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates. control access to the database and database objects. StatementAction CREATE USERCreates a user (usually performed by a DBA) GRANTGives other users privileges to access the objects a CREATE ROLEhCreates a collection of privileges (usually performed byasa DBA) o m) a ilc ide ALTER USER Changes a users password gm t Gu REVOKEan le@ from nRemoves privileges on raobject udeusersatr hlk his S AO ( se t I KR to uAN nseL M Copyright 2009, Oracle. All rights reserved. U le lice H RA ferab Summary LEsRA -tran database security for users by assigning privileges to the users. KA nonDBAs establish initial The DBA creates users who must have a password. The DBA is also responsible for establishingthe initial system privileges for a user. After the user has created an object, the user can pass along any of the available objectprivileges to other users or to all users by using the GRANT statement. A DBA can create roles by using the CREATE ROLE statement to pass along a collection ofsystem or object privileges to multiple users. Roles make granting and revoking privileges easierto maintain. Users can change their password by using the ALTER USER statement. You can remove privileges from users by using the REVOKE statement. With data dictionary views, users can view the privileges granted to them and those that aregranted on their objects. With database links, you can access data on remote databases. Privileges cannot be granted onremote objects.Oracle Database 10g: SQL Fundamentals II 1 - 19 42. SQL Star International LimitedPractice 1: OverviewThis practice covers the following topics:Unauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates. Granting other users privileges to your table Modifying another users table through the privileges granted to you Creating a synonym Querying the data dictionary views related to privilegesa h aso m)a ilc ide@ n gm t Gu arale tude r hlk his SAO ( se tI KR to uAN nse L M Copyright 2009, Oracle. All rights reserved.U le liceHRA ferab Practice ALE 1: OverviewsR -tranpractice controlling access to the database objects. You use two accounts: KA nonIn this exercise, youora21 and ora22. Oracle Database 10g: SQL Fundamentals II 1 - 20 43. SQL Star International Limited Practice 1To complete question 6 and the subsequent ones, you need to connect to the database using SQLDeveloper. To do so, double-click the SQL Developer icon on the desktop.To create a new database connection in the Connections Navigator, right-click Connections. SelectNew Connection from the shortcut menu. The New/Select Database Connection dialog box appears.Unauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates.Create a database connection using the following information:a. Connection Name: ora21b. Username: ora21c. Password: ora21d. Hostname: localhoste. Port: 1521f. SID: ORCLg. Ensure that you select the Save Password check box. aCreate another database connection using the following information:h asa. Connection Name: ora22o m)b. Username: ora22a ilc idec. Password: ora22 @ ngm t Gu rale tuded. Hostname: localhoste. Port: 1521ar hlk his S O ( box. tf. SID: ORCLg. Ensure that you select the Save Password check se ARuNIK se to 1. Which privilege should aMA be given to log on to the Oracle server? Is this a system or anobject privilege?HUL user licen leRA ferab _____________________________________________________________________E AL tran should a user be given to create tables? 2. Which privilege s R - KA youocreate a table, who can pass along privileges to other users on your table?_____________________________________________________________________ 3. If n n _____________________________________________________________________4. You are the DBA. You are creating many users who require the same system privileges. What should you use to make your job easier? _____________________________________________________________________5. Which command would you use to change your password? _____________________________________________________________________Oracle Database 10g: SQL Fundamentals II 1 - 21 44. SQL Star International Limited Practice 1 (continued)6. Connect as user ora21. Query all the rows in your DEPARTMENTS table.Unauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates. sa ) ha7. Add a new row to your DEPARTMENTS table. Add Education as department number 500.8. Grant user ora22 access to your DEPARTMENTS table. om 9. Connect as user ora22. Query user ora21s DEPARTMENTS table.ilc a de@ ngm t Guia rale tude r hlk his SA O ( se tI KR to u AN nseUL M liceR AH rable ALE ansfeAR on-tr K Create a synonym for user ora21s DEPARTMENTS table. Query all the rows in user ora21s 10. n DEPARTMENTS table by using your synonym. Oracle Database 10g: SQL Fundamentals II 1 - 22 45. SQL Star International Limited Practice 1 (continued)11. As user ora22, query the USER_TABLES data dictionary to see information about the tablesthat you own.Unauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates.12. As user ora22, query the ALL_TABLES data dictionary view to see information abouta the alltables that you can access. Exclude the tables that you own.hasNote: Your list may not exactly match the following list: co m)ail uide gm t G @ n a rale tude r hlk his S A O ( se tI KR to u AN nse L M lice HU ande user r a l 13. Connect asRA ora21b revoke the SELECT privilege from user ora22. A LE ansfeAR on the 14. Remove-tr row that you inserted into the DEPARTMENTS table in step 7 and save the changes. K nOracle Database 10g: SQL Fundamentals II 1 - 23 46. Unauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates.SQL Star International Limiteda) hasc om ail uide gm t G @ n a rale tuder hlk his S A O ( se t I KR to uAN nse U L M lice R AH rableA LE ansfeAR on-tr K n 47. Unauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates. SQL Star International Limited Managing Schema Objectsa) hasc om ail uide@ n gm t G arale tude r hlk his SAO ( se tI KR to uAN nse L M Copyright 2009, Oracle. All rights reserved.U le liceH E RA ferab R AL trans KA non- 48. SQL Star International Limited ObjectivesAfter completing this lesson, you should be able to do theUnauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates.following: Add constraints Create indexes Create indexes using the CREATE TABLE statement Creating function-based indexes Drop columns and set column UNUSEDa h as Perform FLASHBACK operationso m) Create and use external tables a ilc ide@ n gm t Gu arale tude r hlk his SAO ( se t I KR to u AN nse L M Copyright 2009, Oracle. All rights reserved.U le lice HRA ferab Objectives LEsranRA contains information about creating indexes and constraints, and altering existing objects.This lesson n-t KA noYou also learn about external tables, and the provision to name the index at the time of creating aprimary key constraint. Oracle Database 10g: SQL Fundamentals II 2 - 2 49. SQL Star International LimitedALTER TABLE StatementUse the ALTER TABLE statement to:Unauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates. Add a new column Modify an existing column Define a default value for the new column Drop a columna h aso m)a ilc ide@ n gm t Gu arale tude r hlk his SAO ( se t I KR to uAN nse L M Copyright 2009, Oracle. All rights reserved. U le liceH ERA ferabAL trans ALTER TABLE StatementR KA non-After you create a table, you may need to change the table structure because you omitted a column,your column definition needs to be changed, or you need to remove columns. You can do this byusing the ALTER TABLE statement. Oracle Database 10g: SQL Fundamentals II 2 - 3 50. SQL Star International Limited ALTER TABLE StatementUse the ALTER TABLE statement to add, modify, or dropUnauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates.columns: ALTER TABLE table ADD(column datatype [DEFAULT expr][, column datatype]...); ALTER TABLE table a MODIFY (column datatype [DEFAULT expr]h as[, column datatype]...); m) oa ilc ideALTER TABLE table @ n gm t GuDROP (column); arale tude r hlk his SAO ( se t I KR to u AN nse L M Copyright 2009, Oracle. All rights reserved.U le liceH E RA ferab AL trans ALTER TABLE Statement (continued) R KA non- statement.You can add columns to a table, modify columns, and drop columns from a table by using theALTER TABLEIn the syntax:table Is the name of the tableADD|MODIFY|DROP Is the type of modificationcolumnIs the name of the new columndatatypeIs the data type and length of the new columnDEFAULT exprSpecifies the default value for a new column Oracle Database 10g: SQL Fundamentals II 2 - 4 51. SQL Star International LimitedAdding a Column You use the ADD clause to add columns:Unauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates. ALTER TABLE dept80 ADD(job_id VARCHAR2(9)); ALTER TABLE succeeded. The new column becomes the last column:a) hasc om ail uide@ n gm t G arale tude r hlk his SAO ( se tI KR to u AN nse L M Copyright 2009, Oracle. All rights reserved.U le liceH RA ferab GuidelinesLE Adding a Column fors RA addanmodify columns. r or KA ncan -t You no You cannot specify where the column is to appear. The new column becomes the last column.The example in the slide adds a column named JOB_ID to the DEPT80 table. The JOB_ID columnbecomes the last column in the table.Note: If a table already contains rows when a column is added, then the new column is initially nullfor all the rows. You cannot add a mandatory NOT NULL column to a table that contains data in theother columns. You can only add a NOT NULL column to an empty table. Oracle Database 10g: SQL Fundamentals II 2 - 5 52. SQL Star International LimitedModifying a Column You can change a columns data type, size, and defaultUnauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates.value. ALTER TABLE dept80 MODIFY(last_name VARCHAR2(30)); ALTER TABLE succeeded. A change to the default value affects only subsequentinsertions to the table.a h aso m)a ilc ide@ n gm t Gu arale tude r hlk his S A O ( se t I KR to uAN nse L M Copyright 2009, Oracle. All rights reserved. U le lice H ERA ferab AL trans Modifying a Column R KA non-You can modify a column definition by using the ALTER TABLE statement with the MODIFY clause.Column modification can include changes to a columns data type, size, and default value.Guidelines You can increase the width or precision of a numeric column. You can increase the width of numeric or character columns. You can 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 You can change the data type if the column contains only null values. The exception to this isCHAR-to-VARCHAR2 conversions, which can be done with data in the columns. You can convert a CHAR column to the VARCHAR2 data type or convert a VARCHAR2 columnto the CHAR data type only if the column contains null values or if you do not change the size. A change to the default value of a column affects only subsequent insertions to the table. Oracle Database 10g: SQL Fundamentals II 2 - 6 53. SQL Star International Limited Dropping a ColumnUse the DROP COLUMN clause to drop columns you no longerUnauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates.need from the table: ALTER TABLE dept80 DROP COLUMN job_id; ALTER TABLE succeeded.a h aso m)a ilc ide@ n gm t Gu arale tude r hlk his SAO ( se t I KR to uAN nse L M Copyright 2009, Oracle. All rights reserved.U le lice H E RA ferab AL tran Dropping a Columns R KA non aYou can drop - column from a table by using the ALTER TABLE statement with the DROP COLUMNclause.Guidelines The column may or may not contain data. Using the ALTER TABLE statement, only one column can be dropped at a time. The table must have at least one column remaining in it after it is altered. After a column is dropped, it cannot be recovered. A column cannot be dropped if it is part of a constraint or part of an index key unless the cascade option is added. Dropping a column can take a while if the column has a large number of values. In this case, it may be better to set it to be unused and drop it when there are fewer users on the system to avoid extended locks.Note: Certain columns can never be dropped such as columns that form part of the partitioning keyof a partitioned table or columns that form part of the primary key of an index-organized table. Oracle Database 10g: SQL Fundamentals II 2 - 7 54. SQL Star International Limited SET UNUSED Option You use the SET UNUSED option to mark one or moreUnauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates.columns as unused. You use the DROP UNUSED COLUMNS option to remove thecolumns that are marked as unused. ALTER TABLE SET UNUSED(); a ORh as m) ALTERTABLE UNUSED COLUMN ; ailco degm t Gui SET@ nALTER TABLE arale tudeDROP UNUSED COLUMNS; rhlk S(his RAO use tANIK se toL M Copyright n2009, Oracle. All rights reserved.U le lice H RA ferab SET UNUSED EL Option snTheARA -traoption marks one or more columns as unused so that they can be dropped when K non SET UNUSEDthe demand on system resources is lower. Specifying this clause does not actually remove the targetcolumns from each row in the table (that is, it does not restore the disk space used by these columns).Therefore, the response time is faster than if you executed the DROP clause. Unused columns aretreated as if they were dropped, even though their column data remains in the tables rows. After acolumn has been marked as unused, you have no access to that column. A SELECT * query will notretrieve data from unused columns. In addition, the names and types of columns marked unused willnot be displayed during a DESCRIBE statement, and you can add to the table a new column with thesame name as an unused column. SET UNUSED information is stored in theUSER_UNUSED_COL_TABS dictionary view.Note: The guidelines for setting a column to be UNUSED are similar to those of dropping a column. Oracle Database 10g: SQL Fundamentals II 2 - 8 55. SQL Star International Limited DROP UNUSED COLUMNS OptionDROP UNUSED COLUMNS removes from the table all columns currently marked as unused. You canuse this statement when you want to reclaim the extra disk space from unused columns in the table. Ifthe table contains no unused columns, the statement returns with no errors.ALTER TABLE dept80SET UNUSED (last_name);Unauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates.ALTER TABLE succeeded.ALTER TABLE dept80DROP UNUSED COLUMNS;ALTER TABLE succeeded.a) hasc om ail uide gm t G @ n a rale tuder hlk his S A O ( se t I KR to uAN nse U L M lice R AH rableA LE ansfeAR on-tr K n Oracle Database 10g: SQL Fundamentals II 2 - 9 56. SQL Star International Limited Adding a Constraint SyntaxUse the ALTER TABLE statement to:Unauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates. Add or drop a constraint, but not modify its structure Enable or disable constraints Add a NOT NULL constraint by using the MODIFY clause ALTER TABLE ADD [CONSTRAINT ] a type (); h aso m)a ilc ide@ n gm t Gu arale tude r hlk his S A O ( se t I KR to u AN nse L M Copyright 2009, Oracle. All rights reserved.U le lice HRA ferab Adding aALE Constraintsran R add a-constraint for existing tables by using the ALTER TABLE statement with the ADDYou can n t KA noclause.In the syntax:table Is the name of the tableconstraintIs the name of the constrainttypeIs the constraint typecolumnIs the name of the column affected by the constraintThe constraint name syntax is optional, although recommended. If you do not name your constraints,the system generates constraint names.Guidelines 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 MODIFY clause of the ALTER TABLE statement.Note: You can define a NOT NULL column only if the table is empty or if the column has a value forevery row. Oracle Database 10g: SQL Fundamentals II 2 - 10 57. SQL Star International LimitedAdding a ConstraintAdd a FOREIGN KEY constraint to the EMP2 table indicating thatUnauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates.a manager must already exist as a valid employee in the EMP2table. ALTER TABLE emp2 modify employee_id Primary Key; ALTER TABLE succeeded.a h asm)ALTER TABLE emp2oilc ideADD CONSTRAINT emp_mgr_fkaFOREIGN KEY(manager_id)REFERENCES emp2(employee_id); @gm t GunALTER TABLE succeeded. arale tude r hlk his SAO ( se t I KR to uAN nse L M Copyright 2009, Oracle. All rights reserved. U le liceHRA ferab Adding aALEs Constraint (continued) R exampleanthe slide modifies the EMP2 table to add a PRIMARY KEY constraint on the r in K firstnon-t column. Note that because no constraint name is provided, the constraint isTheAEMPLOYEE_IDautomatically named by the Oracle server. The second example in the slide creates a FOREIGN KEYconstraint on the EMP2 table. The constraint ensures that a manager exists as a valid employee in theEMP2 table.Oracle Database 10g: SQL Fundamentals II 2 - 11 58. SQL Star International Limited ON DELETE CASCADEDelete child rows when a parent key is deleted:Unauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates. ALTER TABLE Emp2 ADD CONSTRAINT emp_dt_fk FOREIGN KEY (Department_id) REFERENCES departments ON DELETE CASCADE); ALTER TABLE succeeded. ah as o m) a ilc ide @ n gm t Guarale tuder hlk his S AO ( se t I KR to uAN nseL M Copyright 2009, Oracle. All rights reserved.U le liceHRA ferab ON DELETELEs RDELETE anA CASCADEr CASCADE action allows parent key data that is referenced from the child table to K ON non-tTheAbe deleted, but not updated. When data in the parent key is deleted, all rows in the child table thatdepend on the deleted parent key values are also deleted. To specify this referential action, includethe ON DELETE CASCADE option in the definition of the FOREIGN KEY constraint. Oracle Database 10g: SQL Fundamentals II 2 - 12 59. SQL Star International Limited Deferring Constraints Constraints can have the following attributes:Unauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates. DEFERRABLE or NOT DEFERRABLE INITIALLY DEFERRED or INITIALLY IMMEDIATE Deferring constraint onALTER TABLE dept2creationADD CONSTRAINT dept2_id_pkPRIMARY KEY (department_id)aDEFERRABLE INITIALLY DEFERRED h as om)SET CONSTRAINTS dept2_id_pk IMMEDIATE ma ilc ideChanging a specific ug constraint attribute@ n tGraleChanging e constraints for a dALTER SESSION Stu lka is session allSET CONSTRAINTS= IMMEDIATErO ( h th RA to use ANIK seL M Copyright n2009, Oracle. All rights reserved.U le liceHERA ferabAL trans Deferring ConstraintsR KA nonYou can defer-checking constraints for validity until the end of the transaction. A constraint isdeferred if the system checks that it is satisfied only on commit. If a deferred constraint is violated,then commit causes the transaction to roll back. If a constraint is immediate (not deferred), then it ischecked at the end of each statement. If it is violated, the statement is rolled back immediately. If aconstraint causes an action (for example, DELETE CASCADE), that action is always taken as part ofthe statement that caused it, whether the constraint is deferred or immediate. Use the SETCONSTRAINTS statement to specify, for a particular transaction, whether a deferrable constraint ischecked following each DML statement or when the transaction is committed. To create deferrableconstraints, you must create a nonunique index for that constraint.You can define constraints as either deferrable or not deferrable, and either initially deferred orinitially immediate. These attributes can be different for each constraint.Usage scenario: Company policy dictates that department number 40 should be changed to 45.Changing the DEPARTMENT_ID column affects employees assigned to this department. Therefore,you make the primary key and foreign keys deferrable and initially deferred. You update bothdepartment and employee information, and at the time of commit, all rows are validated.Oracle Database 10g: SQL Fundamentals II 2 - 13 60. SQL Star International LimitedDropping a Constraint Remove the manager constraint from the EMP2 table:Unauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates. ALTER TABLE emp2 DROP CONSTRAINT emp_mgr_fk; ALTER TABLE succeeded. Remove the PRIMARY KEY constraint on the DEPT2 tableand drop the associated FOREIGN KEY constraint on theEMP2.DEPARTMENT_ID column: sah a ALTER TABLE dept2 o m) DROP PRIMARY KEY CASCADE; a ilc ide ALTER TABLE succeeded.@ n gm t Guarale tuder hlk his SA O ( se tI KR to uAN nseL M Copyright 2009, Oracle. All rights reserved.U le liceHE RA ferabAL trans Dropping a Constraint R KA non-To drop a constraint, you can identify the constraint name from the USER_CONSTRAINTS andUSER_CONS_COLUMNS data dictionary views. Then use the ALTER TABLE statement with theDROP clause. The CASCADE option of the DROP clause causes any dependent constraints also to bedropped.Syntax ALTER TABLE tableDROP PRIMARY KEY | UNIQUE (column) |CONSTRAINTconstraint [CASCADE];In the syntax:table Is the name of the tablecolumnIs the name of the column affected by the constraintconstraintIs the name of the constraintWhen you drop an integrity constraint, that constraint is no longer enforced by the Oracle server andis no longer available in the data dictionary. Oracle Database 10g: SQL Fundamentals II 2 - 14 61. SQL Star International Limited Disabling Constraints Execute the DISABLE clause of the ALTER TABLEUnauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates. statement to deactivate an integrity constraint. Apply the CASCADE option to disable dependent integrity constraints. ALTER TABLE emp2 DISABLE CONSTRAINT emp_dt_fk; a ALTER TABLE succeeded.h as o m) a ilc ide @ n gm t Guarale tuder hlk his S AO ( se t I KR to uAN nseL M Copyright 2009, Oracle. All rights reserved. U le liceHERA ferab AL trans Disabling a Constraint R KA non-You can disable a constraint without dropping it or re-creating it by using the ALTER TABLEstatement with the DISABLE clause.SyntaxALTER TABLE tableDISABLE CONSTRAINT constraint [CASCADE];In the syntax:tableIs the name of the tableconstraint Is the name of the constraintGuidelines 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 or primary key constraint removes the unique index. Oracle Database 10g: SQL Fundamentals II 2 - 15 62. SQL Star International LimitedEnabling Constraints Activate an integrity constraint currently disabled in theUnauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates.table definition by using the ENABLE clause. ALTER TABLE emp2 ENABLE CONSTRAINT emp_dt_fk; ALTER TABLE succeeded. A UNIQUE index is automatically created if you enable a aUNIQUE key or a PRIMARY KEY constraint.has)c om ail uide@ n gm t G arale tude r hlk his SAO ( se t I KR to uAN nse L M Copyright 2009, Oracle. All rights reserved.U le lice HRA ferab EnablingALEs a Constraint R enabletran KA noYou can n- a constraint without dropping it or re-creating it by using the ALTER TABLEstatement with the ENABLE clause.Syntax ALTERTABLEtable ENABLE CONSTRAINT constraint;In the syntax:tableIs the name of the tableconstraint Is the name of the constraintGuidelines If you enable a constraint, that constraint applies to all the data in the table. All the data in the table must comply with the constraint. If you enable a UNIQUE key or a PRIMARY KEY constraint, a UNIQUE or PRIMARY KEY index is created automatically. If an index already exists, then it can be used by these keys. You can use the ENABLE clause in both the CREATE TABLE statement and the ALTER TABLE statement. Oracle Database 10g: SQL Fundamentals II 2 - 16 63. SQL Star International Limited Enabling a Constraint (continued)Guidelines (continued) Enabling a primary key constraint that was disabled with the CASCADE option does not enableany foreign keys that are dependent on the primary key. To enable a UNIQUE or PRIMARY KEY constraint, you must have the privileges necessary tocreate an index on the table.Unauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates.a) hasc om ail uide gm t G @ n a rale tuder hlk his S A O ( se t I KR to uAN nse U L M lice R AH rableA LE ansfeAR on-tr K nOracle Database 10g: SQL Fundamentals II 2 - 17 64. SQL Star International LimitedCascading ConstraintsThe CASCADE CONSTRAINTS clause is used along withUnauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates. the DROP COLUMN clause.The CASCADE CONSTRAINTS clause drops all referential integrity constraints that refer to the primary and unique keys defined on the dropped columns.The CASCADE CONSTRAINTS clause also drops all multicolumn constraints defined on the dropped columns.a h aso m)a ilc ide@ n gm t Gu arale tude r hlk his SAO ( se tI KR to uAN nse L M Copyright 2009, Oracle. All rights reserved. U le liceHRA ferab Cascading LEConstraintssRA -tran the usage of the CASCADE CONSTRAINTS clause. Assume that the KA nonThis statement illustratesTEST1 table is created as follows: CREATE TABLE test1 ( pk NUMBER PRIMARY KEY, fk NUMBER, col1 NUMBER, col2 NUMBER, CONSTRAINT fk_constraint FOREIGN KEY (fk) REFERENCES test1, CONSTRAINT ck1 CHECK (pk > 0 and col1 > 0), CONSTRAINT ck2 CHECK (col2 > 0));An error is returned for the following statements: ALTER TABLE test1 DROP (pk);pk is a parent key. ALTER TABLE test1 DROP (col1); col1 is referenced by the multicolumn constraint, ck1. Oracle Database 10g: SQL Fundamentals II 2 - 18 65. SQL Star International Limited Cascading ConstraintsExample:Unauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates. ALTER TABLE emp2 DROP COLUMN employee_id CASCADE CONSTRAINTS; ALTER TABLE succeeded. ALTER TABLE test1 DROP (pk, fk, col1);a ALTER TABLE succeeded. h aso m)a ilc ide@ n gm t Gu arale tude r hlk his SAO ( se t I KR to uAN nse L M Copyright 2009, Oracle. All rights reserved.U le liceHRA ferab Cascading LE sConstraints (continued)ranRA the tfollowing statement drops the EMPLOYEE_ID column, the primary key constraint, KA noSubmitting n-and any foreign key constraints referencing the primary key constraint for the EMP2 table:ALTER TABLE emp2 DROP COLUMN employee_id CASCADE CONSTRAINTS;If all columns referenced by the constraints defined on the dropped columns are also dropped, thenCASCADE CONSTRAINTS is not required. For example, assuming that no other referentialconstraints from other tables refer to the PK column, it is valid to submit the following statementwithout the CASCADE CONSTRAINTS clause for the TEST1 table created on the previous page:ALTER TABLE test1 DROP (pk, fk, col1);Oracle Database 10g: SQL Fundamentals II 2 - 19 66. SQL Star International Limited Overview of IndexesIndexes are created:Unauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates. Automatically PRIMARY KEY creation UNIQUE KEY creation Manually CREATE INDEX statement CREATE TABLE statement a h aso m)a ilc ide@ n gm t Gu arale tude r hlk his SAO ( se t I KR to u AN nse L M Copyright 2009, Oracle. All rights reserved. U le liceHRA ferab Overview of E L Indexessran RA of indexes can be created. One type is a unique index. The Oracle server automaticallyTwo types n-t KA nocreates a unique index when you define a column or group of columns in a table to have a PRIMARYKEY or a UNIQUE key constraint. The name of the index is the name given to the constraint.The other type of index is a nonunique index, which a user can create. For example, you can createan index for a FOREIGN KEY column to be used in joins to improve retrieval speed.You can create an index on one or more columns by issuing the CREATE INDEX statement.For more information, see Oracle Database 10g SQL Reference.Note: You can manually create a unique index, but it is recommended that you create a uniqueconstraint, which implicitly creates a unique index.Oracle Database 10g: SQL Fundamentals II 2 - 20 67. SQL Star International Limited CREATE INDEX with the CREATE TABLE StatementUnauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates. CREATE TABLE NEW_EMP (employee_id NUMBER(6)PRIMARY KEY USING INDEX (CREATE INDEX emp_id_idx ON NEW_EMP(employee_id)), first_name VARCHAR2(20), last_name VARCHAR2(25));a CREATE TABLE succeeded. h aso m)SELECT INDEX_NAME, TABLE_NAMEa ilc ideFROM USER_INDEXESgm t GuWHERE TABLE_NAME = NEW_EMP;le@ en ra d lka is StuO(rh thRA to useANIK se L M Copyright n2009, Oracle. All rights reserved.U le lice HERA ferab AL tran the CREATE INDEX with s CREATE TABLE StatementIn theR n- in the slide, the CREATE INDEX clause is used with the CREATE TABLE statement KA examplenoto create a primary key index explicitly. You can name your indexes at the time of primary keycreation to be different from the name of the PRIMARY KEY constraint. The following exampleillustrates the database behavior if the index is not explicitly named:CREATE TABLE EMP_UNNAMED_INDEX (employee_id NUMBER(6) PRIMARY KEY ,first_name VARCHAR2(20),last_name VARCHAR2(25));CREATE TABLE succeeded. SELECT INDEX_NAME, TABLE_NAME FROM USER_INDEXES WHERE TABLE_NAME = EMP_UNNAMED_INDEX;Oracle Database 10g: SQL Fundamentals II 2 - 21 68. SQL Star International Limited CREATE INDEX with the CREATE TABLE Statement (continued)Observe that the Oracle server gives a generic name to the index that is created for the PRIMARYKEY column.You can also use an existing index for your PRIMARY KEY columnfor example, when you areexpecting a large data load and want to speed up the operation. You may want to disable theUnauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates.constraints while performing the load and then enable them, in which case having a unique index onthe primary key will still cause the data to be verified during the load. So you can first create anonunique index on the column designated as PRIMARY KEY, and then create the PRIMARY KEYcolumn and specify that it should use the existing index. The following examples illustrate thisprocess:Step 1: Create the table:CREATE TABLE NEW_EMP2a (employee_id NUMBER(6) h asm) first_name VARCHAR2(20),oilc ide last_name VARCHAR2(25)a gm t Gu );@ nStep 2: Create the index:rale tudeka s SCREATE INDEX emp_id_idx2 ON rhl i(new_emp2(employee_id); O A s e thNKR to uI eStep 3: Create the Primary Key: A M icensLHU ble lALTER TABLE new_emp2 ADD PRIMARY KEY (employee_id) USING INDEXA E R nsfera emp_id_idx2; LRA -tra KA nonOracle Database 10g: SQL Fundamentals II 2 - 22 69. SQL Star International LimitedFunction-Based Indexes A function-based index is based on expressions.Unauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates. The index expression is built from table columns,constants, SQL functions, and user-defined functions. CREATE INDEX upper_dept_name_idx ON dept2(UPPER(department_name));a CREATE INDEX succeeded. h aso m)SELECT *a ilc ideFROM dept2@ n gm t GuWHERE UPPER(department_name) l= SALES; ara e tude r hlk his SAO ( se tI KR to u AN nse L M Copyright 2009, Oracle. All rights reserved.U le liceHERA ferabAL trans Function-Based Indexes R KA non-Function-based indexes defined with the UPPER(column_name) or LOWER(column_name)keywords allow non-case-sensitive searches. For example, the following index:CREATE INDEX upper_last_name_idx ON emp2 (UPPER(last_name));facilitates processing queries such as:SELECT * FROM emp2 WHERE UPPER(last_name) = KING;The Oracle server uses the index only when that particular function is used in a query. For example,the following statement may use the index, but without the WHERE clause, the Oracle server mayperform a full table scan:SELECT*FROMemployeesWHERE UPPER (last_name) IS NOT NULLORDER BY UPPER (last_name);Note: The QUERY_REWRITE_ENABLED initialization parameter must be set to TRUE for afunction-based index to be used.The Oracle server treats indexes with columns marked DESC as function-based indexes. Thecolumns marked DESC are sorted in descending order.Oracle Database 10g: SQL Fundamentals II 2 - 23 70. SQL Star International LimitedRemoving an Index Remove an index from the data dictionary by using theUnauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates.DROP INDEX command: DROP INDEX index; Remove the UPPER_DEPT_NAME_IDX index from the datadictionary: DROP INDEX upper_dept_name_idx; a DROP INDEX succeeded.h as o m) To drop an index, you must be the owner of ailc dethe index or have the DROP ANY INDEX privilege: gm t Gu i@ n arale tude r hlk his SAO ( se tI KR to u AN nse L M Copyright 2009, Oracle. All rights reserved.U le lice HRA ferab Removing LE an Index s RA modifyn aYou cannot n-tr indexes. To change an index, you must drop it and then re-create it. Remove an KA definition from the data dictionary by issuing the DROP INDEX statement. To drop an index,index noyou must be the owner of the index or have the DROP ANY INDEX privilege.In the syntax:index Is the name of the indexNote: If you drop a table, indexes and constraints are automatically dropped, but views andsequences remain.Oracle Database 10g: SQL Fundamentals II 2 - 24 71. SQL Star International Limited DROP TABLE PURGEUnauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates. DROP TABLE dept80 PURGE; ah as o m) a ilc ide @ n gm t Guarale tuder hlk his S AO ( se tI KR to uAN nseL M Copyright 2009, Oracle. All rights reserved. U le lice H RA ferab DROP TABLEE PURGEL ans RA -tr10g introduces a new feature for dropping tables. When you drop a table, the KA nonOracle Databasedatabase does not immediately release the space associated with the table. Rather, the databaserenames the table and places it in a recycle bin, where it can later be recovered with the FLASHBACKTABLE statement if you find that you dropped the table in error. If you want to immediately releasethe space associated with the table at the time you issue the DROP TABLE statement, then include thePURGE clause as shown in the statement in the slide.Specify PURGE only if you want to drop the table and release the space associated with it in a singlestep. If you specify PURGE, then the database does not place the table and its dependent objects intothe recycle bin.Using this clause is equivalent to first dropping the table and then purging it from the recycle bin.This clause saves you one step in the process. It also provides enhanced security if you want toprevent sensitive material from appearing in the recycle bin.Note: You cannot roll back a DROP TABLE statement with the PURGE clause, and you cannotrecover the table if you drop it with the PURGE clause. This feature was not available in earlierreleases.Oracle Database 10g: SQL Fundamentals II 2 - 25 72. SQL Star International Limited FLASHBACK TABLE Statement Repair tool for accidental table modificationsUnauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates. Restores a table to an earlier point in time Benefits: Ease of use, availability, fast execution Performed in place Syntax: FLASHBACK TABLE[schema.]table[,a [ schema.]table ]...) has TO { TIMESTAMP | SCN } exprc om [ { ENABLE | DISABLE } TRIGGERS ]; ail uide@ n gm t G arale tude r hlk his SAO ( se tI KR to u AN nse L M Copyright 2009, Oracle. All rights reserved.U le liceHERA ferabAL trans FLASHBACK TABLE StatementR KA non-Self-Service Repair FacilityOracle Database 10g provides a new SQL DDL command, FLASHBACK TABLE, to restore the stateof a table to an earlier point in time in case it is inadvertently deleted or modified. The FLASHBACKTABLE command is a self-service repair tool to restore data in a table along with associatedattributes such as indexes or views. This is done while the database is online by rolling back only thesubsequent changes to the given table. Compared to traditional recovery mechanisms, this featureoffers significant benefits such as ease of use, availability, and faster restoration. It also takes theburden off the DBA to find and restore application-specific properties. The flashback table featuredoes not address physical corruption caused because of a bad disk.SyntaxYou can invoke a FLASHBACK TABLE operation on one or more tables, even on tables in differentschemas. You specify the point in time to which you want to revert by providing a valid time stamp.By default, database triggers are disabled for all tables involved. You can override this defaultbehavior by specifying the ENABLE TRIGGERS clause.Note: For more information about recycle bin and flashback semantics, refer to Oracle DatabaseAdministrators Guide 10g Release 2 (10.2). Oracle Database 10g: SQL Fundamentals II 2 - 26 73. SQL Star International Limited FLASHBACK TABLE StatementUnauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates. DROP TABLE emp2; DROP TABLE succeeded. SELECT original_name, operation, droptime FROM recyclebin; a) hasc om ail uide FLASHBACK TABLE emp2 TO BEFORE DROP; @ engm t G FLASHBACK TABLE succeeded. raled lka is Stu O (rh th RA to useA NIK se L M Copyright n2009, Oracle. All rights reserved. U le liceH E RA ferab AL trans FLASHBACK TABLE Statement (continued) R KA no ExamplesSyntax andn-The example restores the EMP2 table to a state before a DROP statement.The recycle bin is actually a data dictionary table containing information about dropped objects.Dropped tables and any associated objects, such as indexes, constraints, nested tables, and so on, arenot removed and still occupy space. They continue to count against user space quotas, untilspecifically purged from the recycle bin or the unlikely situation where they must be purged by thedatabase because of tablespace space constraints.Each user can be thought of as an owner of a recycle bin because, unless a user has the SYSDBAprivilege, the only objects that the user has access to in the recycle bin are those that the user owns. Auser can view his or her objects in the recycle bin by using the following statement:SELECT * FROM RECYCLEBIN;When you drop a user, any objects belonging to that user are not placed in the recycle bin and anyobjects in the recycle bin are purged.You can purge the recycle bin with the following statement:PURGE RECYCLEBIN; Oracle Database 10g: SQL Fundamentals II 2 - 27 74. SQL Star International Limited External TablesUnauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates. ah as o m) a ilc ide @ n gm t Guarale tuder hlk his S AO ( se t I KR to u AN nseL M Copyright 2009, Oracle. All rights reserved. U le liceHRA ferab External ALETables s R tablean read-only table whose metadata is stored in the database but whose data isr is a K external n-tAn A nostored outside the database. This external table definition can be thought of as a view that is used forrunning any SQL query against external data without requiring that the external data first be loadedinto the database. The external table data can be queried and joined directly and in parallel withoutrequiring that the external data first be loaded in the database. You can use SQL, PL/SQL, and Javato query the data in an external table.The main difference between external tables and regular tables is that externally organized tables areread-only. No data manipulation language (DML) operations are possible, and no indexes can becreated on them. However, you can create an external table, and thus unload data, by using theCREATE TABLE AS SELECT command.The Oracle server provides two major access drivers for external tables. One, the loader access driver(or ORACLE_LOADER), is used for reading of data from external files whose format can beinterpreted by the SQL*Loader utility. Note that not all SQL*Loader functionality is supported withexternal tables. Oracle Database 10g: SQL Fundamentals II 2 - 28 75. SQL Star International Limited External Tables (continued)The ORACLE_DATAPUMP access driver can be used to both import and export data using aplatform-independent format. The ORACLE_DATAPUMP access driver writes rows from a SELECTstatement to be loaded into an external table as part of a CREATE TABLE ...ORGANIZATIONEXTERNAL...AS SELECT statement. You can then use SELECT to read data out of that data file.You can also create an external table definition on another system and use that data file. This allowsUnauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates.data to be moved between Oracle databases. a) hasc om ail uide gm t G @ n a rale tuder hlk his S A O ( se t I KR to uAN nse U L M lice R AH rableA LE ansfeAR on-tr K n Oracle Database 10g: SQL Fundamentals II 2 - 29 76. SQL Star International Limited Creating a Directory for the External TableCreate a DIRECTORY object that corresponds to the directoryUnauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates.on the file system where the external data source resides. CREATE OR REPLACE DIRECTORY emp_dir AS //emp_dir; a h aso m) GRANT READ ON DIRECTORY emp_dir TO hr; l a i c ide @ n gm t Guarale tuder hlk his S A O ( se t I KR to uAN nseL M Copyright 2009, Oracle. All rights reserved.U le lice HRA ferab ExampleALEsof Creating an External Table RCREATE an r DIRECTORY statement to create a directory object. A directory object specifies an K the non-tUseAalias for a directory on the servers file system where an external data source resides. You can usedirectory names when referring to an external data source, rather than hard code the operating systempath name, for greater file management flexibility.You must have CREATE ANY DIRECTORY system privileges to create directories. When you createa directory, you are automatically granted the READ and WRITE object privileges and can grantREAD and WRITE privileges to other users and roles. The DBA can also grant these privileges toother users and roles.A user needs READ privileges for all directories used in external tables to be accessed and WRITEprivileges for the log, bad, and discard file locations being used.In addition, a WRITE privilege is necessary when the external table framework is being used tounload data.Oracle also provides the ORACLE_DATAPUMP type, with which you can unload data (that is, readdata from a table in the database and insert it into an external table) and then reload it into an OracleDatabase. This is a one-time operation that can be done when the table is created. After the creationand initial population is done, you cannot update, insert, or delete any rows. Oracle Database 10g: SQL Fundamentals II 2 - 30 77. SQL Star International Limited Example of Creating an External Table (continued)SyntaxCREATE [OR REPLACE] DIRECTORY AS path_name;In the syntax:OR REPLACE Specify OR REPLACE to re-create the directory databaseUnauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates.object if it already exists. You can use this clause to change the definitionof an existing directory without dropping, re- creating, and regrantingdatabase object privileges previously granted on the directory. Users who werepreviously grantedprivileges on a redefined directory can continue to access the directory without requiring that the privileges be regranted.directory Specify the name of the directory object to be created. Themaximum length of the directory name is 30 bytes. Youcannotqualify a directory object with a schema name. a Specify the full path name of the operating system directoryhasm)path_nameto be accessed. The path name is case sensitive.il e co gma GuidThe syntax for using the ORACLE_DATAPUMP access driver leas follows: t is @n a ra tudeCREATE TABLE extract_empsr hlk his S O ( se tORGANIZATION EXTERNAL (TYPE ORACLE_DATAPUMP A KR to uNI s PARAMETERS ( ) DEFAULT DIRECTORY AACCESS e nU L M LOCATION ()liceRAH rable PARALLEL 4LE ansfe RA -tr REJECT LIMIT UNLIMITEDAS A K nonSELECT * FROM ;Oracle Database 10g: SQL Fundamentals II 2 - 31 78. SQL Star International Limited Creating an External TableUnauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates. CREATE TABLE ( , ) ORGANIZATION EXTERNAL (TYPE DEFAULT DIRECTORY ACCESS PARAMETERSa ( ) )) has LOCATION () c) m o il REJECT LIMIT [0 | | UNLIMITED]; uidema gG rale@ dent lka is StuO (rh th RA to useA NIK se L M Copyright n2009, Oracle. All rights reserved.U le liceH RA feraban E Creating ALExternal TablesR externaln using the ORGANIZATION EXTERNAL clause of the CREATE TABLEYou create n-t ra tables KA nostatement. You are not, in fact, creating a table. Rather, you are creating metadata in the datadictionary that you can use to access external data. You use the ORGANIZATION clause to specifythe order in which the data rows of the table are stored. By specifying EXTERNAL in theORGANIZATION clause, you indicate that the table is a read-only table located outside the database.Note that the external files must already exist outside the database.TYPE indicates the access driver of the external table. The accessdriver is the API that interprets the external data for the database. If you do not specify TYPE, Oracleuses the default access driver, ORACLE_LOADER. The other option is ORACLE_DATAPUMP.You use the DEFAULT DIRECTORY clause to specify one or more Oracle Database directory objectsthat correspond to directories on the file system where the external data sources may reside.The optional ACCESS PARAMETERS clause enables you to assign values to the parameters of thespecific access driver for this external table. Oracle Database 10g: SQL Fundamentals II 2 - 32 79. SQL Star International Limited Creating an External Table (continued)Use the LOCATION clause to specify one external locator for each external data source. Usually, the is a file, but it need not be.The REJECT LIMIT clause enables you to specify how many conversion errors can occur during aquery of the external data before an Oracle error is returned and the query is aborted. The defaultUnauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates.value is 0. a) hasc om ail uide gm t G @ n a rale tuder hlk his S A O ( se t I KR to uAN nse U L M lice R AH rableA LE ansfeAR on-tr K n Oracle Database 10g: SQL Fundamentals II 2 - 33 80. SQL Star International Limited Creating an External Table by Using ORACLE_LOADERUnauthorized reproduction or distribution prohibited. Copyright 2011, Oracle and/or its affiliates. CREATE TABLE oldemp ( fname char(25), lname CHAR(25)) ORGANIZATION EXTERNAL (TYPE ORACLE_LOADER DEFAULT DIRECTORY emp_dir ACCESS PARAMETERS (RECORDS DELIMITED BY NEWLINENOBADFILEaNOLOGFILE ) has FIELDS TERMINATED BY , c om (fname POSITION ( 1:20) CHAR, ail uidelname POSITION (22:41) CHAR)) gm t G@ n LOCATION (emp.dat))a rale tude PARALLEL 5(r hlk his S REJECT LIMIT 200; tO se RA CREATE TABLE succeeded. u ANIK se to L M Copyright n2009, Oracle. All rights reserved.U le lice H E RA ferab AL trans Example of Creating an External Table by Using the ORACLE_LOADER Access DriverR there KA no 10,jones,11-Dec-1934Assume thatn- is a flat file that has records in the following format:20,smith,12-Jun-1972Records are delimited by new lines, and the fields are all terminated by a comma ( , ). The name ofthe file is /emp_dir/emp.dat.To convert this file as the data source for an external table, whose metadata will reside in thedatabase, you must perform the following steps:1. Create a directory object, emp_dir, as follows:CREATE DIRECTORY emp_dir AS /emp_dir ; 2. Run the CREATE TABLE command shown in the slide.The example in the slide illustrates the table specification to create an external table for the file:/emp_dir/emp.datOracle Database 10g: SQL Fundamentals II 2 - 34 81. SQL Star International Limited Example of Creating an External Table by Using the ORACLE_LOADER Access Driver (continued) In the example, the TYPE specification is given only to illustrate its use. ORACLE_LOADER is the default access driver if not specified. The ACCESS PARAMETERS option provides values to parameters of the specific access driver, which are interpreted by the access driver,