48742447 11g-sql-fundamentals-ii-additional-practices-and-solutions

7,767 views

Published on

Published in: Technology
0 Comments
4 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
7,767
On SlideShare
0
From Embeds
0
Number of Embeds
15
Actions
Shares
0
Downloads
832
Comments
0
Likes
4
Embeds 0
No embeds

No notes for slide

48742447 11g-sql-fundamentals-ii-additional-practices-and-solutions

  1. 1. Oracle Database 11g: SQLFundamentals IIAdditional Practices and SolutionsD49994GC10Edition 1.0August 2007D52149®Oracle Internal &Oracle AcademyUse Only
  2. 2. Copyright © 2007, Oracle. All rights reserved.DisclaimerThis course provides an overview of features and enhancements planned in release11g. It is intended solely to help you assess the business benefits of upgrading to 11gand to plan your IT projects.This course in any form, including its course labs and printed matter, containsproprietary information that is the exclusive property of Oracle. This course and theinformation contained herein may not be disclosed, copied, reproduced, or distributedto anyone outside Oracle without prior written consent of Oracle. This course and itscontents are not part of your license agreement nor can they be incorporated into anycontractual agreement with Oracle or its subsidiaries or affiliates.This course is for informational purposes only and is intended solely to assist you inplanning for the implementation and upgrade of the product features described. It isnot a commitment to deliver any material, code, or functionality, and should not berelied upon in making purchasing decisions. The development, release, and timing ofany features or functionality described in this document remain at the sole discretionof Oracle.This document contains proprietary information and is protected by copyright andother intellectual property laws. You may copy and print this document solely for yourown use in an Oracle training course. The document may not be modified or altered inany way. Except where your use constitutes "fair use" under copyright law, you maynot use, share, download, upload, copy, print, display, perform, reproduce, publish,license, post, transmit, or distribute this document in whole or in part without theexpress authorization of Oracle.The information contained in this document is subject to change without notice. If youfind any problems in the document, please report them in writing to: Oracle University,500 Oracle Parkway, Redwood Shores, California 94065 USA. This document is notwarranted to be error-free.Restricted Rights NoticeIf this documentation is delivered to the United States Government or anyone usingthe documentation on behalf of the United States Government, the following notice isapplicable:U.S. GOVERNMENT RIGHTSThe U.S. Government’s rights to use, modify, reproduce, release, perform, display, ordisclose these training materials are restricted by the terms of the applicable Oraclelicense agreement and/or the applicable U.S. Government contract.Trademark NoticeOracle is a registered trademark of Oracle Corporation and/or its affiliates. Othernames may be trademarks of their respective owners.AuthorChaitanya KoratamaddiTechnical Contributorsand ReviewersClaire BennettKen CooperYanti ChangLaszlo CzinkoczkiBurt DemchickGerlinde FrenzenJoel GoodmanLaura GarzaRichard GreenNancy GreenbergAkira KinutaniWendy LoIsabelle MarchandTimothy McglueAlan PaulsonSrinivas PutrevuBryan RobertsClinton ShafferAbhishek SinghJenny Tsai SmithJames SpillerLori TritzLex van der WerffMarcie YoungEditorsNita PavitranArijit GhoshRaj KumarGraphic DesignerSatish BettegowdaPublisherMichael Sebastian AlmeidaOracle Internal &Oracle AcademyUse Only
  3. 3. iiiContentsPrefaceI IntroductionLesson Objectives I-2Lesson Agenda I-3Course Objectives I-4Course Prerequisites I-5Course Agenda I-6Lesson Agenda I-7Human Resources (HR) Schema Used in This Course I-8Appendixes Used in This Course I-9Development Environments I-10Lesson Agenda I-11Review of Using Oracle SQL Developer I-12Creating a Database Connection I-13Creating a Schema Object I-14Using the SQL Worksheet I-15Executing SQL Statements I-16Saving SQL Statements I-17Executing SQL Scripts I-18Lesson Agenda I-19SQL Statements in SQL*Plus I-20Review of Restricting Data I-21Review of Sorting Data I-22Review of SQL Functions I-23Review of Single-Row Functions I-24Review of Types of Group Functions I-25Review of Using Subqueries I-26Review of Manipulating Data I-27Lesson Agenda I-28Oracle Database 11g SQL Documentation I-29Additional Resources I-30Summary I-31Practice I: Overview I-32Oracle Internal &Oracle AcademyUse Only
  4. 4. iv1 Controlling User AccessObjectives 1-2Lesson Agenda 1-3Controlling User Access 1-4Privileges 1-5System Privileges 1-6Creating Users 1-7User System Privileges 1-8Granting System Privileges 1-9Lesson Agenda 1-10What Is a Role? 1-11Creating and Granting Privileges to a Role 1-12Changing Your Password 1-13Lesson Agenda 1-14Object Privileges 1-15Granting Object Privileges 1-17Passing On Your Privileges 1-18Confirming Granted Privileges 1-19Lesson Agenda 1-20Revoking Object Privileges 1-21Summary 1-23Practice 1: Overview 1-242 Managing Schema ObjectsObjectives 2-2Lesson Agenda 2-3ALTER TABLE Statement 2-4Adding a Column 2-6Modifying a Column 2-7Dropping a Column 2-8SET UNUSED Option 2-9Lesson Agenda 2-11Adding a Constraint Syntax 2-12Adding a Constraint 2-13ON DELETE CASCADE 2-14Deferring Constraints 2-15Difference Between INITIALLY DEFERRED and INITIALLY IMMEDIATE 2-16Deferring Constraints: Example 2-17Dropping a Constraint 2-18Disabling Constraints 2-19Oracle Internal &Oracle AcademyUse Only
  5. 5. vEnabling Constraints 2-20Cascading Constraints 2-22Renaming Table Columns and Constraints 2-24Lesson Agenda 2-25Overview of Indexes 2-26CREATE INDEX with the CREATE TABLE Statement 2-27Function-Based Indexes 2-29Removing an Index 2-30DROP TABLE … PURGE 2-31Lesson Agenda 2-32FLASHBACK TABLE Statement 2-33Using the FLASHBACK TABLE Statement 2-35Lesson Agenda 2-36External Tables 2-37Creating a Directory for the External Table 2-38Creating an External Table 2-40Creating an External Table by Using ORACLE_LOADER 2-42Querying External Tables 2-44Creating an External Table by Using ORACLE_DATAPUMP: Example 2-45Summary 2-46Practice 2: Overview 2-473 Managing Objects with Data Dictionary ViewsObjectives 3-2Lesson Agenda 3-3Data Dictionary 3-4Data Dictionary Structure 3-5How to Use the Dictionary Views 3-7USER_OBJECTS and ALL_OBJECTS Views 3-8USER_OBJECTS View 3-9Lesson Agenda 3-10Table Information 3-11Column Information 3-12Constraint Information 3-14USER_CONSTRAINTS: Example 3-15Querying USER_CONS_COLUMNS 3-16Lesson Agenda 3-17View Information 3-18Sequence Information 3-19Confirming Sequences 3-20Oracle Internal &Oracle AcademyUse Only
  6. 6. viIndex Information 3-21USER_INDEXES: Examples 3-22Querying USER_IND_COLUMNS 3-23Synonym Information 3-24Lesson Agenda 3-25Adding Comments to a Table 3-26Summary 3-27Practice 3: Overview 3-284 Manipulating Large Data SetsObjectives 4-2Lesson Agenda 4-3Using Subqueries to Manipulate Data 4-4Retrieving Data Using a Subquery as Source 4-5Inserting Using a Subquery as a Target 4-7Using the WITH CHECK OPTION Keyword on DML Statements 4-9Lesson Agenda 4-11Overview of the Explicit Default Feature 4-12Using Explicit Default Values 4-13Copying Rows from Another Table 4-14Lesson Agenda 4-15Overview of Multitable INSERT Statements 4-16Types of Multitable INSERT Statements 4-18Multitable INSERT Statements 4-19Unconditional INSERT ALL 4-21Conditional INSERT ALL: Example 4-23Conditional INSERT ALL 4-24Conditional INSERT FIRST: Example 4-25Conditional INSERT FIRST 4-26Pivoting INSERT 4-28Lesson Agenda 4-31MERGE Statement 4-32MERGE Statement Syntax 4-33Merging Rows: Example 4-34Lesson Agenda 4-37Tracking Changes in Data 4-38Example of the Flashback Version Query 4-39VERSIONS BETWEEN Clause 4-41Summary 4-42Practice 4: Overview 4-43Oracle Internal &Oracle AcademyUse Only
  7. 7. vii5 Managing Data in Different Time ZonesObjectives 5-2Lesson Agenda 5-3Time Zones 5-4TIME_ZONE Session Parameter 5-5CURRENT_DATE, CURRENT_TIMESTAMP, and LOCALTIMESTAMP 5-6Comparing Date and Time in a Session’s Time Zone 5-7DBTIMEZONE and SESSIONTIMEZONE 5-9TIMESTAMP Data Types 5-10TIMESTAMP Fields 5-11Difference Between DATE and TIMESTAMP 5-12Comparing TIMESTAMP Data Types 5-13Lesson Agenda 5-14INTERVAL Data Types 5-15INTERVAL Fields 5-17INTERVAL YEAR TO MONTH: Example 5-18INTERVAL DAY TO SECOND Data Type: Example 5-20Lesson Agenda 5-21EXTRACT 5-22TZ_OFFSET 5-23FROM_TZ 5-25TO_TIMESTAMP 5-26TO_YMINTERVAL 5-27TO_DSINTERVAL 5-28Daylight Saving Time 5-29Summary 5-31Practice 5: Overview 5-326 Retrieving Data Using SubqueriesObjectives 6-2Lesson Agenda 6-3Multiple-Column Subqueries 6-4Column Comparisons 6-5Pairwise Comparison Subquery 6-6Nonpairwise Comparison Subquery 6-8Lesson Agenda 6-10Scalar Subquery Expressions 6-11Scalar Subqueries: Examples 6-12Lesson Agenda 6-14Correlated Subqueries 6-15Oracle Internal &Oracle AcademyUse Only
  8. 8. viiiUsing Correlated Subqueries 6-17Lesson Agenda 6-19Using the EXISTS Operator 6-20Find Employees Who Have at Least One Person Reporting to Them 6-21Find All Departments That Do Not Have Any Employees 6-22Correlated UPDATE 6-23Using Correlated UPDATE 6-24Correlated DELETE 6-26Using Correlated DELETE 6-27Lesson Agenda 6-28WITH Clause 6-29WITH Clause: Example 6-30Summary 6-32Practice 6: Overview 6-347 Regular Expression SupportObjectives 7-2Lesson Agenda 7-3What Are Regular Expressions? 7-4Benefits of Using Regular Expressions 7-5Using the Regular Expressions Functions and Conditions in SQL and PL/SQL 7-6Lesson Agenda 7-7What Are Metacharacters? 7-8Using Metacharacters with Regular Expressions 7-9Lesson Agenda 7-11Regular Expressions Functions and Conditions: Syntax 7-12Performing a Basic Search Using the REGEXP_LIKE Condition 7-13Replacing Patterns Using the REGEXP_REPLACE Function 7-14Finding Patterns Using the REGEXP_INSTR Function 7-15Extracting Substrings Using the REGEXP_SUBSTR Function 7-16Lesson Agenda 7-17Subexpressions 7-18Using Subexpressions with Regular Expression Support 7-19Why Access the nth Subexpression? 7-20REGEXP_SUBSTR: Example 7-21Lesson Agenda 7-22Using the REGEXP_COUNT Function 7-23Regular Expressions and Check Constraints: Examples 7-24Summary 7-25Practice 7: Overview 7-26Oracle Internal &Oracle AcademyUse Only
  9. 9. ixAppendix A: Practice SolutionsAppendix B: Table DescriptionsAppendix C: Using the SQL Developer GUIAppendix D: Using SQL*PlusAppendix E: Generating Reports by Grouping Related DataAppendix F: Hierarchical RetrievalAppendix G: Writing Advanced ScriptsAppendix H: Oracle Database Architectural ComponentsIndexAdditional PracticesAdditional Practice SolutionsOracle Internal &Oracle AcademyUse Only
  10. 10. Oracle Internal &Oracle AcademyUse Only
  11. 11. PrefaceOracle Internal &Oracle AcademyUse Only
  12. 12. Oracle Internal &Oracle AcademyUse Only
  13. 13. Preface - 3ProfileBefore You Begin This CourseBefore you begin this course, you should have working experience with SQL.How This Course Is OrganizedOracle Database 11g: SQL Fundamentals II is an instructor-led course featuringlectures and hands-on exercises. Online demonstrations and written practicesessions reinforce the concepts and skills that are introduced.Oracle Internal &Oracle AcademyUse Only
  14. 14. Preface - 4Related PublicationsOracle PublicationsTitle Part NumberOracle® Database Reference 11g Release 1 (11.1) B28320-01Oracle® Database SQL Language Reference 11g –Release 1 (11.1) B28286-01Oracle® Database Concepts 11g Release 1 (11.1) B28318-01Oracle® Database Advanced Application Developer’s Guide –11g Release 1 (11.1) B28424-01SQL*Plus® User’s Guide and Reference Release 11.1 B31189-01Oracle Database SQL Developer Users Guide Release 1.2 E10406-01Additional Publications• System release bulletins• Installation and user’s guides• read.me files• International Oracle User’s Group (IOUG) articles• Oracle MagazineOracle Internal &Oracle AcademyUse Only
  15. 15. Preface - 5Typographic ConventionsWhat follows are two lists of typographical conventions that are used specificallywithin text or within code.Typographic Conventions Within TextConvention Object or Term ExampleUppercase Commands, Use the SELECT command to viewfunctions, information stored in the LAST_NAMEcolumn names, column of the EMPLOYEES table.table names,PL/SQL objects,schemasLowercase, Filenames, where: role is the name of the roleitalic syntax variables, to be created.usernames,passwordsInitial cap Trigger and Assign a When-Validate-Item trigger tobutton names the ORD block.Choose Cancel.Italic Books, names of For more information on the subject seecourses and Oracle SQL Referencemanuals, and Manualemphasizedwords or phrases Do not save changes to the database.Quotation marks Lesson module This subject is covered in Lesson 3,titles referenced “Working with Objects.”within a courseOracle Internal &Oracle AcademyUse Only
  16. 16. Preface - 6Typographic Conventions (continued)Typographic Conventions Within CodeConvention Object or Term ExampleUppercase Commands, SELECT employee_idfunctions FROM employees;Lowercase, Syntax variables CREATE ROLE role;italicInitial cap Forms triggers Form module: ORDTrigger level: S_ITEM.QUANTITYitemTrigger name: When-Validate-Item. . .Lowercase Column names, . . .table names, OG_ACTIVATE_LAYERfilenames, (OG_GET_LAYER (prod_pie_layer))PL/SQL objects . . .SELECT last_nameFROM employees;Bold Text that must CREATE USER scottbe entered by a IDENTIFIED BY tiger;userOracle Internal &Oracle AcademyUse Only
  17. 17. __________________Additional Practices__________________Oracle Internal &Oracle AcademyUse Only
  18. 18. Oracle Database 11g: SQL Fundamentals II Additional Practices - 2The following exercises can be used for extra practice after you have discussed datamanipulation language (DML) and data definition language (DDL) statements in the lessonstitled “Managing Schema Objects” and “Manipulating Large Data Sets.”Note: Run the lab_ap_cre_special_sal.sql, lab_ap_cre_sal_history.sql,and lab_ap_cre_mgr_history.sql scripts in the labs folder to create theSPECIAL_SAL, SAL_HISTORY, and MGR_HISTORY tables.1. The Human Resources department wants to get a list of underpaid employees, salaryhistory of employees, and salary history of managers based on an industry salary survey.So they have asked you to do the following:Write a statement to do the following:- Retrieve details such as the employee ID, hire date, salary, and manager ID of thoseemployees whose employee ID is more than or equal to 200 from the EMPLOYEEStable.- If the salary is less than $5,000, insert details such as the employee ID and salaryinto the SPECIAL_SAL table.- Insert details such as the employee ID, hire date, and salary into theSAL_HISTORY table.- Insert details such as the employee ID, manager ID, and salary into theMGR_HISTORY table.2. Query the SPECIAL_SAL, SAL_HISTORY, and MGR_HISTORY tables to view theinserted records.SALARY_HISTORYSPECIAL_SALOracle Internal &Oracle AcademyUse Only
  19. 19. Oracle Database 11g: SQL Fundamentals II Additional Practices - 33. Nita, the DBA, needs you to create a table, which has a primary key constraint, but shewants to name the index to have a different name than the constraint. Create theLOCATIONS_NAMED_INDEX table based on the following table instance chart. Namethe index for the PRIMARY KEY column as LOCATIONS_PK_IDX.4. Query the USER_INDEXES table to display the INDEX_NAME for theLOCATIONS_NAMED_INDEX table.Column Name Deptno DnamePrimary Key YesData Type Number VARCHAR2Length 4 30MGR_HISTORYOracle Internal &Oracle AcademyUse Only
  20. 20. Oracle Database 11g: SQL Fundamentals II Additional Practices - 4The following exercises can be used for extra practice after you have discussed datetimefunctions.You work for a global company and the new vice president of operations wants to know thedifferent time zones of all the company branches. The new vice president has requested thefollowing information:5. Alter the session to set the NLS_DATE_FORMAT to DD-MON-YYYY HH24:MI:SS.6. a. Write queries to display the time zone offsets (TZ_OFFSET) for the following timezones:Australia/SydneyChile/Easter Islandb. Alter the session to set the TIME_ZONE parameter value to the time zone offset ofAustralia/Sydney.c. Display SYSDATE, CURRENT_DATE, CURRENT_TIMESTAMP, andLOCALTIMESTAMP for this session.Note: The output might be different based on the date when the command is executed.d. Alter the session to set the TIME_ZONE parameter value to the time zone offset ofChile/Easter Island.Note: The results of the preceding question are based on a different date, and in somecases, they will not match the actual results that the students get. Also, the time zoneoffset of the various countries may differ, based on daylight saving time.e. Display SYSDATE, CURRENT_DATE, CURRENT_TIMESTAMP, andLOCALTIMESTAMP for this session.Note: The output may be different based on the date when the command is executed.f. Alter the session to set NLS_DATE_FORMAT to DD-MON-YYYY.Oracle Internal &Oracle AcademyUse Only
  21. 21. Oracle Database 11g: SQL Fundamentals II Additional Practices - 5Note• Observe in the preceding question that CURRENT_DATE, CURRENT_TIMESTAMP, andLOCALTIMESTAMP are all sensitive to the session time zone. Observe that SYSDATE isnot sensitive to the session time zone.• The results of the preceding question are based on a different date, and in some cases,they will not match the actual results that the students get. Also the time zone offset ofthe various countries may differ, based on daylight saving time.7. The Human Resources department wants a list of employees who are up for review inJanuary, so they have requested you to do the following:Write a query to display the last names, month of the date of hire, and hire date of thoseemployees who have been hired in the month of January, irrespective of the year of hire.Oracle Internal &Oracle AcademyUse Only
  22. 22. Oracle Database 11g: SQL Fundamentals II Additional Practices - 6The following exercises can be used for extra practice after you have discussed advancedsubqueries.8. The CEO needs a report on the top three earners in the company for profit sharing. Youare responsible to provide the CEO with a list.Write a query to display the top three earners in the EMPLOYEES table. Display their lastnames and salaries.9. The benefits for the state of California have been changed based on a local ordinance. Sothe benefits representative has asked you to compile a list of the people who are affected.Write a query to display the employee ID and last names of the employees who work inthe state of California.Hint: Use scalar subqueries.10. Nita, the DBA, wants to remove old information from the database. One of the things shethinks is unnecessary is the old employment records. She has asked you to do thefollowing:Write a query to delete the oldest JOB_HISTORY row of an employee by looking up theJOB_HISTORY table for the MIN(START_DATE) for the employee. Delete the recordsof only those employees who have changed at least two jobs.Hint: Use a correlated DELETE command.11. The vice president of Human Resources needs the complete employment records for theannual employee recognition banquet speech. The vice president makes a quick phonecall to stop you from following the DBA’s orders.Roll back the transaction.Oracle Internal &Oracle AcademyUse Only
  23. 23. Oracle Database 11g: SQL Fundamentals II Additional Practices - 712. The sluggish economy is forcing management to take cost reduction actions. The CEOwants to review the highest paid jobs in the company. You are responsible to provide theCEO with a list based on the following specifications:Write a query to display the job IDs of those jobs whose maximum salary is above halfthe maximum salary in the entire company. Use the WITH clause to write this query.Name the query MAX_SAL_CALC.Oracle Internal &Oracle AcademyUse Only
  24. 24. Oracle Database 11g: SQL Fundamentals II Additional Practices - 8Additional Practices: Case StudyIn the case study for the SQL Fundamentals I course, you built a set of database tables for avideo application. In addition, you inserted, updated, and deleted records in a video storedatabase and generated a report.The following is a diagram of the tables and columns that you created for the video application:Note: First, run the dropvid.sql script in the labs folder to drop tables if they alreadyexist. Then run the buildvid.sql script in the labs folder to create and populate thetables.Oracle Internal &Oracle AcademyUse Only
  25. 25. Oracle Database 11g: SQL Fundamentals II Additional Practices - 9Additional Practices: Case Study (continued)1. Verify that the tables were created properly by running a report to show the list of tablesand their column definitions.2. Verify the existence of the MEMBER_ID_SEQ and TITLE_ID_SEQ sequences in thedata dictionary.3. You want to create some users who have access only to their own rentals. Create a usercalled Carmen and grant her the privilege to select from the RENTAL table.Note: Make sure to prefix the user name with your database account. For example, if youare the user oraxx, then create a user called oraxx_Carmen.Oracle Internal &Oracle AcademyUse Only
  26. 26. Oracle Database 11g: SQL Fundamentals II Additional Practices - 10Additional Practices: Case Study (continued)4. Add a price column (number 4,2) to the TITLE table to store how much it costs to rentthe title.5. Add a CATEGORY table to store CATEGORY_ID and CATEGORY_DESCRIPTION. Thetable has a foreign key with the CATEGORY column in the TITLE table.6. Select all the tables from the data dictionary.7. There is no real need to store reservations any longer. You can drop the table.8. Create a RENTAL_HISTORY table to store the details of a rental by member for the last6 months. (Hint: You can copy the RENTAL table.)9. Show a list of the top 10 titles rented in the last month grouped by category.10. You want to calculate the late fee (price of title/day) if the member brings back the video6 days late.11. Show a list of members who have rented 2 or more times.Oracle Internal &Oracle AcademyUse Only
  27. 27. Oracle Database 11g: SQL Fundamentals II Additional Practices - 11Additional Practices: Case Study (continued)12. Show a list of titles who have a status of rented.13. Show a list of members who have “99” in their phone numbers.Oracle Internal &Oracle AcademyUse Only
  28. 28. Oracle Internal &Oracle AcademyUse Only
  29. 29. _______________AdditionalPracticeSolutions_______________Oracle Internal &Oracle AcademyUse Only
  30. 30. Oracle Database 11g: SQL Fundamentals II Additional Practice Solutions - 2The following exercises can be used for extra practice after you have discussed datamanipulation language (DML) and data definition language (DDL) statements in the lessonstitled “Managing Schema Objects” and “Manipulating Large Data Sets.”Note: Run the lab_ap_cre_special_sal.sql, lab_ap_cre_sal_history.sql,and lab_ap_cre_mgr_history.sql scripts in the labs folder to create theSPECIAL_SAL, SAL_HISTORY, and MGR_HISTORY tables.1. The Human Resources department wants to get a list of underpaid employees, salaryhistory of employees, and salary history of managers based on an industry salary survey.So they have asked you to do the following:Write a statement to do the following:- Retrieve details such as the employee ID, hire date, salary, and manager ID of thoseemployees whose employee ID is more than or equal to 200 from the EMPLOYEEStable.- If the salary is less than $5,000, insert details such as the employee ID and salaryinto the SPECIAL_SAL table.- Insert details such as the employee ID, hire date, and salary into theSAL_HISTORY table.- Insert details such as the employee ID, manager ID, and salary into theMGR_HISTORY table.INSERT ALLWHEN SAL < 5000 THENINTO special_sal VALUES (EMPID, SAL)ELSEINTO sal_history VALUES(EMPID,HIREDATE,SAL)INTO mgr_history VALUES(EMPID,MGR,SAL)SELECT employee_id EMPID, hire_date HIREDATE,salary SAL, manager_id MGRFROM employeesWHERE employee_id >=200;2. Query the SPECIAL_SAL, SAL_HISTORY, and the MGR_HISTORY tables to view theinserted records.SELECT * FROM special_sal;SELECT * FROM sal_history;SELECT * FROM mgr_history;Oracle Internal &Oracle AcademyUse Only
  31. 31. Oracle Database 11g: SQL Fundamentals II Additional Practice Solutions - 33. Nita, the DBA, needs you to create a table, which has a primary key constraint, but shewants to name the index to have a different name than the constraint. Create theLOCATIONS_NAMED_INDEX table based on the following table instance chart. Namethe index for the PRIMARY KEY column as LOCATIONS_PK_IDX.CREATE TABLE LOCATIONS_NAMED_INDEX(location_id NUMBER(4) PRIMARY KEY USING INDEX(CREATE INDEX locations_pk_idx ONLOCATIONS_NAMED_INDEX(location_id)),location_name VARCHAR2(20));4. Query the USER_INDEXES table to display the INDEX_NAME for theLOCATIONS_NAMED_INDEX table.SELECT INDEX_NAME, TABLE_NAMEFROM USER_INDEXESWHERE TABLE_NAME = ‘LOCATIONS_NAMED_INDEX’;Column Name Deptno DnamePrimary Key YesData Type Number VARCHAR2Length 4 30Oracle Internal &Oracle AcademyUse Only
  32. 32. Oracle Database 11g: SQL Fundamentals II Additional Practice Solutions - 4The following exercises can be used for extra practice after you have discussed datetimefunctions.You work for a global company and the new vice president of operations wants to know thedifferent time zones of all the company branches. The new vice president has requested thefollowing information:5. Alter the session to set NLS_DATE_FORMAT to DD-MON-YYYY HH24:MI:SS.ALTER SESSIONSET NLS_DATE_FORMAT = ‘DD-MON-YYYY HH24:MI:SS’;6. a. Write queries to display the time zone offsets (TZ_OFFSET) for the following timezones:- Australia/SydneySELECT TZ_OFFSET (‘Australia/Sydney’) from dual;- Chile/Easter IslandSELECT TZ_OFFSET (‘Chile/EasterIsland’) from dual;b. Alter the session to set the TIME_ZONE parameter value to the time zone offset ofAustralia/Sydney.ALTER SESSION SET TIME_ZONE = ‘+10:00’;c. Display SYSDATE, CURRENT_DATE, CURRENT_TIMESTAMP, andLOCALTIMESTAMP for this session.Note: The output may be different based on the date when the command isexecuted.SELECT SYSDATE, CURRENT_DATE, CURRENT_TIMESTAMP,LOCALTIMESTAMP FROM DUAL;d. Alter the session to set the TIME_ZONE parameter value to the time zone offset ofChile/Easter Island.Note: The results of the preceding question are based on a different date, and insome cases, they will not match the actual results that the students get. Also, thetime zone offset of the various countries may differ, based on daylight saving time.ALTER SESSION SET TIME_ZONE = ‘-06:00’;e. Display SYSDATE, CURRENT_DATE, CURRENT_TIMESTAMP, andLOCALTIMESTAMP for this session.Oracle Internal &Oracle AcademyUse Only
  33. 33. Oracle Database 11g: SQL Fundamentals II Additional Practice Solutions - 5Note: The output may be different based on the date when the command isexecuted.SELECT SYSDATE, CURRENT_DATE, CURRENT_TIMESTAMP,LOCALTIMESTAMP FROM DUAL;f. Alter the session to set NLS_DATE_FORMAT to DD-MON-YYYY.ALTER SESSION SET NLS_DATE_FORMAT = ‘DD-MON-YYYY’;Note• Observe in the preceding question that CURRENT_DATE, CURRENT_TIMESTAMP, andLOCALTIMESTAMP are all sensitive to the session time zone. Observe that SYSDATE isnot sensitive to the session time zone.• The results of the preceding question are based on a different date, and in some cases,they will not match the actual results that the students get. Also, the time zone offset ofthe various countries may differ, based on daylight saving time.7. The Human Resources department wants a list of employees who are up for review inJanuary, so they have requested you to do the following:Write a query to display the last names, month of the date of hire, and hire date of thoseemployees who have been hired in the month of January, irrespective of the year of hire.SELECT last_name, EXTRACT (MONTH FROM HIRE_DATE),HIRE_DATE FROM employeesWHERE EXTRACT (MONTH FROM HIRE_DATE) = 1;Oracle Internal &Oracle AcademyUse Only
  34. 34. Oracle Database 11g: SQL Fundamentals II Additional Practice Solutions - 6The following exercises can be used for extra practice after you have discussed advancedsubqueries.8. The CEO needs a report on the top three earners in the company for profit sharing. Youare responsible to provide the CEO with a list.Write a query to display the top three earners in the EMPLOYEES table. Display their lastnames and salaries.SELECT last_name, salaryFROM employees eWHERE 3 > (SELECT COUNT (*)FROM employeesWHERE e.salary < salary);9. The benefits for the state of California have been changed based on a local ordinance. Sothe benefits representative has asked you to compile a list of the people who are affected.Write a query to display the employee ID and last names of the employees who work inthe state of California.Hint: Use scalar subqueries.SELECT employee_id, last_nameFROM employees eWHERE ((SELECT location_idFROM departments dWHERE e.department_id = d.department_id )IN (SELECT location_idFROM locations lWHERE state_province = ‘California’));10. Nita, the DBA, wants to remove old information from the database. One of the things shethinks is unnecessary is the old employment records. She has asked you to do thefollowing:Write a query to delete the oldest JOB_HISTORY row of an employee by looking up theJOB_HISTORY table for the MIN(START_DATE)for the employee. Delete the recordsof only those employees who have changed at least two jobs.Hint: Use a correlated DELETE command.Oracle Internal &Oracle AcademyUse Only
  35. 35. Oracle Database 11g: SQL Fundamentals II Additional Practice Solutions - 7DELETE FROM job_history JHWHERE employee_id = (SELECT employee_idFROM employees EWHERE JH.employee_id = E.employee_idAND START_DATE = (SELECT MIN(start_date)FROM job_history JHWHERE JH.employee_id = E.employee_id)AND 3 > (SELECT COUNT(*)FROM job_history JHWHERE JH.employee_id = E.employee_idGROUP BY EMPLOYEE_IDHAVING COUNT(*) >= 2));11. The vice president of Human Resources needs the complete employment records for theannual employee recognition banquet speech. The vice president makes a quick phonecall to stop you from following the DBA’s orders.Roll back the transaction.ROLLBACK;12. The sluggish economy is forcing management to take cost reduction actions. The CEOwants to review the highest paid jobs in the company. You are responsible to provide theCEO with a list based on the following specifications:Write a query to display the job IDs of those jobs whose maximum salary is above halfthe maximum salary in the entire company. Use the WITH clause to write this query.Name the query MAX_SAL_CALC.WITHMAX_SAL_CALC AS (SELECT job_title, MAX(salary) ASjob_totalFROM employees, jobsWHERE employees.job_id = jobs.job_idGROUP BY job_title)SELECT job_title, job_totalFROM MAX_SAL_CALCWHERE job_total > (SELECT MAX(job_total) * 1/2FROM MAX_SAL_CALC)ORDER BY job_total DESC;Oracle Internal &Oracle AcademyUse Only
  36. 36. Oracle Database 11g: SQL Fundamentals II Additional Practice Solutions - 8Additional Practices: Case Study SolutionsIn the case study for the SQL Fundamentals I course, you built a set of database tables for avideo application. In addition, you inserted, updated, and deleted records in a video storedatabase and generated a report.The following is a diagram of the tables and columns that you created for the video application:Note: First, run the dropvid.sql script in the labs folder to drop tables if they alreadyexist. Then run the buildtab.sql script in the labs folder to create and populate thetables.Oracle Internal &Oracle AcademyUse Only
  37. 37. Oracle Database 11g: SQL Fundamentals II Additional Practice Solutions - 9Additional Practices: Case Study Solutions (continued)1. Verify that the tables were created properly by running a report to show the list of tablesand their column definitions.SELECT table_name,column_name,data_type,nullableFROM user_tab_columnsWHERE table_nameIN(MEMBER,TITLE,TITLE_COPY,RENTAL,RESERVATION);2. Verify the existence of the MEMBER_ID_SEQ and TITLE_ID_SEQ sequences in thedata dictionary.SELECT sequence_name FROM user_sequences;3. You want to create some users who have access only to their own rentals. Create a usercalled Carmen and grant her the privilege to select from the RENTAL table.Note: Make sure to prefix the user name with your database account. For example, if youare the user oraxx, then create a user called oraxx_Carmen.CREATE USER oraxx_carmen IDENTIFIED BY oracle ;GRANT select ON rental TO oraxx_carmen;4. Add a price column (number 4,2) to the TITLE table to store how much it costs to rentthe title.ALTER TABLE title ADD(price NUMBER(6))5. Add a CATEGORY table to store CATEGORY_ID and CATEGORY_DESCRIPTION. Thetable has a foreign key with the CATEGORY column in the TITLE table.CREATE TABLE CATEGORY( "CATEGORY_ID" NUMBER(6,0) NOT NULL ENABLE,"CATEGORY_DESCRIPTION" VARCHAR2(4000 BYTE),CONSTRAINT "CATEGORY_PK" PRIMARY KEY ("CATEGORY_ID"))6. Select all the tables from the data dictionary.SELECT table_name FROM user_tables order by table_name;7. There is no real need to store reservations any longer. You can drop the table.DROP TABLE reservation cascade constraints;8. Create a RENTAL_HISTORY table to store the details of a rental by member for the last6 months. (Hint: You can copy the RENTAL table.)CREATE TABLE rental_history as select * from rental where 1 = 1Oracle Internal &Oracle AcademyUse Only

×