+ All Categories
Home > Documents > OCP - SQL&PL_SQL(Vol2)

OCP - SQL&PL_SQL(Vol2)

Date post: 10-Apr-2015
Category:
Upload: api-3814149
View: 700 times
Download: 4 times
Share this document with a friend
348
Introduction to Oracle: SQL and PL/SQL Using Procedure Builder Volume Two S Participant Guide Edition 1.1 M03990 T1001E11
Transcript
Page 1: OCP - SQL&PL_SQL(Vol2)

���������� �� ��� �� ������ ������ ���� ���������� ����� ��� ��� � �������� ����

������� ���

���

�����

Page 2: OCP - SQL&PL_SQL(Vol2)

Authors

Neena KochharDebby Kramer

Technical Contributorsand Reviewers

Christian BauwensDebra BowmanLenny BrunsonJackie CollinsRalf DurbenBrian FryAnthony HolbrookKarlene JensenSarah JonesGlenn MaslenSundar NagarathnamSandra SchrickUlrike SchwinnRosemarie TrumanJenny TsaiLaura Van Deusen

Publishers

Stephanie JonesKimberly LeeJennifer RobertsonMark Turangan

��������� �������� ������������ ����� ����� ��� ������ ���������

��� ��� !�������� �������� ����������� ��"��!����� �" ������ �����������# �� ��

�������� ���� � ������� �����!��� ���������� ������������ �� �� ��� ������$

� �� ��� �� ���� ��������� %� ��������� ��&� '������ ����������� �" ��� ��"�&���

�� �����%����� (" ���� ��� !�������� �� ��������� �� � )�*� +�����!��� ������ �"

��� ,�����!��� �" ,�"����� ���� �� �� ��������� &��� '��������� '����� ��� ��� "��$

��&��� ������ �� �������%��-

������� �!�� ������

)��� � ��������� �� ������� �� %� ��� +�����!��� �� � %.��� �� ������������ "��

��!!������ ��!� ��� ��"�&��� ��� ����� %� ���!�� �� %� '��������� '����� ��"�$

&��� ���� /������ ��&� ��� �� ��� "���� �� � %��������� 0�1 0�1 0��1 �" ,/�'*

�2����3$3��� '����� �� �������� ,��� ��� ��!� ��� *�"�&��� 0����%�� ��441�

��� !������� �� ��� ������� �" �� !�� ��� %� ������ �� ��� "��! �� %� ��� !����

&���� � ��� �5����� ����� &������ ���!������ �" ���6����&��� �� ������ *�������

��� � �"������ ������������ ��� ����� ������� �� � ��������� �" ��������� ��& ���

!�� ��� �� �� ����� ���7�� ���!���� ����������

(" ���� ��� !�������� �� ��������� �� �)�*� +�����!��� ������ ��� &����� ��� ,�$

����!��� �" ,�"����� ���� �� �� ��������� &��� 8'��������� '������9 �� ��"���� ��

/�' 2����3$�:� '����� �� ,���$+������� ���� ���� ��������� ((( 0; �� ��431�

�� ��"��!����� �� ���� ��� !��� �� � %.��� �� ������ &���� � ������� (" �� "���

��� ���%��!� �� ��� ��� !��������� ������ ������ ���! �� &������ �� 6����&���

�� ������ *�������� ������ ������������ 2 ������ <��=&��� >�5 �2�4�� '��$

&���*������ ���:�2������������������ ���� ���&������ ���� ���� ��� !���

�� ����� "����

*?@A<� �� <@7*?@� <����� �� > ������ ,��������7�� ������3 *������ ������

*������ ,���������7�� ��� ,�������7� ��� �����!��=� �� ���������� �����$

!��=� �" ������ ������������

��� ����� ���� ��� �� ��!���� ��!�� ��� ��� "�� ������"������� � ������ �����

��� !�� %� �����!��=� �" ����� ���������� �&�����

Page 3: OCP - SQL&PL_SQL(Vol2)

��������� ���� ��� �� �������

Page 4: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� ��� ��� ������ ���� ��������� �������� !

Page 5: OCP - SQL&PL_SQL(Vol2)

��������� ���� ��� �� ������� � "

� #����$��

You can create a command file containing a WHERE clause to restrict the rowsdisplayed. To change the condition each time the command file is run, you usesubstitution variables. Substitution variables can replace values in the WHEREclause, a text string, and even a column or a table name.

At the end of this lesson, you should be able to

� Create a SELECT statement that prompts the user to enter a value at runtime.

� Use the SQL*Plus ACCEPT command to define a variable.

� Define a variable that can be automatically picked up by the SELECT statementat runtime.

Page 6: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� ��� ��� ������ ���� ��������� �������� %

Page 7: OCP - SQL&PL_SQL(Vol2)

��������� ���� ��� �� ������� � &

�$��$��'

The reports produced so far have not been interactive in any way. In a finishedapplication, the user would trigger the report, and the report would run withoutfurther prompting. The range of data reported would be predetermined by the fixedWHERE clause in the SQL*Plus script file. However, SQL*Plus enables you tocreate reports that prompt the user to supply their own values to restrict the range ofdata returned.

���������$� �������

To create interactive reports, you can embed substitution variables in a command fileor in single SQL commands. A variable can be thought of as a container in whichvalues are temporarily stored.

Page 8: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� ��� ��� ������ ���� ��������� �������� (

Page 9: OCP - SQL&PL_SQL(Vol2)

��������� ���� ��� �� ������� � �

�� ��������� ���� ���

In SQL*Plus, you can use single ampersand substitution variable to temporarily storevalues.

You can predefine variables in SQL*Plus by using the ACCEPT or DEFINEcommands. ACCEPT reads a line of user input and stores it in a variable. DEFINEcreates and assigns a value to a variable.

)*������ �� ���������� ����� �� +���

� Report figures for the current quarter or specified date range only.

� Report on data relevant to the user requesting the report only.

� Display personnel within a given department only.

��,�� ���������$� )������

Interactive effects are not restricted to direct user interaction with the WHEREclause. The same principles can be used to achieve other goals, for example:

� Dynamically altering headers and footers.

� Obtaining input parameters from a file rather than from a person.

� Passing values from one SQL statement to another.

SQL*Plus does not support validation checks on user input. Make sure that theprompts you write for the user are simple and unambiguous.

Page 10: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� ��� ��� ������ ���� ��������� �������� -

Page 11: OCP - SQL&PL_SQL(Vol2)

��������� ���� ��� �� ������� � .

����� /�������� �� ��������� ���� ���

When running a report, users often want to restrict the data returned dynamically.SQL*Plus provides this flexibility by means of user variables. Use an ampersand (&)to identify each variable in your SQL statement. You do not need to define the valueof each variable.

Notation Description

&user_variable Indicates a variable in a SQL statement; if the variable doesnot exist, SQL*Plus prompts the user for a value.SQL*Plus discards a new variable once it is used.

)*�����

Create a statement to prompt the user for a department number at runtime. The reportshould contain each employee’s number, last name, and salary.

SQL> SELECT id, last_name, salary2 FROM s_emp3 WHERE dept_id = &department_number;

Enter value for department_number: 31

ID LAST_NAME SALARY---------- ------------------------- ---------- 3 Nagayama 1400 11 Magee 1400

With the single ampersand, the user is prompted every time the command is executed.

�)0 )��12 3������

To confirm the changes in the SQL statement, use the SQL*Plus SET VERIFYcommand. Setting SET VERIFY to ON forces SQL*Plus to display the text of acommand before and after it replaces substitution variables with values.

Page 12: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� ��� ��� ������ ���� ��������� �������� 45

Page 13: OCP - SQL&PL_SQL(Vol2)

��������� ���� ��� �� ������� � 44

����� /�������� �� ��������� ���� ��� ���������

��������� 3,������� ��� +��� ����� '��, �� ��������� ���� ���

Remember that in a WHERE clause, date and character values must be enclosedwithin single quotation marks. The same rule applies to the substitution variables.

To avoid entering the quotation marks at run time, enclose the variable in singlequotation marks within the SQL statement itself.

)*�����

Write a query to retrieve the employee number, last name, and salary of all employeesbased on the title entered at the prompt by the user.

SQL> SELECT id, last_name, salary2 FROM s_emp3 WHERE title = ’&job_title’;

Enter value for job_title: Stock Clerk

Page 14: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� ��� ��� ������ ���� ��������� �������� 4!

Page 15: OCP - SQL&PL_SQL(Vol2)

��������� ���� ��� �� ������� � 4"

����� /�������� �� ��������� ���� ��� ���������

��������� 3����� 6����7 )*���������7 ��� 0�*� �� �������

Not only can you use the substitution variables in the WHERE clause of a SQLstatement, but these variables can be used to substitute column names, expressions, ortext.

)*������

Display the number and any other column and any condition of orders. Try a coupleof variations of column names and conditions to observe the results.

SQL> SELECT id, &column_name2 FROM s_ord3 WHERE &condition;

Enter value for column_name: totalEnter value for condition: payment_type = ’CASH’

ID TOTAL---------- ---------- 103 377 110 1539.13 111 2770 98 595

SQL> SELECT id, &column_name2 FROM s_ord3 WHERE &condition;

Enter value for column_name: date_orderedEnter value for condition: total > 300000

ID DATE_ORDE---------- --------- 100 31-AUG-92 109 08-SEP-92

If you do not enter a value for the substitution variable, you will obtain an error whenyou execute above command.

Page 16: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� ��� ��� ������ ���� ��������� �������� 4%

Page 17: OCP - SQL&PL_SQL(Vol2)

��������� ���� ��� �� ������� � 4&

+������ ���� ���� ���

You can predefine user variables before executing a SELECT statement. SQL*Plusprovides two commands for defining and setting user variables: DEFINE andACCEPT.

Command Description

DEFINE variable = value Creates a CHAR datatype user variable and assignsa value to it.

DEFINE variable Displays the variable, its value, and its datatype.

DEFINE Displays all user variables with value and datatype.

ACCEPT (see syntax below) Reads a line of user input and stores it in a variable.

/ ����� �����*

ACCEPT variable [datatype][FORMAT][PROMPT text][HIDE]

where: variable is the name of the variable that stores the value.If it does not exist, SQL*Plus creates it.

datatype is either NUMBER, CHAR, or DATE. CHARhas a maximum length limit of 240 bytes.DATE checks against a format model, and thedatatype is CHAR.

FOR[MAT] specifies the format model, for example A10 or9.999.

PROMPT text displays the text before the user can enter thevalue.

HIDE suppresses what the user enters, for example apassword.

Note: Do not prefix the SQL*Plus substitution parameter with the ampersand (&)when referencing the substitution parameter in the ACCEPT command.

Page 18: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� ��� ��� ������ ���� ��������� �������� 4(

Page 19: OCP - SQL&PL_SQL(Vol2)

��������� ���� ��� �� ������� � 4�

+������ ���� ���� ��� ���������

8���������

� Both the ACCEPT and DEFINE commands will create a variable if the variabledoes not exist; these commands will automatically redefine a variable if it exists.

� When using the DEFINE command, use single quotation marks (‘ ’) to enclose astring that contains an embedded space.

� Use the ACCEPT command to

� Give a customized prompt when accepting user input. Otherwise, you will seethe default “Enter value for variable.”

� Explicitly define a NUMBER or DATE datatype variable.

� Hide user input for security reasons.

)*�����

Display the region number and name for a specified department name. Create a scriptfile called l7prompt.sql, and use the ACCEPT command to prompt the user with acustomized message.

SET ECHO OFFACCEPT p_dname PROMPT ’Provide the department name: ’SELECT d.name, r.id, r.name ”REGION NAME”FROM s_dept d, s_region rWHERE d.region_id = r.idAND UPPER(d.name) LIKE UPPER(’%&p_dname%’)/SET ECHO ON

SQL> START l7promptProvide the department name: sales

�)0 )39� 3������

The ECHO variable controls whether START and @ commands list each command ina command file as the command is executed. Setting the ECHO variable to ON liststhe command and setting it to OFF suppresses the listing.

Page 20: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� ��� ��� ������ ���� ��������� �������� 4-

Page 21: OCP - SQL&PL_SQL(Vol2)

��������� ���� ��� �� ������� � 4.

+������ ���� ���� ��� ���������

Variables are defined until you either

� Issue the UNDEFINE command on a variable.

� Exit SQL*Plus.

When you undefine variables, you can verify your changes with the DEFINEcommand. When you exit SQL*Plus, variables defined during that session are lost.To define those variables for every session, modify your login.sql file so that thosevariables are created at startup.

)*�����

Create a variable to hold the department position. Display all department names thatmatch the position in the variable.

SQL> DEFINE dname = salesSQL> DEFINE dname

DEFINE dname = ”sales” (CHAR)

SQL> SELECT name2 FROM s_dept3 WHERE lower(name) = ’&dname’;

NAME--------------------SalesSalesSalesSalesSales

SQL> UNDEFINE dnameSQL> DEFINE dname

symbol dname is UNDEFINED

Page 22: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� ��� ��� ������ ���� ��������� �������� !5

Page 23: OCP - SQL&PL_SQL(Vol2)

��������� ���� ��� �� ������� � !4

������ ����� ���� � ������ 1���

A parameter is a value that you can pass to a report by means of the command line.To create and run a parameterized report, follow these steps:

1. Create a script file to include the SELECT statement.

2. In the SELECT statement, use the notation &number for each variable reference.

3. In the command line, specify a value following the filename. Use a space toseparate values.

)*�����

Create a script file, l7param.sql, to produce a series of reports by job title. Instead ofprompting you for the title, you enter the job title on the command line when youstart the file.

SET ECHO OFFSELECT id, last_name, salaryFROM s_empWHERE title = ’&1’/SET ECHO ON

SQL> START l7param President

8���������

� You can use the DEFINE command to associate meaningful names withparameters.

� A prefix can be used to differentiate column names (no prefix), simple variables(for example, v_test), and parameterized variables (for example, p_name).

� The position of each parameter value in the command line is significant. The firstvalue corresponds to &1, the second parameter to &2, and onward.

� Reports can accept a maximum of nine parameters that are named from &1 to &9.

� SQL*Plus retains report parameters and their values until you redefine them,undefine them, or terminate your SQL*Plus session.

Page 24: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� ��� ��� ������ ���� ��������� �������� !!

Page 25: OCP - SQL&PL_SQL(Vol2)

��������� ���� ��� �� ������� � !"

�������

Substitution variables are useful for running reports. They allow flexibility to replacevalues in a WHERE clause, column names, and expressions. You can customizereports by writing script files with

� Single ampersand substitution variables.

� The ACCEPT command.

� The DEFINE command.

� The UNDEFINE command.

� Substitution variables in the command line.

Page 26: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� ��� ��� ������ ���� ��������� �������� !%

Page 27: OCP - SQL&PL_SQL(Vol2)

��������� ���� ��� �� ������� � !&

�������� �$��$��'

This practice gives you the opportunity to create files that can be run interactively byusing substitution variables to create runtime selection criteria.

�������� 3�������

� Creating a query to display values using substitution variables

� Starting a command file containing substitution variables

� Using the ACCEPT command

Page 28: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� ��� ��� ������ ���� ��������� �������� !(

�������� �

Determine whether the following statements are true or false.

1. A single ampersand substitution variable prompts only once.True / False

2. The ACCEPT command is a SQL command.True / False

The following questions use the S_EMP, S_CUSTOMER, and S_PRODUCT tables.

3. Write a script file to display the user name, first and last names concatenatedtogether, and start dates of employees within a specified range. Prompt the userfor the two ranges by using the ACCEPT command. Use the format MM/DD/YY.Save the script file as p7q3.sql. Your result should look like the output below.

Enter the low date range (’MM/DD/YY’): 09/01/91Enter the high date range (’MM/DD/YY’): 09/01/92

USERID EMPLOYEE START_DAT-------- ------------------------------ ---------acatchpo Antoinette Catchpole 09-FEB-92hgiljum Henry Giljum 18-JAN-92mnguyen Mai Nguyen 22-JAN-92adumas Andre Dumas 09-OCT-91emaduro Elena Maduro 07-FEB-92

Page 29: OCP - SQL&PL_SQL(Vol2)

��������� ���� ��� �� ������� � !�

�������� � ���������

4. Write a script to search for customer names and numbers. The search conditionshould allow for case-insensitive name searches. Save the script file as p7q4.sql.Your result should look like the output below.

Please enter the customer’s name: sport

ID CUSTOMER NAME------ ---------------------------------------- 201 Unisports 203 Delhi Sports 204 Womansport 205 Kam’s Sporting Goods 206 Sportique 207 Sweet Rock Sports 208 Muench Sports 211 Kuhn’s Sports 212 Hamada Sport 213 Big John’s Sports Emporium 215 Sporta Russia

Page 30: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� ��� ��� ������ ���� ��������� �������� !-

�������� � ���������

If you have time, complete the following exercises.

5. Write a report containing the sales representative name, customer name, and eachcustomer’s total sales order. Prompt the user for a region number. Save the scriptas p7q5.sql.

SQL> START p7q5

Please enter a region number: 1

EMPLOYEE CUSTOMER SALES––––––––––– –––––––––––––––––––––––––––– ––––––––––Colin Magee Beisbol Si! $2,722Colin Magee Big John’s Sports Emporium $1,020,935Colin Magee Ojibway Retail $1,539Colin Magee Womansport $603,870

Page 31: OCP - SQL&PL_SQL(Vol2)

�������� �� � �� ����� �

���� �����

Page 32: OCP - SQL&PL_SQL(Vol2)

����� ������ �� ������ ��� � ������ ����� ����� ��� ���� ����

Page 33: OCP - SQL&PL_SQL(Vol2)

�������� �� � �� ����� � ���� ����� ��!

��"�������

Before you build your tables, you design your database. In this lesson, youexamine the data modeling process and relational database concepts, and definenormalization. You also translate an entity relationship model into a relationaldatabase design.

At the end of this lesson, you should be able to

� Describe the stages of system development.

� List and define basic types of data relationships.

� Define a relational database and its components.

� Read an entity relationship model.

� Translate an entity relationship model into a relational database design.

Page 34: OCP - SQL&PL_SQL(Vol2)

����� ������ �� ������ ��� � ������ ����� ����� ��� ���� ����#

Page 35: OCP - SQL&PL_SQL(Vol2)

�������� �� � �� ����� � ���� ����� ��$

��������

When you create a database, you need to carefully consider its components. Forassistance with the design, you can follow the concepts outlined in this lesson.

�%���& �����'&��� (%���

In order to logically and successfully create the database objects in the Oracle7Server, you complete the system development cycle. Each stage of the cycle containsspecific activities that you perform to achieve the best possible database design.

���� �����

Database design is just one of the stages of the development cycle. Through gooddatabase design, you can achieve a reliable, high-performance system.

()������� �� ������ �

There are many challenges you face as you design your system. They range fromcontrolling data redundancy to enhancing communications with users. By meetingeach of these challenges through good database design, you improve the performanceof your database.

Page 36: OCP - SQL&PL_SQL(Vol2)

����� ������ �� ������ ��� � ������ ����� ����� ��� ���� ����*

Page 37: OCP - SQL&PL_SQL(Vol2)

�������� �� � �� ����� � ���� ����� ��+

�%���& �����'&��� (%���

From concept to production, develop a database by using the system developmentcycle. The cycle contains multiple stages of development. This top-down, systematicapproach to database development transforms business information requirements intoan operational database.

����� �� �����'&���

Strategy and Analysis

� Study and analyze the business requirements. Interview users and managers toidentify the information requirements. Incorporate the enterprise and applicationmission statements as well as any future system specifications.

� Build models of the system. Transfer the business narrative developed in thestrategy and analysis phase into a graphical representation of business informationneeds and rules. Confirm and refine the model with the analysts and experts.

Design

� Design the database. The entity relationship model maps entities to tables,attributes to columns, relationships to foreign keys, and business rules toconstraints.

Build and Document

� Build the prototype system. Write and execute the commands to create the tablesand supporting objects for the database.

� Develop user documentation, help-screen text, and operations manuals to supportthe use and operation of the system.

Transition

� Refine the prototype. Move an application into production with user acceptancetesting, conversion of existing data, and parallel operations. Make anymodifications required.

Production

� Roll out the system to the users. Operate the production system. Monitor itsperformance, and enhance and refine the system.

Page 38: OCP - SQL&PL_SQL(Vol2)

����� ������ �� ������ ��� � ������ ����� ����� ��� ���� �����

Page 39: OCP - SQL&PL_SQL(Vol2)

�������� �� � �� ����� � ���� ����� ��,

���� �����

Designing a relational database system involves converting a model into a workablesoftware representation. The entities (or objects) perceived by the user aretransformed into tables in the database. All forms of design involve a mixture ofrules, judgements, and common sense, and relational design is no different.

During a design effort, your goal is to design reliable, high-performance systemsusing the deliverables from the analysis effort. The following key factors describe indetail why you should bother to design at all.

������&���

The initial design of a system has an enormous impact on its final performance.Generally the impact is much greater than any remedial tuning.

�������� -''�������

Application systems are typically developed by teams of developers. Without somedesign specification from which to work, developers will each build in their ownstyle. Not only does good design promote a cohesive look and feel, but it also helpsensure that all components of the resulting application system are integrated witheach other.

���������� ���) ��)�� �%���&�

Often, there are requirements that a new system integrate with existing systems, oreven with systems yet to be built. Good design extends the integration benefitsmentioned above into corporate or worldwide systems.

���&������� � (�&&��������

A major part of a designer’s job is to communicate design decisions to others. At thevery least, these decisions need to be documented.

��������%

Tackle performance issues during design rather than during production. For example,developing an application in a small, controlled environment does not test real-worldsituations or a large set of data, factors that can reveal design flaws.

-��� .���������� �)� /)���

Many of the problems you will face will have been encountered by others before you.Use existing successful design solutions wherever you can.

Page 40: OCP - SQL&PL_SQL(Vol2)

����� ������ �� ������ ��� � ������ ����� ����� ��� ���� ����01

������

ÉÉÉÉ

ÉÉÉÉ

Page 41: OCP - SQL&PL_SQL(Vol2)

�������� �� � �� ����� � ���� ����� ��00

� �� ��

Models are a cornerstone of design. Engineers build a model of a car before putting itinto production to work out any details. In the same manner, system designersdevelop models to explore ideas and improve the understanding of the databasedesign.

���'��� �� �� ���

Models help communicate the concepts in people’s minds. They can be used for thefollowing purposes:

� Communicate

� Categorize

� Describe

� Specify

� Investigate

� Evolve

� Analyze

� Imitate

The objective is to produce a model that fits a multitude of these uses, can beunderstood by an end user, but contains sufficient detail for a developer to build adatabase system.

Page 42: OCP - SQL&PL_SQL(Vol2)

����� ������ �� ������ ��� � ������ ����� ����� ��� ���� ����0

Page 43: OCP - SQL&PL_SQL(Vol2)

�������� �� � �� ����� � ���� ����� ��0!

2����% .�������)�' �� �����

Entity relationship models are derived from business specifications or narratives. Thismodel is a graphical representation of business information needs and rules.

2����% .�������)�' �� ���

Entity relationship models separate the information required by a business from theactivities performed within a business. Although businesses can change theiractivities, the type of information tends to remain constant. Therefore, the datastructures also tend to be constant.

�������� �� 2����% .�������)�' �� ���

� Documents information requirements for the organization in a clear, preciseformat

� Provides an easily understood pictorial map for the database design

� Develops and refines the model easily

� Provides a clear picture of the scope of the information requirements

� Offers an effective framework for integrating multiple applications, developmentprojects, and purchased application packages

3�% (�&'������

Component Description

Entity A thing of significance about which information needs tobe known.

Attribute Something that describes or qualifies an entity.

Relationship A named association between entities showing optionalityor degree.

Page 44: OCP - SQL&PL_SQL(Vol2)

����� ������ �� ������ ��� � ������ ����� ����� ��� ���� ����0#

Page 45: OCP - SQL&PL_SQL(Vol2)

�������� �� � �� ����� � ���� ����� ��0$

2����% .�������)�' �� �� (����'��

An entity relationship model is composed of entities, attributes, and relationships.

2�������

An entity represents a thing of significance about the business system, or a discretecategory or collection of related data. Examples are customer, orders, and employees.

To represent an entity in a model, use the following conventions:

� Soft box with any dimensions

� Singular, unique entity name

� Entity name in uppercase

� Optional synonym names in uppercase within parentheses “()”

-���������

An attribute describes entities and holds the specific information that should beknown about an entity. For example, for the customer entity, the attributes would becustomer number, name, phone number, and address.

If an entity does not have attributes that need to be known from the businessviewpoint, then it is not within the scope of the system requirements, and should notappear in the model.

Each of the attributes is either required or optional. This state is called optionality.

To represent an entity in a model, use the following conventions:

� Use singular names in lowercase.

� Tag mandatory attributes, or values that must be known, with an asterisk “*”.

� Tag optional attributes, or values that may be known, with an “o”.

���4�� � ���������

A unique identifier (UID) is any combination of attributes or relationships, or both,that serves to distinguish occurrences of an entity. Each entity occurrence must beuniquely identifiable.

� Tag each attribute that is part of the UID with a number symbol (#).

� Tag secondary UIDs with a number sign in parentheses (#).

Page 46: OCP - SQL&PL_SQL(Vol2)

����� ������ �� ������ ��� � ������ ����� ����� ��� ���� ����0*

Page 47: OCP - SQL&PL_SQL(Vol2)

�������� �� � �� ����� � ���� ����� ��0+

2����% .�������)�' �� �� (����'�� ���������

.�������)�'�

Each entity must have a relationship that represents the information requirements andrules of the business. The relationship is a two-directional association between twoentities, or between an entity and itself. When an entity has a relationship with itself,it is recursive.

Each direction of the relationship contains

� A name, for example, taught by or assigned to.

� An optionality, either must be or may be.

� A degree, either one and only one or one or more.

Note: Cardinality is a synonym for the term degree.

.�������)�' �%��5

Each source entity {may be | must be} relationship name {one and only one | one ormore} destination entity.

Note: Convention is to read clockwise.

.�������)�' ���&&��� (����������

Symbol Description

Dashed line Optional element indicating “may be.”

Solid line Mandatory element indicating “must be.”

Crow’s foot Degree element indicating “one or more.”

Single line Degree element indicating “one and only one.”

Page 48: OCP - SQL&PL_SQL(Vol2)

����� ������ �� ������ ��� � ������ ����� ����� ��� ���� ����0�

Page 49: OCP - SQL&PL_SQL(Vol2)

�������� �� � �� ����� � ���� ����� ��0,

2����% .�������)�' �� �� (����'�� ���������

���4�� � �������� 6)����) �)� .�������)�'

An entity may be uniquely identified through a relationship. Use a UID bar toindicate that a relationship is part of the entity’s unique identifier. The relationshipincluded in a UID must be mandatory and one and only one in the direction thatparticipates in the UID.

25&'��

When you order items, you have an order number and an item with a unique line itemnumber. But when another order is placed, that item number is no longer unique.Therefore, the item is uniquely identified by its attribute number and the specificorder number to which the item is related.

Order number Item number Product number

100 1 209

100 2 399

100 3 876

101 1 630

101 2 297

.�������� .�������)�'

A relationship between an entity and itself is called a recursive relationship. It isrepresented by a “pig’s ear.”

.�������)�' 6%'��

Type Description

One-to-one Degree of one and only one in both directions. These typesare rare, and may really be the same entity, or an attributeof the entity.

Many-to-one Degree of one or more in one direction and a degree of oneand only one in the other direction. Very common.

Many-to-many Degree of one or more in both directions. Very common.Resolve them with an intersection entity.

Page 50: OCP - SQL&PL_SQL(Vol2)

����� ������ �� ������ ��� � ������ ����� ����� ��� ���� ���� 1

Page 51: OCP - SQL&PL_SQL(Vol2)

�������� �� � �� ����� � ���� ����� �� 0

2����% .�������)�' �� �� (����'�� ���������

7��&��8����

Before creating the database design, you want to eliminate the problems of dataredundancy by normalizing the data model. Modify the data model to supportdifferent functional requirements and alternate database designs by normalizing thestorage of data before you create the database.

�������� �� 7��&��8����

� Minimizes data redundancy

� Reduces integrity problems

� Identifies missing entities, relationships, and tables

7��&��8���� .����

Rule Description

First normal form (1NF) All attributes must be single-valued and notrepeating.

Second normal form (2NF) An attribute must depend upon its entity’s entireunique identifier.

Third normal form (3NF) No non-UID attribute can be dependent uponanother non-UID attribute.

Page 52: OCP - SQL&PL_SQL(Vol2)

����� ������ �� ������ ��� � ������ ����� ����� ��� ���� ����

Page 53: OCP - SQL&PL_SQL(Vol2)

�������� �� � �� ����� � ���� ����� �� !

��������% (��������� � 3�%�

Ensure that users perform only operations that leave the database in a correct andconsistent state by enforcing data integrity constraints. All data integrity constraintsshould be enforced by the database server or the application software. Keyscorrespond to integrity constraints. The three types of keys are primary key, uniquekey, and foreign key.

Integrity Constraint Type Description

Entity No part of a primary key can be NULL and thevalue must be unique.

Referential Foreign key values must match a primary key or beNULL.

Column Values in the column must match the defineddatatype.

User-defined Values must comply with the business rules.

25&'��� �� ���������� � ��������% (���������

� An employee in the finance department cannot have a title of programmer.

� A salesperson’s commission cannot exceed 50% of the base salary.

� Customers can only have Excellent, Good, or Poor credit rating values.

Page 54: OCP - SQL&PL_SQL(Vol2)

����� ������ �� ������ ��� � ������ ����� ����� ��� ���� ���� #

Page 55: OCP - SQL&PL_SQL(Vol2)

�������� �� � �� ����� � ���� ����� �� $

��������% (��������� � 3�%� ���������

���&�% 3�%�

Each row in the table is uniquely identified by a column or set of columns called aprimary key (PK). The primary key is defined as allowing no duplicate values andcannot be NULL.

A primary key consisting of multiple columns is called a composite primary key or acompound primary key. The columns of a composite primary key must be unique incombination, although the individual columns can have duplicates. No part of aprimary key can contain a null value.

(� � �� 3�%�

A table can have several candidate keys. A candidate key is a column or combinationof columns that can serve as the primary key for the table.

Select one candidate key to be the primary key for the table. The other candidatesbecome alternate keys or unique keys. They must be UNIQUE and NOT NULL.

Page 56: OCP - SQL&PL_SQL(Vol2)

����� ������ �� ������ ��� � ������ ����� ����� ��� ���� ���� *

Page 57: OCP - SQL&PL_SQL(Vol2)

�������� �� � �� ����� � ���� ����� �� +

��������% (��������� � 3�%� ���������

9������ 3�%�

A foreign key (FK) is a column or combination of columns in one table that refers toa primary key or unique key in the same table or in another table. Foreign keys arebased on data values and are purely logical, not physical pointers. A foreign keyvalue must match an existing primary key value or unique key, or else be NULL. If aforeign key is part of a primary key, it cannot contain a null value because no part ofa PK can be NULL.

25&'��

In the S_ITEM table, the ORD_ID cannot contain a null value because it is part of thePK.

ORD_ID 100 100 101 101 102

ITEM_ID 1 2 1 3 1

PRODUCT_ID 10011 10013 30421 41010 20180

...

ID100101102103

CUSTOMER_ID 204 205 206 208

DATE_ORDERED31-AUG-9231-AUG-9201-SEP-9202-SEP-92

...

���&�% 3�%9������ 3�%

�:�62� 6���

�:�. 6���

���&�% 3�%

Page 58: OCP - SQL&PL_SQL(Vol2)

����� ������ �� ������ ��� � ������ ����� ����� ��� ���� ���� �

Page 59: OCP - SQL&PL_SQL(Vol2)

�������� �� � �� ����� � ���� ����� �� ,

�������� �)� ����

The database design stage produces design specifications for a relational database,including definitions for relational tables, indexes, views, and storage space.

�' �)� 2����% .�������)�' �� �� �� 6��� ������� ()��

1. Map the simple entities to tables.

2. Map the attributes to columns and document sample data. Clearly label thecolumn names and their associated generic datatypes; for example, character,number, or date.

3. Map the unique identifiers to a primary key. Be sure to include any foreign keycomponents of the primary key.

4. Map relationships to foreign keys.

- ������ .�4����&����

� Design the indexes, which are database objects that provide direct, quick access torows. You may want to create indexes for alternate keys, foreign keys, andcolumns frequently used in the search condition.

� Establish view definitions, which are logical tables based on one or more tables orviews. Views can restrict access, provide improved presentation of information,and can contain a pre-packaged complex query.

� Plan the physical storage space, which is the amount of space required to store thedata of a table in the database.

� Redefine integrity constraints.

For more information, seeDevelop Complex Data Models and Design Databases course description.

Page 60: OCP - SQL&PL_SQL(Vol2)

����� ������ �� ������ ��� � ������ ����� ����� ��� ���� ����!1

0

!

#

��� �������� � �����0 ��� ����� ��� ��� ���

��� ��� ��� ������������ � � ����������

!

��� ������������ ������� ����

#

Page 61: OCP - SQL&PL_SQL(Vol2)

�������� �� � �� ����� � ���� ����� ��!0

�������� �)� ���� ���������

�%&���� ��� �� ���&��� �)� 6��� ������� ()��

Symbol Definition

PK Primary key column

FK Foreign key column

FK1, FK2 Two foreign keys within the same table

FK1, FK1 Two columns within the same composite foreign key

NN Not null column

U Unique column

U1, U1 Two columns that are unique in combination

;�� ������

� The table name should be easy to trace back to the entity name. The plural of theentity name is sometimes used because the table will contain a set of rows.

� Column names should be easily traced to the entity relationship model. Shortcolumn names will reduce the time required for SQL command parsing.

� You should develop your own naming conventions and standards.

Page 62: OCP - SQL&PL_SQL(Vol2)

����� ������ �� ������ ��� � ������ ����� ����� ��� ���� ����!

Page 63: OCP - SQL&PL_SQL(Vol2)

�������� �� � �� ����� � ���� ����� ��!!

�������� �)� ���� ���������

�' �)� 2������� �� 6����

Create a table instance chart for the new table. The table instance chart should containcolumns for the name of the table, the names of the columns, the key types, null andunique references, foreign key information, column datatype and maximum length,and sample data. Record the name of the table.

�' �)� -��������� �� (���&��

Map each attribute in the entity relationship model to a column name in the table.Add sample data to the chart to show the contents of the table in a visual form. Mapmandatory attributes, tagged with an asterisk (*), to columns defined as NOT NULL(NN).

Do not name columns with SQL reserved words, such as NUMBER. Name columnswith consistent abbreviations, such as NO or NUM (but not both) to avoidprogrammer and user confusion.

For more information, seeOracle7 Server SQL Reference, Release 7.3, “Object Names and Qualifiers” sectionfor reserved words, naming rules, and guidelines.

0

Page 64: OCP - SQL&PL_SQL(Vol2)

����� ������ �� ������ ��� � ������ ����� ����� ��� ���� ����!#

Page 65: OCP - SQL&PL_SQL(Vol2)

�������� �� � �� ����� � ���� ����� ��!$

�������� �)� ���� ���������

�' �)� ���4�� � ��������� �� ���&�% 3�%�

Map the UIDs identified in the entity relationship model by a number symbol (#) toprimary key columns and label the key type as PK. Map a UID containing a singleattribute to a single-column PK. Label the not null and unique references as NN andU. Map a UID that includes multiple attributes to a composite PK. Label thosecolumns NN and U1. If you have an alternate primary key, label it as NN and U, butchoose only one PK.

If the entity’s UID includes the relationship (indicated by the UID bar), add a FKcolumn for each relationship and label it as PK and FK key types. Add FK columnsto the end of the table instance chart or to the right of all columns, even if the FK ispart of the PK. Choose a unique name for each FK column and add sample data.

�62�

<=���

� '����4�����%4�����% �)�''�

<=���

� �� �� ��� �� �)�''� '%&��� �%'�

�.2.��

& ��' ��

!

Page 66: OCP - SQL&PL_SQL(Vol2)

����� ������ �� ������ ��� � ������ ����� ����� ��� ���� ����!*

Page 67: OCP - SQL&PL_SQL(Vol2)

�������� �� � �� ����� � ���� ����� ��!+

�������� �)� ���� ���������

�' .�������)�'� �� 9������ 3�%�

The last step is to map relationship to foreign keys. There are two types ofrelationships to consider: Many-to-one and one-to-one. If your relationship is part ofthe unique identifier, you have already mapped it. Be sure to label mandatoryrelationships with the NN reference. Choose a unique name for the foreign keycolumn.

��%������� .�������)�'�

Map the many-to-one relationship by taking the primary key at the one end andputting it in the table at the many end as a foreign key. This technique also applies torecursive relationships.

���������� �'����� .�������)�'�

You can place the foreign key in the table at either end of the relationship for anoptional one-to-one relationship. Be sure to add the U reference.

�26

<=��

� ���������8�

�27������ ��

�)���&'���%)�&� ���

<=���=

� �&� �� �� ����)����)��'�����

���������� �� ���% .�������)�'�

Place the unique foreign key in the table at the mandatory end and label it NN toenforce the mandatory requirement and U to enforce the one-to-one relationship.

�26

<=���=

<=��

� ���������8�

�27������ ��

�)���&'���%)�&� ���

� �&� �� �� ����)����)��'�����

#

Page 68: OCP - SQL&PL_SQL(Vol2)

����� ������ �� ������ ��� � ������ ����� ����� ��� ���� ����!�

Page 69: OCP - SQL&PL_SQL(Vol2)

�������� �� � �� ����� � ���� ����� ��!,

��&&�%

Logically and successfully create database objects in the Oracle7 Server bycompleting the system development cycle. Each stage helps you to achieve the bestpossible database design.

����� �� �����'&���

� Study and analyze the business requirements.

� Build models of the system.

� Design the database.

� Build the prototype system.

� Write the user documentation.

� Refine the prototype.

� Roll out the system to the users.

2����% .�������)�' �� ��

� Entities are things of significance.

� Attributes describe or qualify two entities.

� Relationships associate two entities.

� Establish unique identifiers.

� Follow normalization rules.

���� �����

� Create a table instance chart.

� Map all entity relationship model components to the chart.

� Add other supporting information and objects.

Page 70: OCP - SQL&PL_SQL(Vol2)

����� ������ �� ������ ��� � ������ ����� ����� ��� ���� ����#1

Page 71: OCP - SQL&PL_SQL(Vol2)

�������� ����

Page 72: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� ��� ��� ������ ����� ��������� ������� ��

Page 73: OCP - SQL&PL_SQL(Vol2)

�������� ���� ��

������ ��

In this lesson, you will create tables. You will also build integrity constraints,which are rules governing what can and cannot be done with the data.

At the end of this lesson, you should be able to

� Create a table containing integrity constraints.

� Identify table naming conventions.

� Describe the datatypes that can be used when specifying column definitions.

� Recognize the indexes that are created automatically by constraints.

� Create a table by populating it with rows from another table.

Page 74: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� ��� ��� ������ ����� ��������� ������� �!

Page 75: OCP - SQL&PL_SQL(Vol2)

�������� ���� �"

� �� ��#

An Oracle7 database can contain multiple data structures. Each structure should beoutlined in the database design so that it can be created during the build stage ofdatabase development.

$��� ����������

Structure Description

Table Stores data.

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

Sequence Generates primary key values.

Index Improves the performance of some queries.

��%%��& �' ������( ��� ����������

� Tables can be created at any time, even while users are using the database.

� You do not need to specify the size of any table. The size is ultimately defined bythe amount of space allocated to the database as a whole. It is important, however,to estimate how much space a table will use over time.

� Table structure can be modified online.

Page 76: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� ��� ��� ������ ����� ��������� ������� �)

Page 77: OCP - SQL&PL_SQL(Vol2)

�������� ���� �(

�������� ����

Create tables to store data by executing the SQL CREATE TABLE command. Thiscommand is one of the data definition language (DDL) commands, which you willcover in the next several lessons. DDL commands are a subset of SQL commandsused to create, modify, or remove Oracle7 database structures. These commands havean immediate effect on the database, and they also record information in the datadictionary.

In order to create a table, a user must have the CREATE TABLE privilege and astorage area in which to create objects. The database administrator uses data controllanguage (DCL) commands, which are covered in a later lesson, to grant privileges tousers.

*������ �&���+

CREATE TABLE [schema.]table(column datatype [DEFAULT expr][column_constraint], ... [table_constraint]);

where: schema is the same as the owner’s name.

table is the name of the table.

DEFAULT expr specifies a default value if a value is omitted inthe INSERT statement.

column is the name of the column.

datatype is the column’s datatype and length.

column_constraint is an integrity constraint as part of the columndefinition.

table_constraint is an integrity constraint as part of the tabledefinition.

For more information, seeOracle7 Server SQL Reference, Release 7.3, “CREATE TABLE.”

Page 78: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� ��� ��� ������ ����� ��������� ������� �,

Page 79: OCP - SQL&PL_SQL(Vol2)

�������� ���� �

�������� ���� ���������

-�'�������� *���.�� ����/� ����

A schema is a collection of objects. Schema objects are the logical structures thatdirectly refer to the data in a database. Schema objects include tables, views,synonyms, sequences, stored procedures, indexes, clusters, and database links.

The tables referenced in a constraint must exist in the same database. If the table doesnot belong to the user creating the constraint, the owner’s name must be prefixed tothe table referenced in the constraint.

.� $01*�� �2����

A column can be given a default value by using the DEFAULT option. This optionprevents null values from entering the columns if a row is inserted without a value forthe column. The default value can be a literal, an expression, or SQL function, suchas SYSDATE and USER, but the value cannot be the name of another column or apseudocolumn, such as NEXTVAL or CURRVAL. The default expression mustmatch the datatype of the column.

Page 80: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� ��� ��� ������ ����� ��������� ������� �34

Page 81: OCP - SQL&PL_SQL(Vol2)

�������� ���� �33

�������� ���� ���������

5�%��� -����

Name database tables and columns according to the standard rules for naming anyOracle7 database object.

� Table names and column names must begin with a letter and can be 1–30characters long.

� Names must contain only the characters A–Z, a–z, 0–9, _ (underscore), $ and #(legal characters, but their use is discouraged).

� Names must not duplicate the name of another object owned by the same Oracle7Server user.

� Names must not be an Oracle7 Server reserved words.

5�%��� 6���������

� Use descriptive names for tables and other database objects.

� Name the same entity consistently in different tables. For example, thedepartment number column is called DEPT_ID in both the S_EMP table and theS_REGION table.

Note: Names are case-insensitive. For example, EMP is treated as the same name aseMP or eMp.

For more information, seeOracle7 Server SQL Reference, Release 7.3, “Object Names and Qualifiers.”

Page 82: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� ��� ��� ������ ����� ��������� ������� �3�

Page 83: OCP - SQL&PL_SQL(Vol2)

�������� ���� �3�

������( $����&2��

There are many different column types. The Oracle7 Server can treat values of onedatatype differently from values of other datatypes. The basic datatypes are character,number, date, and RAW.

��%2�� ������( $����&2��

Datatype Description

VARCHAR2(size) Variable length character values up to maximum lengthsize. Minimum length is 1, maximum length is 2000.

CHAR(size) Fixed length character values of length size. Defaultlength is 1, maximum length is 255.

NUMBER Floating point number with precision of 38 significantdigits.

NUMBER(p,s) Number value having a maximum precision of pranging from 1 to 38 and a maximum scale of s; theprecision is the total number of decimal digits, and thescale is the number of digits to the right of the decimalpoint.

DATE Date and time values between January 1, 4712 B.C.and December 31, 4712 A.D.

LONG Variable length character values up to 2 gigabytes.Only one LONG column is allowed per table.

RAW and LONG RAW Equivalent to VARCHAR2 and LONG, respectively,but used to store byte-oriented or binary data that is notto be interpreted by the Oracle7 Server.

Note: The column width determines the maximum number of characters for valuesin the column. You must specify the size for VARCHAR2 columns. You canspecify the size for NUMBER and CHAR columns, but default values areavailable (38 for NUMBER and 1 for CHAR).

For more information, seeOracle7 Server SQL Reference, Release 7.3, “Datatypes.”

Page 84: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� ��� ��� ������ ����� ��������� ������� �3!

Page 85: OCP - SQL&PL_SQL(Vol2)

�������� ���� �3"

�����������

Constraints have been available with the Oracle7 Server since Version 6. In Oracle7,constraints are enforced at the database level.

You can use constraints to

� Enforce rules at the table level whenever a row is inserted, updated, or deletedfrom that table. The constraint must be satisfied for the operation to succeed.

� Prevent the deletion of a table if there are dependencies from other tables.

� Provide rules for Oracle tools, such as Developer/2000.

$��� ��������& �����������

Constraint Description

NOT NULL Specifies that this column may not contain a null value.

UNIQUE Specifies a column or combination of columns whosevalues must be unique for all rows in the table.

PRIMARY KEY Uniquely identifies each row of the table.

FOREIGN KEY Establishes and enforces a foreign key relationshipbetween the column and a column of the referencedtable.

CHECK Specifies a condition that must be true.

For more information, seeOracle7 Server SQL Reference, Release 7.3, “CONSTRAINT clause.”

Page 86: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� ��� ��� ������ ����� ��������� ������� �3)

Page 87: OCP - SQL&PL_SQL(Vol2)

�������� ���� �3(

����������� ���������

���������� 5�%��� ��� �������

All constraints are stored in the data dictionary. Constraints are easy to reference ifyou give them a meaningful name. Constraint names must follow the standard objectnaming rules. If you do not name your constraint, Oracle7 generates a name with theformat SYS_Cn, where n is an integer to create a unique constraint name.

�������� �����������

Constraints are usually created at the same time as the table. Constraints may beadded to a table after its creation and also temporarily disabled, and will be coveredin another lesson.

$�'����� �����������

Constraints can be defined at one of two levels.

Constraint Level Description

Column References a single column and is defined within aspecification for the owning column. Can define any typeof integrity constraint.

Table References one or more columns and is defined separatelyfrom the definitions of the columns in the table. Can defineany constraints except NOT NULL.

�&���+7����%������������ �� ��

column [CONSTRAINT constraint_name] constraint_type,

�&���+7�������������� �� ��

column, [CONSTRAINT constraint_name] constraint_type (column, ...),

Page 88: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� ��� ��� ������ ����� ��������� ������� �3,

Page 89: OCP - SQL&PL_SQL(Vol2)

�������� ���� �3

����������� ���������

.� 5� 5��� ����������

The NOT NULL constraint ensures that null values are not allowed in the column.Columns without the NOT NULL constraint can contain null values by default. Thisconstraint can only be specified at the column-constraint level, not at thetable-constraint level.

0+�%2���

This example applies the NOT NULL constraint to the PHONE column, which is avariable character column that holds 15 characters. Because this constraint isunnamed, Oracle7 will create a name for it.

CREATE TABLE friend...phone VARCHAR2(15) NOT NULL, ...

This example applies the NOT NULL constraint to the LAST_NAME column, whichis a variable length character column that holds up to 25 characters. In this case, theconstraint name is FRIEND_LAST_NAME_NN.

CREATE TABLE friend...last_name VARCHAR2(25)

CONSTRAINT friend_last_name_nn NOT NULL, ...

.� �5���0 ����������

A UNIQUE constraint designates a column or combination of columns as a uniquekey. No two rows in the table can have the same value for this key. Null values areallowed if the unique key is based on a single column.

Unique constraints can be defined at the column- or table-constraint level. Acomposite unique key is created by using the table-level definition.

A UNIQUE index is automatically created for a unique key column.

A UNIQUE constraint is not the same as or synonymous to a PRIMARY KEYconstraint.

Page 90: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� ��� ��� ������ ����� ��������� ������� ��4

Page 91: OCP - SQL&PL_SQL(Vol2)

�������� ���� ��3

����������� ���������

.� �-�8*-9 :09 ����������

A PRIMARY KEY constraint creates a primary key for the table. Only one primarykey can be created for a each table. The PRIMARY KEY constraint is a column or setof columns that uniquely identifies each row in a table. This constraint enforcesuniqueness of the column or column combination and ensures that no column that ispart of the primary key can contain a null value.

PRIMARY KEY constraints can be defined at the column-constraint level ortable-constraint level. A composite PRIMARY KEY is created by using thetable-level definition.

A UNIQUE index is automatically created for a PRIMARY KEY column.

.� 1�-0�65 :09 ����������

The FOREIGN KEY, or referential integrity constraint, designates a column orcombination of columns as a foreign key and establishes a relationship between aprimary key or a unique key in the same table or between tables.

A foreign key value must match an existing value in the parent table or be NULL.

FOREIGN KEY constraints can be defined at the column- or table-constraint level. Acomposite foreign key is created by using the table-level definition.

Foreign keys are based upon data values and are purely logical, not physical, pointers.

A foreign key that is part of a primary key cannot be a null value because no part of aprimary key can be NULL.

Continued

Page 92: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� ��� ��� ������ ����� ��������� ������� ���

Page 93: OCP - SQL&PL_SQL(Vol2)

�������� ���� ���

����������� ���������

.� 1�-0�65 :09 ����������7���������

The foreign key is defined in the child table, and the table containing the referencedcolumn is the parent table. The foreign key is defined using a combination of thefollowing keywords:

� FOREIGN KEY is used to define the column in the child table at thetable-constraint level.

� REFERENCES identifies the table and column in the parent table.

� ON DELETE CASCADE indicates that when the row in the parent table isdeleted, the dependent rows in the child table will also be deleted.

Without the ON DELETE CASCADE option, the row in the parent table cannot bedeleted if it is referenced in the child department.

.� �;0�: ����������

The CHECK constraint defines a condition that each row must satisfy. The conditioncan use the same constructs as query conditions, with the following exceptions:

� References to the CURRVAL, NEXTVAL, LEVEL, or ROWNUMpseudocolumns

� Calls to SYSDATE, UID, USER, or USERENV functions

� Queries that refer to other values in other rows

CHECK constraints can be defined at the column-constraint level or table-constraintlevel. The constraint syntax can apply to any column in the table, not only on thecolumn on which it is defined.

Page 94: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� ��� ��� ������ ����� ��������� ������� ��!

Page 95: OCP - SQL&PL_SQL(Vol2)

�������� ���� ��"

�������� � ��� '��% � ��� �������� �.���

Create your tables, based on the table instance chart from the database design, byusing the CREATE TABLE syntax. You might find it useful to create the syntax in ascript file for documentation and ease of use.

������ � ���

1. Create a script file. Start the CREATE TABLE syntax and specify the table name.

2. Map the column names, datatypes, and lengths from the table instance chart to thescript file. Separate each column definition with a comma (,).

3. Map the NOT NULL constraints, except for the PRIMARY KEY constraintcolumns, as column constraint.

4. Map the PRIMARY KEY constraint either as a column constraint if the constraintconstitutes only one column or as a table constraint if the constraint constitutesmore than one column.

5. Map the UNIQUE, CHECK, and FOREIGN KEY constraints.

6. Save and execute the script file.

Page 96: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� ��� ��� ������ ����� ��������� ������� ��)

Page 97: OCP - SQL&PL_SQL(Vol2)

�������� ���� ��(

�������� � ��� '��% � ��� �������� �.��� ���������

0+�%2��

Create the S_DEPT database table based on the table instance chart.

SQL> CREATE TABLE s_dept2 (id NUMBER(7)3 CONSTRAINT s_dept_id_pk PRIMARY KEY,4 name VARCHAR2(25)5 CONSTRAINT s_dept_name_nn NOT NULL,6 region_id NUMBER(7)7 CONSTRAINT s_dept_region_id_fk REFERENCES8 s_region (id),9 CONSTRAINT s_dept_name_region_id_uk UNIQUE10 (name, region_id));

$�'����� �.� �����������

� The S_DEPT_ID_PK column constraint identifies the ID column as the primarykey of the S_DEPT table. This constraint ensures that no two departments in thesame table have the same department number and that no department number isNULL.

� The S_DEPT_NAME_NN column constraint ensures that each departmentnumber in the table has a name.

� The S_DEPT_REGION_ID_FK column constraint ensures that any regionnumber entered in the S_DEPT table has a corresponding value in theS_REGION table. Before defining this constraint, the S_REGION table,including a PRIMARY KEY or UNIQUE constraint on the ID column, must becreated.

� The S_DEPT_NAME_REGION_ID_UK table constraint identifies the NAMEcolumn and the REGION_ID column as a composite unique key to ensure that thesame combination of department name and region number does not appear in thetable more than once.

Page 98: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� ��� ��� ������ ����� ��������� ������� ��,

Page 99: OCP - SQL&PL_SQL(Vol2)

�������� ���� ��

�������� � ��� '��% � ��� �������� �.��� ���������

0+�%2��

Create the S_EMP database table based on the table instance chart. Also, enforce thebusiness constraint that the legal values for commission percent are 10, 12.5, 15,17.5, and 20.

ColumnName ID LAST_NAME USERID

START_DATE

COMMISSION_PCT DEPT_ID

Key Type PK FK

Nulls/Unique

NN, U NN NN, U

FK Table S_DEPT

FKColumn

ID

Datatype NUM CHAR CHAR DATE NUM NUM

Length 7 25 8 6 7

Note: The above table displays a subset of columns found in the S_EMP table.

Constraint Description

S_EMP_ID_PK Establishes the ID column as the table’s primary key.This constraint ensures that a value is entered andthat it is unique.

S_EMP_LAST_NAME_NN Ensures that each row in the table contains a lastname value.

S_EMP_USERID_NN Ensures that there is a value in the USERID column.

S_EMP_USERID_UK Ensures that each value in the USERID column isunique.

S_EMP_DEPT_ID_FK Ensures that the S_EMP table does not containdepartment number not already stored in the S_DEPTtable.

S_EMP_COMMISSION_PCT_CK

Restricts commission percentages.

Page 100: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� ��� ��� ������ ����� ��������� ������� ��4

Page 101: OCP - SQL&PL_SQL(Vol2)

�������� ���� ��3

�������� � ��� '��% -�#� �� *���.�� ���

A second method to create a table is to apply the AS subquery clause to both createthe table and insert rows returned from the subquery.

�&���+

CREATE TABLE table [column(, column...)] AS subquery;

where: table is the name of the table.

column is the name of the column, default value, andintegrity constraint.

subquery is the SELECT statement that defines the set ofrows to be inserted into the new table.

6���������

� The table will be created with the specified column names, and the rows retrievedby the SELECT statement will be inserted into the table.

� The column definition can contain only the column name, default value, andintegrity constraints, not the datatype or referential integrity constraint.

� If column specifications are given, the number of columns must equal the numberof columns in the subquery SELECT list.

� If no column specifications are given, the column names of the table are the sameas the column names in the subquery.

� Only the NOT NULL constraint is inherited from the subquery table tocorresponding columns in the new table.

Page 102: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� ��� ��� ������ ����� ��������� ������� ���

Page 103: OCP - SQL&PL_SQL(Vol2)

�������� ���� ���

���'��%��� ��� ��������

You can verify the existence of a database table and check the column definitions byusing the SQL*Plus DESCRIBE command.

0+�%2��

Confirm the creation of the S_EMP table.

SQL> DESCRIBE s_emp

Name Null? Type----------------------------- -------- -------------ID NOT NULL NUMBER(7)LAST_NAME NOT NULL VARCHAR2(25)FIRST_NAME VARCHAR2(25)USERID NOT NULL VARCHAR2(8)START_DATE DATECOMMENTS VARCHAR2(255)MANAGER_ID NUMBER(7)TITLE VARCHAR2(25)DEPT_ID NUMBER(7)SALARY NUMBER(11,2)COMMISSION_PCT NUMBER(4,2)

Note: Only the NOT NULL constraint is identified in the DESCRIBE command. Allconstraints can be viewed in the data dictionary.

Page 104: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� ��� ��� ������ ����� ��������� ������� ��!

Page 105: OCP - SQL&PL_SQL(Vol2)

�������� ���� ��"

��%%��&

The Oracle7 Server stores data in tables. Create a table by using the SQL CREATETABLE command. You can create a table based on the definition of another table byusing the AS subquery option in the CREATE TABLE command.

��� 1�������

� Table name

� Column names, datatypes, and lengths

� Integrity constraints

UNIQUE indexes are created automatically when you create PRIMARY KEY andUNIQUE constraints.

���������� &2��

� NOT NULL

� UNIQUE

� PRIMARY KEY

� FOREIGN KEY

� CHECK

$0��-��0 ��%%���

Review the structure of a table using the SQL*Plus DESCRIBE command.

Page 106: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� ��� ��� ������ ����� ��������� ������� ��)

Page 107: OCP - SQL&PL_SQL(Vol2)

�������� ���� ��(

�������� � �� ��#

Create new tables containing constraints by using the CREATE TABLE command.Confirm that the new table was added to the database. Create the syntax in thecommand file, then execute the command file to create the table.

�������� ��������

� Creating new tables containing constraints

� Verifying that the tables exist

Page 108: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� ��� ��� ������ ����� ��������� ������� ��,

Page 109: OCP - SQL&PL_SQL(Vol2)

�������� ���� ��

��������

1. Are the following examples syntactically correct? If not, why?

SQL> CREATE TABLE T_30002 (id NUMBER(7),3 name VARCHAR2(25)4 CONSTRAINT table_id_pk PRIMARY KEY(id));

a. Correct/Incorrect

SQL> CREATE TABLE 1995_orders2 (id NUMBER(7),3 customer_id NUMBER(7),4 CONSTRAINT ord_cust_id_nn NOT NULL,5 total NUMBER(11,2),6 filled CHAR(1)7 CONSTRAINT ord_filled_ck CHECK 8 (filled IN (’Y’,’N’)),9 CONSTRAINT ord_id_pk PRIMARY KEY);

b. Correct/Incorrect

Page 110: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� ��� ��� ������ ����� ��������� ������� �!4

�������� ���������

2. Create the DEPARTMENT table based on the table instance chart given below.Enter the syntax in a script p9q2.sql, then execute the script to create the table.Confirm that the table is created. You will add data to the table in another lesson.

Table name: DEPARTMENT

Column Name ID NAME

Key Type PK

Nulls/ Unique NN, U

FK Table

FK Column

Datatype NUMBER CHAR

Length 7 25

3. Create the EMPLOYEE table based on the table instance chart given below. Enterthe syntax in a script p9q3.sql, then execute the script to create the table. Confirmthat the table is created. You will add data to the table in another lesson.

Table name: EMPLOYEE

ColumnName

ID LAST_NAME FIRST_NAME DEPT_ID

Key Type PK FK

Nulls/ Unique NN, U NN NN

FK Table DEPARTMENT

FK Column ID

Datatype NUMBER CHAR CHAR NUMBER

Length 7 25 25 7

Page 111: OCP - SQL&PL_SQL(Vol2)

������ ���� �������

Page 112: OCP - SQL&PL_SQL(Vol2)

��������� � ������� ��� ��� ������ ���� �������� ������ ���

Page 113: OCP - SQL&PL_SQL(Vol2)

������ ���� ������� ���

�� ���!��

The Oracle data dictionary is one of the most important components of theOracle7 Server. It consists of a set of tables and views that provide a read-onlyreference to the database.

At the end of this lesson, you should be able to

� Describe the data dictionary views a user may access.

� Query data from the data dictionary.

Page 114: OCP - SQL&PL_SQL(Vol2)

��������� � ������� ��� ��� ������ ���� �������� ������ ��"

Page 115: OCP - SQL&PL_SQL(Vol2)

������ ���� ������� ��#

�!��!�$

The Oracle data dictionary is one of the most important components of the Oracle7Server. It is created when a database is created. Whenever the database is inoperation, the data dictionary is updated and maintained by the Oracle7 Server. Alldata dictionary tables are owned by the SYS user. The base tables are rarely accesseddirectly because the information in them is not easy to understand. Therefore, userstypically access data dictionary views because the information is presented in aformat that is easy for them to understand.

%����� &�'� �'� ������( ��������

Tables Description

User tables Collection of tables created and maintained by the user,such as S_EMP, that contain user information.

Data dictionary Collection of tables created and maintained by the Oracle7Server, such as USER_OBJECTS, that contain informationabout the database.

)*�+,�� ���� ������� -������

� Names of Oracle7 Server users

� Privileges granted to users

� Database object names (for example, tables, views, and indexes)

� Table constraints

� Auditing information, such as who has accessed or updated specified databaseobjects

���� ������� ����

The data dictionary is a reference for all database users. It is a valuable source ofinformation for end users, application designers, and DBAs. The data dictionary isalso critical for the operation of the Oracle7 Server because the database relies on thedata dictionary to record and verify information about itself.

Page 116: OCP - SQL&PL_SQL(Vol2)

��������� � ������� ��� ��� ������ ���� �������� ������ ��.

Page 117: OCP - SQL&PL_SQL(Vol2)

������ ���� ������� ��(

������� �'� ���� �������

You can query the data dictionary by issuing a SQL SELECT statement. Dependingon your privileges, you can query various views.

/�$ -������

Data dictionary view names reflect their intended use. There are four categories ofviews; each category has a distinct prefix.

Prefix Description

USER_ Contains objects owned by the user. For example, views with this prefixallow the user to display information about tables created by the user andprivileges granted by the user.

ALL_ Accesses objects to which the user has been granted access rights, inaddition to objects owned by the user.

DBA_ Allows users with the DBA privilege to access any object in thedatabase.

V$ Displays database server performance and locking. Initially availableonly to the DBA.

0������ /�$�

Several data dictionary views do not use the prefixes listed above. These includesynonyms for views with long names.

View Name Description

DICTIONARY Lists all data dictionary tables, views, and synonyms.

TABLE_PRIVILEGES Grants on objects for which the user is the grantor,grantee, or owner.

IND Is a synonym for USER_INDEXES.

Page 118: OCP - SQL&PL_SQL(Vol2)

��������� � ������� ��� ��� ������ ���� �������� ������ ��1

Page 119: OCP - SQL&PL_SQL(Vol2)

������ ���� ������� ��2

������� �'� ���� ������� ���������

)*�+,��

The DICTIONARY view lists all data dictionary views accessible to the user with abrief description of the object in a comment column. You can also reference thesynonym for the view, DICT.

SQL> SELECT *2 FROM DICTIONARY;

)*�+,��

You can display the structure of any data dictionary view by using the SQL*PlusDESCRIBE command. Display the structure of USER_OBJECTS.

SQL> DESCRIBE user_objects

Name Null? Type------------------------------ -------- ------------OBJECT_NAME VARCHAR2(128)OBJECT_ID NUMBEROBJECT_TYPE VARCHAR2(13)CREATED DATELAST_DDL_TIME DATETIMESTAMP VARCHAR2(75)STATUS VARCHAR2(7)

)*�+,��

To view a description of each column in data dictionary tables and views, query theDICT_COLUMNS view.

SQL> SELECT column_name, comments2 FROM dict_columns3 WHERE table_name = ’USER_OBJECTS’;

For more information, seeOracle7 Server SQL Language Quick Reference, Release 7.3.

Page 120: OCP - SQL&PL_SQL(Vol2)

��������� � ������� ��� ��� ������ ���� �������� ������ �� �

Page 121: OCP - SQL&PL_SQL(Vol2)

������ ���� ������� ��

������� �'� ���� ������� ���������

)*�+,��

Display the types of objects that the user owns.

SQL> SELECT DISTINCT object_type2 FROM user_objects;

)*�+,��

You can search the data dictionary for a specific topic by querying the COMMENTScolumn in the DICTIONARY view. Find all data dictionary views pertaining to thekeyword Grant.

COLUMN table_name FORMAT A20COLUMN comments FORMAT A30

SQL> SELECT *2 FROM dictionary3 WHERE LOWER(comments) LIKE ’%grant%’;

TABLE_NAME COMMENTS-------------------- ------------------------------ALL_COL_PRIVS Grants on columns for which th e user is the grantor, grantee , owner, or an enabled role or PUBLIC i s the grantee

ALL_COL_PRIVS_MADE Grants on columns for which th e user is owner or grantor

ALL_COL_PRIVS_RECD Grants on columns for which th e user, PUBLIC or enabled role is the grantee...20 rows selected.

Page 122: OCP - SQL&PL_SQL(Vol2)

��������� � ������� ��� ��� ������ ���� �������� ������ �� �

Page 123: OCP - SQL&PL_SQL(Vol2)

������ ���� ������� �� �

-'��3�� -�������� � � %����

After creating a table, you can confirm its existence by issuing a DESCRIBEcommand. The only constraint you can verify is the NOT NULL constraint. To viewall constraints on your table, you can check the USER_CONSTRAINTS table.

)*�+,��

Confirm the constraints on the S_EMP table.

SQL> SELECT constraint_name, constraint_type,2 search_condition, r_constraint_name3 FROM user_constraints4 WHERE table_name = ’S_EMP’;

CONSTRAINT_NAME C SEARCH_CONDITION R_CONSTRAINT_NA----------------------- - --------------------- ---------------S_EMP_MANAGER_ID_FK R S_EMP_ID_PKS_EMP_LAST_NAME_NN C LAST_NAME IS NOT NULLS_EMP_USERID_NN C USERID IS NOT NULLS_EMP_ID_PK PS_EMP_USERID_UK US_EMP_COMMISSION_PCT_CK C commission_pct IN (10, 12 .5, 15, 17.5, 20)S_EMP_DEPT_ID_FK R S_DEPT_ID_PKS_EMP_TITLE_FK R S_TITLE_TITLE_PK

8 rows selected.

Note: The above display has been formatted to fit the page.

Page 124: OCP - SQL&PL_SQL(Vol2)

��������� � ������� ��� ��� ������ ���� �������� ������ �� "

Page 125: OCP - SQL&PL_SQL(Vol2)

������ ���� ������� �� #

-'��3�� -�������� � � %���� ���������

View the names of the columns involved in constraints by querying theUSER_CONS_COLUMNS data dictionary view. This view is especially useful forconstraints that use the system-assigned name.

)*�+,��

Display the column constraint information in the data dictionary for the S_EMP table.

SQL> SELECT constraint_name, column_name2 FROM user_cons_columns3 WHERE table_name = ’S_EMP’;

CONSTRAINT_NAME COLUMN_NAME----------------------- -----------------------S_EMP_COMMISSION_PCT_CK COMMISSION_PCTS_EMP_DEPT_ID_FK DEPT_IDS_EMP_ID_PK IDS_EMP_LAST_NAME_NN LAST_NAMES_EMP_MANAGER_ID_FK MANAGER_IDS_EMP_TITLE_FK TITLES_EMP_USERID_NN USERIDS_EMP_USERID_UK USERID

8 rows selected.

Page 126: OCP - SQL&PL_SQL(Vol2)

��������� � ������� ��� ��� ������ ���� �������� ������ �� .

Page 127: OCP - SQL&PL_SQL(Vol2)

������ ���� ������� �� (

��++���

The data dictionary is a set of tables that the user can query through views. The datadictionary holds all the data about the database. Write a SELECT statement to displaythe contents of the data dictionary views.

4��5������ 0������� ���� ������� /�$�

� DICTIONARY

� DICT_COLUMNS

� USER_OBJECTS

� USER_CONSTRAINTS

� USER_CONS_COLUMNS

Page 128: OCP - SQL&PL_SQL(Vol2)

��������� � ������� ��� ��� ������ ���� �������� ������ �� 1

Page 129: OCP - SQL&PL_SQL(Vol2)

������ ���� ������� �� 2

������� �!��!�$

In this practice, you will access the data dictionary views to verify information aboutyour tables.

������� -������

� Querying the data dictionary to view table information

� Viewing constraint information from the data dictionary

Page 130: OCP - SQL&PL_SQL(Vol2)

��������� � ������� ��� ��� ������ ���� �������� ������ ����

Page 131: OCP - SQL&PL_SQL(Vol2)

������ ���� ������� ���

������� �

1. Select all the views from the data dictionary pertaining to Table. You can adjustthe column formats by using the SQL*Plus COLUMN command.

If you want to interrupt your query, you can cancel it by pressing [CTRL]+[C] onyour PC keyboard.

2. If a query is very lengthy, what SQL*Plus command can you set before youexecute the query to show only one page at a time?

Note: If you did not complete Practice 9, Exercise 2 and Exercise 3, you can invokescripts p9q2.sql and p9q3.sql to create DEPARTMENT table andEMPLOYEE table respectively.

3. Query the USER_OBJECTS data dictionary to see information about the tablesyou created in Practice 9, DEPARTMENT and EMPLOYEE tables.

4. Create a script to execute a generic query to confirm the constraints for the tablesyou have created. You can use a substitution parameter for the table name. Savethe query as p10q4.sql. Execute the script to confirm the constraints for the tablesyou created in Practice 9, DEPARTMENT and EMPLOYEE tables.

Page 132: OCP - SQL&PL_SQL(Vol2)

��������� � ������� ��� ��� ������ ���� �������� ������ ����

Page 133: OCP - SQL&PL_SQL(Vol2)

����������� ���

��

Page 134: OCP - SQL&PL_SQL(Vol2)

��� �������� �� � ����� ��� ��� ������ ���� � ����� � ������ ����

Page 135: OCP - SQL&PL_SQL(Vol2)

����������� ��� ����

�� ����!��

Once your tables have been created, you will need to add new rows, makechanges to rows in a table, or delete rows by using data manipulationcommands. This lesson covers using SQL commands to make changes to data. Anumber of these data manipulation commands make up a transaction, whichyou may either save or delete using transaction controls.

At the end of this lesson, you should be able to

� Insert new rows into a table.

� Update existing rows in a table.

� Delete rows from a table.

� Explain transaction controls and their importance.

Page 136: OCP - SQL&PL_SQL(Vol2)

��� �������� �� � ����� ��� ��� ������ ���� � ����� � ������ ���"

Page 137: OCP - SQL&PL_SQL(Vol2)

����������� ��� ���#

�!� !��$

Data manipulation language (DML) is a core part of SQL. When you want to add,update, or delete data in the database, you execute a DML statement. A collection ofDML statements that have not yet been made permanent is called a transaction, or alogical unit of work.

Page 138: OCP - SQL&PL_SQL(Vol2)

��� �������� �� � ����� ��� ��� ������ ���� � ����� � ������ ���%

Page 139: OCP - SQL&PL_SQL(Vol2)

����������� ��� ���&

'���� � (�$ )�$ �� � *����

You can add new rows to a table by issuing the INSERT command.

�+���,

INSERT INTO table [(column [, column...])]VALUES (value [, value...]);

where: table is the table name.

column is the name of the column in the table topopulate.

value is the corresponding value for the column.

Note: This command with the VALUES clause adds only one row at a time to atable.

���� ��� � )�$ ���� � *����

Because you can insert a new row that contains values for each column, therefore thecolumn list is not required in the INSERT clause. However, the values must be listedaccording to the default order of the columns in the table.

SQL> DESCRIBE s_dept

Name Null? Type------------------------- -------- --------------ID NOT NULL NUMBER(7)NAME NOT NULL VARCHAR2(25)REGION_ID NUMBER(7)

SQL> INSERT INTO s_dept2 VALUES (11, ’Finance’, 2);

1 row created.

For clarity, use the column list in the INSERT clause.

Enclose character and date values within single quotation marks; do not enclosenumeric values within single quotation marks.

Page 140: OCP - SQL&PL_SQL(Vol2)

��� �������� �� � ����� ��� ��� ������ ���� � ����� � ������ ���-

Page 141: OCP - SQL&PL_SQL(Vol2)

����������� ��� ���.

'���� � (�$ )�$ �� � *���� ���������

���� ��� (��� /�����

Method Description

Implicit Omit the column from the column list.

Explicit Specify the NULL keyword in the VALUES list.

Specify the empty string (‘’) in the VALUES list; forcharacter strings and dates only.

0,�1���

Enter a new department omitting the region number. Because the region number isnot listed in the INSERT clause, a null value is entered implicitly for the regionnumber in this row.

SQL> INSERT INTO s_dept (id, name)2 VALUES (12, ’MIS’);

1 row created.

0,�1���

Alternatively, you can enter a null value into a row explicitly by using the NULLkeyword for the value.

SQL> INSERT INTO s_dept2 VALUES (13, ’Administration’, NULL);

1 row created.

Be sure that the targeted column allows null values by verifying the Null? status fromthe SQL*Plus DESCRIBE command.

Page 142: OCP - SQL&PL_SQL(Vol2)

��� �������� �� � ����� ��� ��� ������ ���� � ����� � ������ ����2

Page 143: OCP - SQL&PL_SQL(Vol2)

����������� ��� �����

'���� � (�$ )�$ �� � *���� ���������

���� ��� ������� /����� �+ ���� ��� 3��������

You can use pseudocolumns to enter special values in your table. Specify USERID toenter the current user name. SYSDATE enters the current date and time.

0,�1���

Record information for the student in the S_EMP table. Supply the current user namefor the USERID column and the current date and time in the START_DATE column.

SQL> INSERT INTO s_emp (id, first_name,2 last_name, userid, salary, start_date)3 VALUES (26, ’Donna’,4 ’Smith’, USER, NULL, SYSDATE);

1 row created.

4��5� 1�� '�������� �� �6� *����

To verify that the rows were inserted into the table, you can write a SELECTstatement.

0,�1���

SQL> SELECT id, last_name, first_name,2 userid, start_date, salary3 FROM s_emp4 WHERE id = 26;

ID LAST_NAME FIRST_NAME USERID START_DAT-- --------- ---------- -------- --------- SALARY------26 Smith Donna SFCL26 01-JAN-96

Page 144: OCP - SQL&PL_SQL(Vol2)

��� �������� �� � ����� ��� ��� ������ ���� � ����� � ������ �����

Page 145: OCP - SQL&PL_SQL(Vol2)

����������� ��� �����

'���� � (�$ )�$ �� � *���� ���������

���� ��� �����5�� ��� ��� *�1� /�����

When inserting a date value, the format DD-MON-YY is usually used. With thisformat, recall that the century defaults to the current century. Because the date alsocontains time information, the default time is midnight (00:00:00).

If a date is required to be entered in another century and a specific time is alsorequired, use the TO_DATE function.

0,�1���

Record information for the student in the S_EMP table. Supply the current user namefor the USERID column. Set the START_DATE to be January 1, 1996, 8:00 A.M.

SQL> INSERT INTO s_emp (id, first_name,2 last_name, userid, salary, start_date)3 VALUES (26, ’Donna’,4 ’Smith’, USER, NULL,5 TO_DATE(’01-JAN-96 08:00’,6 ’DD-MON-YY HH:MI’));

1 row created.

If the RR format is set, the century may not be the current one.

Page 146: OCP - SQL&PL_SQL(Vol2)

��� �������� �� � ����� ��� ��� ������ ���� � ����� � ������ ����"

Page 147: OCP - SQL&PL_SQL(Vol2)

����������� ��� ����#

'���� � (�$ )�$ �� � *���� ���������

���� ��� /����� �+ ���� ������������ /� ������

You can produce an INSERT command that allows the user to add valuesinteractively by using SQL*Plus substitution variables.

0,�1���

Record information for a department in the S_DEPT table. Prompt the user for thedepartment number, department name, and region number.

SQL> INSERT INTO s_dept (id, name,2 region_id)3 VALUES (&department_id, ‘&department_name’, 4 &region_id);

Enter value for department_id: 61Enter value for department_name: AccountingEnter value for region_id: 2

1 row created.

For date and character values, the ampersand and the variable name are enclosed insingle quotation marks.

Page 148: OCP - SQL&PL_SQL(Vol2)

��� �������� �� � ����� ��� ��� ������ ���� � ����� � ������ ����%

Page 149: OCP - SQL&PL_SQL(Vol2)

����������� ��� ����&

'���� � (�$ )�$ �� � *���� ���������

4 ����� � �� ��� �� ���������� ���

You can save your command with substitution variables to a file and execute the file.Each time you execute the command, it will prompt you for new values. Customizethe prompts by using the SQL*Plus ACCEPT command.

0,�1���

Record information for a department in the S_DEPT table. Prompt the user for thedepartment number, department name, and region number. Customize the promptmessages.

ACCEPT department_id PROMPT ’Pleaseenter the department number:’

ACCEPT department_name PROMPT ’Please enter the department name:’

ACCEPT region_id PROMPT ’Pleaseenter the region number:’

INSERT INTO s_dept (id, name, region_id)VALUES (&department_id, ’&department_name’,

&region_id);

Please enter the department number: 61Please enter the department name: AccountingPlease enter the region number: 2

1 row created.

Do not prefix the SQL*Plus substitution parameter with the ampersand (&) whenreferencing it in the ACCEPT command. Use a dash (-) to continue a SQL*Pluscommand on the next line.

Page 150: OCP - SQL&PL_SQL(Vol2)

��� �������� �� � ����� ��� ��� ������ ���� � ����� � ������ ����-

Page 151: OCP - SQL&PL_SQL(Vol2)

����������� ��� ����.

4��+�� )�$� 5 �1 '���6� *����

You can use the INSERT statement to add rows to a table where the values arederived from existing tables. In place of the VALUES clause, you use a subquery.

�+���,

INSERT INTO table [column (, column)]subquery;

where: table is the table name.

column is the name of the column in the table topopulate.

subquery is the subquery that returns rows into the table.

For more information, seeOracle7 Server SQL Reference, Release 7.3, “SELECT,” Subqueries section.

0,�1���

Copy selected rows from the S_EMP table into the HISTORY table.

SQL> INSERT INTO HISTORY (id, last_name, salary,2 title, start_date)3 SELECT id, last_name, salary,4 title, start_date5 FROM s_emp6 WHERE start_date < ’01-JAN-94’;

10 rows created.

The number of columns in the column list of the INSERT clause must match thenumber of values in the subquery.

Page 152: OCP - SQL&PL_SQL(Vol2)

��� �������� �� � ����� ��� ��� ������ ���� � ����� � ������ ����2

Page 153: OCP - SQL&PL_SQL(Vol2)

����������� ��� �����

������� )�$�

You can modify existing rows by using the UPDATE command.

�+���,

UPDATE tableSET column = value [, column = value...][WHERE condition];

where: table is the table name.

column is the name of the column in the table topopulate.

value is the corresponding value or subquery for thecolumn.

condition identifies the rows to be updated and iscomposed of column names, expressions,constants, subqueries, and comparisonoperators.

Confirm the update operation by querying the table to display the updated rows.

For more information, seeOracle7 Server SQL Reference, Release 7.3, “UPDATE.”

Page 154: OCP - SQL&PL_SQL(Vol2)

��� �������� �� � ����� ��� ��� ������ ���� � ����� � ������ �����

Page 155: OCP - SQL&PL_SQL(Vol2)

����������� ��� �����

������� )�$� ���������

0,�1���

Transfer employee number 2 to department 10. Transfer employee number 1 todepartment 32 and change the employee’s salary to 2550.

SQL> UPDATE s_emp2 SET dept_id = 103 WHERE id = 2;

1 row updated.

SQL> UPDATE s_emp2 SET dept_id = 32, salary = 25503 WHERE id = 1;

1 row updated.

Confirm both data changes.

SQL> SELECT id, last_name, salary, dept_id2 FROM s_emp3 WHERE id IN (1,2);

ID LAST_NAME SALARY DEPT_ID------- --------- ------ ------- 2 Ngao 1450 10 1 Velasquez 2550 32

Page 156: OCP - SQL&PL_SQL(Vol2)

��� �������� �� � ����� ��� ��� ������ ���� � ����� � ������ ����"

Page 157: OCP - SQL&PL_SQL(Vol2)

����������� ��� ����#

������� )�$� ���������

If you do not include a WHERE clause in your UPDATE command, all rows in thetable will be updated.

0,�1���

Give a commission of 10 percent to every employee in the company. Confirm thechanges.

SQL> UPDATE s_emp2 SET commission_pct = 10;

25 rows updated.

SQL> SELECT id, commission_pct2 FROM s_emp;

ID COMMISSION_PCT------- -------------- 1 10 2 10 3 10 4 10 5 10 6 10...25 rows selected.

Page 158: OCP - SQL&PL_SQL(Vol2)

��� �������� �� � ����� ��� ��� ������ ���� � ����� � ������ ����%

Page 159: OCP - SQL&PL_SQL(Vol2)

����������� ��� ����&

������� )�$� ���������

���� ��+ 4���� ���� 0 �

If you attempt to update a record with a value that is tied to an integrity constraint,you will experience an error.

0,�1���

If the value you specify does not exist in the parent table, then you receive the “parentkey” violation ORA-02291.

SQL> UPDATE s_emp2 SET dept_id = 603 WHERE dept_id = 10;

update s_emp *ERROR at line 1:ORA-02291: integrity constraint (USR.S_EMP_DEPT_ID_FK)violated - parent key not found

Page 160: OCP - SQL&PL_SQL(Vol2)

��� �������� �� � ����� ��� ��� ������ ���� � ����� � ������ ����-

Page 161: OCP - SQL&PL_SQL(Vol2)

����������� ��� ����.

������ )�$�

You can remove existing rows by using the DELETE command.

�+���,

DELETE [FROM] table[WHERE condition];

where: table is the table name.

condition identifies the rows to be deleted and iscomposed of column names, expressions,constants, subqueries, and comparisonoperators.

Confirm the delete operation by displaying the deleted rows by using the SELECTcommand.

If the WHERE clause is omitted, all rows in the table will be deleted.

0,�1���

Remove all information about employees who started after January 1, 1996.

SQL> DELETE FROM s_emp2 WHERE start_date >3 TO_DATE(’01.01.1996’,’DD.MM.YYYY’);

1 row deleted.

For more information, seeOracle7 Server SQL Reference, Release 7.3, “DELETE.”

Page 162: OCP - SQL&PL_SQL(Vol2)

��� �������� �� � ����� ��� ��� ������ ���� � ����� � ������ ����2

Page 163: OCP - SQL&PL_SQL(Vol2)

����������� ��� �����

������ )�$� ���������

If you do not include a WHERE clause in your DELETE command, all rows in thetable will be deleted.

0,�1���

Eliminate all data from the TEST table.

SQL> DELETE FROM test;

25,000 rows deleted.

Confirm the deletions.

SQL> SELECT *2 FROM test;

no rows selected

Page 164: OCP - SQL&PL_SQL(Vol2)

��� �������� �� � ����� ��� ��� ������ ���� � ����� � ������ �����

Page 165: OCP - SQL&PL_SQL(Vol2)

����������� ��� �����

������ )�$� ���������

���� ��+ 4���� ���� 0 �

If you attempt to delete a record with a value that is tied to an integrity constraint, youwill experience an error.

0,�1���

Attempt to delete all departments in region number 1.

SQL> DELETE s_dept2 WHERE region_id = 1;

delete from s_region * ERROR at line 1:ORA-02292: integrity constraint (USR.S_EMP_DEPT_ID_FK) violated - child record found

If the parent record you attempt to delete has child records, then you receive the“child record found” violation ORA-02292.

Page 166: OCP - SQL&PL_SQL(Vol2)

��� �������� �� � ����� ��� ��� ������ ���� � ����� � ������ ����"

Page 167: OCP - SQL&PL_SQL(Vol2)

����������� ��� ����#

* ��������� � �������

The Oracle7 Server ensures data consistency based on transactions. Transactions giveyou more flexibility and control when changing data, and assure data consistency inthe event of user process failure or system failure.

Transactions consist of DML commands that make up one consistent change to thedata. For example, a transfer of funds between two accounts should include the debitto one account and the credit to another account in the same amount. Both actionsshould either fail or succeed together. The credit should not be committed without thedebit.

* ��������� *+���

Type Description

Data manipulation (DML) Consist of any number of DML statements that theOracle7 Server treats as a single entity or a logical unitof work.

Data definition (DDL) Consist of only one DDL statement.

Data control (DCL) Consists of only one DCL statement.

76�� ��� � * ��������� ��� � ��� 0��8

A transaction begins when the first executable SQL command is encountered andterminates when one of the following occurs:

� A COMMIT or ROLLBACK command is issued.

� A DDL command, such as CREATE, or DCL command is issued.

� Certain errors are detected, such as deadlocks.

� The user exits SQL*Plus.

� A machine fails or the system crashes.

After one transaction ends, the next executable SQL statement will automatically startthe next transaction.

A DDL command or a DCL command is automatically committed and thereforeimplicitly ends a transaction.

Page 168: OCP - SQL&PL_SQL(Vol2)

��� �������� �� � ����� ��� ��� ������ ���� � ����� � ������ ����%

Page 169: OCP - SQL&PL_SQL(Vol2)

����������� ��� ����&

* ��������� � ������� ���������

0,������ * ��������� 4��� �� �����1����

Control the logic of transactions by using the COMMIT, SAVEPOINT, andROLLBACK statements.

Command Description

COMMIT Ends the current transaction by making all pendingdata changes permanent.

SAVEPOINT name Marks a savepoint within the current transaction.

ROLLBACK [TOSAVEPOINT name]

Ends the current transaction by discarding all pendingdata changes.

�1������ * ��������� � �������

Status Circumstance

Automatic commit DDL command or DCL command is issued.

Normal exit from SQL*Plus, without explicitly issuingCOMMIT or ROLLBACK.

Automatic rollback Abnormal termination of SQL*Plus, or system failure.

Page 170: OCP - SQL&PL_SQL(Vol2)

��� �������� �� � ����� ��� ��� ������ ���� � ����� � ������ ����-

Page 171: OCP - SQL&PL_SQL(Vol2)

����������� ��� ����.

4�11����� 46����

Every data change made during the transaction is temporary until the transaction iscommitted.

����� �5 �6� ��� ��5� � 4����* � )����'49

� Data manipulation operations primarily affect the database buffer; therefore, theprevious state of the data can be recovered.

� The current user can review the results of the data manipulation operations byquerying the tables.

� Other user cannot view the results of the data manipulation operations for thecurrent user. Oracle7 institutes read consistency to ensure that each user sees dataas it existed at the last commit.

� The affected rows are locked; other users cannot change the data within theaffected rows.

Page 172: OCP - SQL&PL_SQL(Vol2)

��� �������� �� � ����� ��� ��� ������ ���� � ����� � ������ ���"2

Page 173: OCP - SQL&PL_SQL(Vol2)

����������� ��� ���"�

4�11����� 46���� ���������

Make all pending changes permanent by using the COMMIT command. Following aCOMMIT

� Data changes are written to the database.

� The previous state of the data is permanently lost.

� All users can view the results of the transaction.

� The locks on the affected rows are released; the rows are now available for otherusers to perform new data changes.

� All savepoints are erased.

0,�1���

Create a new Education department with at least one employee. Make the data changepermanent.

SQL> INSERT INTO s_dept (id, name, region_id)2 VALUES (54, ’Education’, 1);

1 row created.

SQL> UPDATE s_emp2 SET dept_id = 543 WHERE id = 2;

1 row updated.

SQL> COMMIT;

Commit complete.

Page 174: OCP - SQL&PL_SQL(Vol2)

��� �������� �� � ����� ��� ��� ������ ���� � ����� � ������ ���"�

Page 175: OCP - SQL&PL_SQL(Vol2)

����������� ��� ���"�

)����� ���: 46����

Discard all pending changes by using the ROLLBACK statement. Following aROLLBACK

� Data changes are undone.

� The previous state of the data is restored.

� The locks on the affected rows are released; the rows are now available for otherusers to perform new data changes.

0,�1���

While attempting to remove a record from the TEST table, accidentally empty thetable. Correct the mistake, then reissue the proper command, and make the datachange permanent.

SQL> DELETE FROM test;

25,000 rows deleted.

SQL> ROLLBACK;

Rollback complete.

SQL> DELETE FROM test2 WHERE id = 100;

1 row deleted.

SQL> SELECT *2 FROM test3 WHERE id = 100;

no rows selected

SQL> COMMIT;

Commit complete.

Page 176: OCP - SQL&PL_SQL(Vol2)

��� �������� �� � ����� ��� ��� ������ ���� � ����� � ������ ���""

Page 177: OCP - SQL&PL_SQL(Vol2)

����������� ��� ���"#

)����� ���: 46���� �� � ��!������

You can create a marker within the current transaction by using the SAVEPOINTcommand. The transaction therefore can be divided into smaller sections. You canthen discard pending changes up to that marker by using the ROLLBACK TOSAVEPOINT statement.

0,�1���

Update the salary for all Stock Clerks by 10 percent. Create a savepoint namedUPDATE_DONE.

SQL> UPDATE s_emp2 SET salary = salary * 1.13 WHERE title = ’Stock Clerk’;

10 rows updated.

SQL> SAVEPOINT update_done;

Savepoint created.

SQL> INSERT INTO s_region (id, name)2 VALUES (8, ’Central’)

1 row inserted.

SQL> SELECT *2 FROM s_region3 WHERE id = 8

ID NAME------- -------------------- 8 Central

SQL> ROLLBACK TO update_done;

Rollback complete.

SQL> SELECT *2 FROM s_region3 WHERE id = 8

no rows selected

If you create a second savepoint with the same name as an earlier savepoint, theearlier savepoint is deleted.

Page 178: OCP - SQL&PL_SQL(Vol2)

��� �������� �� � ����� ��� ��� ������ ���� � ����� � ������ ���"%

Page 179: OCP - SQL&PL_SQL(Vol2)

����������� ��� ���"&

�����1��� ��!�� )������:

Part of a transaction may be discarded by an implicit rollback if a statement executionerror is detected. If a single DML statement fails during execution of a transaction, itseffect is undone by a statement-level rollback, but the changes made by the previousDML statements in the transaction will not be discarded. They can be committed orrolled back explicitly by the user.

Oracle issues an implicit COMMIT before and after any Data Definition Languagestatement. So, even if your DDL statement does not execute successfully, you cannotrollback the previous statement because the server issued a commit.

Terminate your transactions explicitly by executing a COMMIT or ROLLBACKstatement.

Page 180: OCP - SQL&PL_SQL(Vol2)

��� �������� �� � ����� ��� ��� ������ ���� � ����� � ������ ���"-

Page 181: OCP - SQL&PL_SQL(Vol2)

����������� ��� ���".

��11� +

Manipulate data in the Oracle database by using the INSERT, UPDATE, andDELETE statements. Control data changes by using the COMMIT, SAVEPOINT, andROLLBACK commands.

��� ������������ ��� * ��������� 4��� �� 4�11����

Command Description

INSERT Adds a new row to the table.

UPDATE Modifies existing rows in the table.

DELETE Removes existing rows from the table.

COMMIT Makes all pending data changes permanent.

SAVEPOINT Allows a rollback to that savepoint marker.

ROLLBACK Discards all pending data changes.

Page 182: OCP - SQL&PL_SQL(Vol2)

��� �������� �� � ����� ��� ��� ������ ���� � ����� � ������ ���#2

Page 183: OCP - SQL&PL_SQL(Vol2)

����������� ��� ���#�

� ������ �!� !��$

This practice builds on a prior lesson with the DEPARTMENT and EMPLOYEEtables. In this practice, you will add rows to the tables, update, and delete data fromthe tables, and control your transactions.

� ������ 4�������

� Inserting rows into the tables

� Updating and deleting rows in the tables

� Controlling transactions

Page 184: OCP - SQL&PL_SQL(Vol2)

��� �������� �� � ����� ��� ��� ������ ���� � ����� � ������ ���#�

Page 185: OCP - SQL&PL_SQL(Vol2)

����������� ��� ���#�

� ������ ��

1. Insert data into the DEPARTMENT and EMPLOYEE tables.

Note: If you did not complete Practice 9, Exercise 2 and Exercise 3, you can invokescripts p9q2.sql and p9q3.sql to create DEPARTMENT table andEMPLOYEE table respectively.

a. Describe the DEPARTMENT and EMPLOYEE tables to identify the columnnames.

b. View the constraints on each table to identify the primary key and any otherconstraints. Execute the script p10q4.sql, which is a generic query to confirmconstraints.

c. Add a row of data to the DEPARTMENT table. The department number is 10and the department name is Finance. Do not list the columns in the INSERTclause.

d. Add two rows of data to the EMPLOYEE table. Write a script namedp11q1d.sql that prompts you for each column value. The first employee isDonna Smith in department number 10, and her employee number is 200. Thesecond employee is Albert Jones in department number 54, and his employeenumber is 201. What was the result and why?

e. Insert into the DEPARTMENT table department number 10 and departmentname of Marketing. What was the result and why?

f. Confirm your additions to the tables.

g. Write a script named p11q1g.sql to add the following rows to theDEPARTMENT table: Marketing as number 37; Sales as number 54; andPersonnel as number 75.

h. Execute the p11q1d.sql script to add the following rows to the EMPLOYEEtable: Albert Jones in department number 54, and employee number 201;Harry Chin in department 75 and employee number 202; Rey Guiliani indepartment 37 and employee number 203.

i. Confirm your additions to the tables.

j. Make the data additions permanent.

Page 186: OCP - SQL&PL_SQL(Vol2)

��� �������� �� � ����� ��� ��� ������ ���� � ����� � ������ ���#"

� ������ �� ���������

2. Update and delete data in the DEPARTMENT and EMPLOYEE tables.

a. Change the name of the Personnel department to Human Resources.

b. Change the last name of employee 202 to Korsgaard.

c. Verify your changes to the tables.

d. Attempt to delete department 54. What was the result and why?

e. Delete Albert Jones from the EMPLOYEE table.

f. Attempt to delete department 54 from the DEPARTMENT table again. Whatwas the result and why?

g. Verify the changes to your tables.

h. Commit all pending changes.

3. Control data transactions to the DEPARTMENT and EMPLOYEE tables.

a. Execute the p11q1g.sql script to reinstate the Sales department as departmentnumber 54.

b. Verify your addition.

c. Mark a transaction processing savepoint.

d. Empty the entire EMPLOYEE table.

e. Verify that the EMPLOYEE table is empty.

f. Discard the most recent DELETE operation without discarding the mostrecent INSERT operation.

g. Verify that the new row in the DEPARTMENT table is still intact. Verify thatthe EMPLOYEE table has all three rows.

h. Make the data addition permanent.

Page 187: OCP - SQL&PL_SQL(Vol2)

�������� ���� � ����������

��

Page 188: OCP - SQL&PL_SQL(Vol2)

����� ������ �� ������ ��� � ������ ����� ����� ��� ���� ������

Page 189: OCP - SQL&PL_SQL(Vol2)

�������� ���� � ���������� ����

�� ����!��

After you create your tables, you may need to change the table structuresbecause you omitted a column, your column definition needs to be changed, oryou want to enable or disable constraints. This lesson will demonstrate how youcan amend table structures as well as add and remove constraints.

At the end of this lesson, you should be able to

� Add and modify table columns.

� Add, enable, disable, or remove constraints.

� Drop a table.

� Remove all rows leaving the table definition intact.

� Change object names.

� Add comments to objects and view comments from the data dictionary.

Page 190: OCP - SQL&PL_SQL(Vol2)

����� ������ �� ������ ��� � ������ ����� ����� ��� ���� �����"

Page 191: OCP - SQL&PL_SQL(Vol2)

�������� ���� � ���������� ���#

�!��!��$

Once you have created your tables, you can modify their structure by using theALTER TABLE command. Add columns, modify the column length, add or dropconstraints, and enable or disable constraints by using this command.

If you want to remove a table, both the rows and the data structure of a table, invokethe DROP TABLE command. Other commands that affect tables that are covered inthis lesson are

� RENAME, to change a database object name.

� TRUNCATE, to remove all rows from a table.

� COMMENT, to add a comment about a database object to the data dictionary.

All of these commands are data definition commands (DDL). When you issue thesestatements, an automatic commit occurs. You cannot roll back DDL commands.Therefore, be very careful when you execute them.

Page 192: OCP - SQL&PL_SQL(Vol2)

����� ������ �� ������ ��� � ������ ����� ����� ��� ���� �����%

Page 193: OCP - SQL&PL_SQL(Vol2)

�������� ���� � ���������� ���&

� ��� ����'�

You can add columns to a table by using the ALTER TABLE command with theADD clause.

�(��)

ALTER TABLE tableADD (column datatype [DEFAULT expr][NOT NULL]

[, column datatype]...);

where: table is the name of the table.

column is the name of the new column.

datatype is the datatype and length of the new column.

DEFAULT expr specifies the default value for a new column.

NOT NULL adds a NOT NULL constraint to the newcolumn.

*�� ������

� You can add or modify columns, but you cannot drop them from a table.

� You cannot specify where the column is to appear. The new column becomes thelast column.

Page 194: OCP - SQL&PL_SQL(Vol2)

����� ������ �� ������ ��� � ������ ����� ����� ��� ���� �����+

Page 195: OCP - SQL&PL_SQL(Vol2)

�������� ���� � ���������� ���,

-� �.(��� ����'�

You can modify a column definition by using the ALTER TABLE command with theMODIFY clause. Column modification can include changes to a column’s datatype,size, default value, and NOT NULL column constraint.

�(��)

ALTER TABLE tableMODIFY (column datatype [DEFAULT expr][NOT NULL]

[, column datatype]...);

where: table is the name of the table.

column is the name of the column.

datatype is the datatype and length of the column.

DEFAULT expr specifies the default value for a new column.

NOT NULL adds a NOT NULL constraint to the newcolumn.

*�� ������

� Increase the width or precision of a numeric column.

� Decrease the width of a column if the column contains only null values or if thetable has no rows.

� Change the datatype if the column contains null values.

� Convert a CHAR column to the VARCHAR2 datatype or convert a VARCHAR2column to the CHAR datatype if the column contains null values or if you do notchange the size.

� A change to the default value of a column only affects subsequent insertions tothe table.

� Add a NOT NULL constraint only if there are no null values in the column.

Page 196: OCP - SQL&PL_SQL(Vol2)

����� ������ �� ������ ��� � ������ ����� ����� ��� ���� ������/

Page 197: OCP - SQL&PL_SQL(Vol2)

�������� ���� � ���������� �����

� ��� � 0��11��� ���������

You can add or drop constraints for existing tables by using the ALTER TABLEcommand with the ADD or DROP clause.

�(��)

ALTER TABLE tableADD [CONSTRAINT constraint] type (column);

where: table is the name of the table.

constraint is the name of the constraint.

type is the constraint type.

column is the name of the column affected by theconstraint.

The constraint name syntax is optional, although recommended. If you do not nameyour constraints, the system will generate constraint names.

*�� ������

� You can add, drop, enable, or disable a constraint, but you cannot modify itsstructure.

� You can add a NOT NULL constraint to an existing column by using theMODIFY clause of the ALTER TABLE command.

Page 198: OCP - SQL&PL_SQL(Vol2)

����� ������ �� ������ ��� � ������ ����� ����� ��� ���� �������

Page 199: OCP - SQL&PL_SQL(Vol2)

�������� ���� � ���������� �����

� ��� � 0��11��� ��������� ���������

To drop a constraint, you can identify the constraint name from theUSER_CONSTRAINTS and USER_CONS_COLUMNS data dictionary views.Then, use the ALTER TABLE command with the DROP clause. The CASCADEoption of the DROP clause causes any dependent constraints also to be dropped.

�(��)

ALTER TABLE tableDROP PRIMARY KEY | UNIQUE (column) |

CONSTRAINT constraint [CASCADE];

where: table is the name of the table.

column is the name of the column affected by theconstraint.

constraint is the name of the constraint.

When you drop an integrity constraint, that constraint is no longer enforced by theOracle7 Server and is no longer available in the data dictionary.

Page 200: OCP - SQL&PL_SQL(Vol2)

����� ������ �� ������ ��� � ������ ����� ����� ��� ���� ������"

Page 201: OCP - SQL&PL_SQL(Vol2)

�������� ���� � ���������� ����#

0������� � 2������ ���������

You can enable or disable constraints without dropping them or recreating them byusing the ALTER TABLE command with the ENABLE or DISABLE clause.

�(��)

ALTER TABLE tableDISABLE | ENABLE CONSTRAINT constraint [CASCADE];

*�� ������

� If you enable a constraint, that constraint applies to all the data in the table. Allthe data in the table must fit the constraint.

� If you enable a UNIQUE or PRIMARY KEY constraint, a UNIQUE orPRIMARY KEY index is automatically created.

� You can use the ENABLE and DISABLE clauses in both the CREATE TABLEcommand and the ALTER TABLE command.

� The CASCADE clause disables dependent integrity constraints.

Page 202: OCP - SQL&PL_SQL(Vol2)

����� ������ �� ������ ��� � ������ ����� ����� ��� ���� ������%

Page 203: OCP - SQL&PL_SQL(Vol2)

�������� ���� � ���������� ����&

0��11��� ���

The DROP TABLE command removes the definition of an Oracle7 table. When youdrop a table, the database loses all the data in the table and all the indexes associatedwith it. The CASCADE CONSTRAINTS option will also remove dependentreferential integrity constraints.

�(��)

DROP TABLE table [CASCADE CONSTRAINTS];

where: table is the name of the table.

*�� ������

� All data is deleted from the table.

� Any views, synonyms, stored procedures, functions, or packages will remain, butare invalid.

� Any pending transactions are committed.

� Only the creator of the table or a user with the DROP ANY TABLE privilege canremove a table.

The DROP TABLE command, once executed, is irreversible. The Oracle7 Serverdoes not question the action when you issue the DROP TABLE command. If you ownthat table or have a high level privilege, then the table is immediately removed. AllDDL commands issue a commit, therefore making the transaction permanent.

Page 204: OCP - SQL&PL_SQL(Vol2)

����� ������ �� ������ ��� � ������ ����� ����� ��� ���� ������+

Page 205: OCP - SQL&PL_SQL(Vol2)

�������� ���� � ���������� ����,

3��'��� � �������� ���

Additional DDL commands include the RENAME command, which is used torename a table, view, sequence, or synonym, and the TRUNCATE TABLE command,which is used to remove all rows from a table and to release the storage space used bythat table.

�(��)4325�-2 ��''�

RENAME old_name TO new_name;

You must be the owner of the object you rename.

�(��)43�5��2 ��''�

TRUNCATE TABLE table;

You must be the owner of the table or have DELETE TABLE system privileges totruncate a table.

The DELETE command can also remove all rows from a table, but it does not releasestorage space.

Page 206: OCP - SQL&PL_SQL(Vol2)

����� ������ �� ������ ��� � ������ ����� ����� ��� ���� ������/

Page 207: OCP - SQL&PL_SQL(Vol2)

�������� ���� � ���������� �����

� ��� ��''��� �� ���

You can add a comment of up to 2000 bytes about a column, table, view, or snapshotby using the COMMENT command. The comment is stored in the data dictionaryand can be viewed in one of the following data dictionary views in the COMMENTScolumn:

� ALL_COL_COMMENTS

� USER_COL_COMMENTS

� ALL_TAB_COMMENTS

� USER_TAB_COMMENTS

�(��)

COMMENT ON TABLE table | COLUMN table.column IS ’text’;

where: table is the name of the table.

column is the name of the column in a table.

text is the text of the comment.

2)'1���

Add a comment on the S_EMP table.

SQL> COMMENT ON TABLE s_emp IS ’Employee Information’;

Comment created.

Remove a comment from a column.

SQL> COMMENT ON COLUMN s_emp.last_name IS ’’;

Comment created.

Page 208: OCP - SQL&PL_SQL(Vol2)

����� ������ �� ������ ��� � ������ ����� ����� ��� ���� �������

Page 209: OCP - SQL&PL_SQL(Vol2)

�������� ���� � ���������� �����

��''�(

Data definition commands (DDL) allow you to create, modify, remove, and renameobjects. When you issue a DDL command, an autocommit occurs. You cannot rollback your commands.

�32�2 ���2

� You can create a table and the indicated constraints.

� Create a table based on another table by using a subquery.

��23 ���2

� Modify table structures and constraints.

� Change column widths, change column datatypes, add columns, add or dropconstraints, and enable or disable constraints.

03�� ���2

� Remove rows and a table structure.

� Once executed, this command cannot be rolled back.

325�-2

� Rename a table, view, sequence, or synonym.

3�5��2

� Remove all rows from a table and release the storage space used by the table.

� DELETE command only removes rows.

��--25

� Add a comment to a table or a column.

� Query the data dictionary to view the comment.

Page 210: OCP - SQL&PL_SQL(Vol2)

����� ������ �� ������ ��� � ������ ����� ����� ��� ���� ������"

Page 211: OCP - SQL&PL_SQL(Vol2)

�������� ���� � ���������� ����#

������� �!��!��$

In this practice, you will create, modify, and drop tables related to the EMPLOYEEand DEPARTMENT tables using the commands covered in this lesson.

������� ��������

� Creating a new table by using the CREATE TABLE AS syntax

� Adding constraints

� Modifying column definitions

� Dropping tables

� Adding a comment to a table

� Displaying information in data dictionary views

Page 212: OCP - SQL&PL_SQL(Vol2)

����� ������ �� ������ ��� � ������ ����� ����� ��� ���� ������%

Page 213: OCP - SQL&PL_SQL(Vol2)

�������� ���� � ���������� ����&

������� ��

1. Create a WORKER table, which copies the data from the EMPLOYEE table.Describe the table to confirm its structure.

2. View the constraints for this new table. Save this command to a script namedp12q2.sql. Note the types and names of the constraints.

3. Compare these constraints to those in the EMPLOYEE table. Note the types andnames of the constraints.

4. Add a table level PRIMARY KEY constraint to the WORKER table using the IDcolumn. The constraint should be immediately enabled.

5. Add a foreign key reference from the DEPARTMENT table to the DEPT_IDcolumn in the WORKER table. Confirm that the constraints were added byre-executing p12q2.sql.

6. Display the object names and types from the USER_OBJECTS data dictionaryview. You may want to format the columns for readability. Notice that the newtable and a new index were created.

7. Drop the EMPLOYEE table, while leaving the WORKER table in the database.

If you have time, complete the following exercises.

8. Modify the WORKER table. Add a TITLE column of VARCHAR2 datatype,length 30.

9. Add a comment to the WORKER and DEPARTMENT table definitionsdescribing the tables. Confirm your additions in the data dictionary.

TABLE_NAME COMMENTS--------------- ------------------------------DEPARTMENT Departmental ListingWORKER Employee Information

Page 214: OCP - SQL&PL_SQL(Vol2)

����� ������ �� ������ ��� � ������ ����� ����� ��� ���� ������+

Page 215: OCP - SQL&PL_SQL(Vol2)

�������� ������

��

Page 216: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� �� ��� ����� � ��� ��������� �����������

Page 217: OCP - SQL&PL_SQL(Vol2)

�������� ������ ����

������� �

Many applications require the use of unique numbers as primary key values.You can either build code into the application to handle this requirement or usea sequence to generate unique numbers. This lesson covers creating and usingsequences that create unique numbers.

At the end of this lesson, you should be able to

� Explain the use of sequences.

� Create a sequence.

� Use a sequence.

� Modify a sequence definition.

� Remove a sequence.

Page 218: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� �� ��� ����� � ��� ��������� ����������!

Page 219: OCP - SQL&PL_SQL(Vol2)

�������� ������ ���"

� �� ��#

A sequence generator can be used to automatically generate sequence numbers forrows in tables. A sequence is a database object created by a user and can be shared bymultiple users.

A typical usage for sequences is to create a primary key value, which must be uniquefor each row. The sequence is generated and incremented (or decremented) by aninternal Oracle7 routine. This can be a time saving object because it can reduce theamount of application code needed to write a sequence generating routine.

Sequence numbers are stored and generated independently of tables. Therefore, thesame sequence can be used for multiple tables.

Page 220: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� �� ��� ����� � ��� ��������� ����������$

Page 221: OCP - SQL&PL_SQL(Vol2)

�������� ������ ���%

�������� � ������

Define a sequence to generate sequential numbers automatically by using theCREATE SEQUENCE command.

&������� '���(

CREATE SEQUENCE sequence[INCREMENT BY n][START WITH n][{MAXVALUE n | NOMAXVALUE}][{MINVALUE n | NOMINVALUE}][{CYCLE | NOCYCLE}][{CACHE n | NOCACHE}]

where: sequence is the name of the sequence generator.

INCREMENT BY n specifies the interval between sequence numberswhere n is an integer. If this clause is omitted,the sequence will increment by 1.

START WITH n specifies the first sequence number to begenerated. If this clause is omitted, the sequencewill start with 1.

MAXVALUE n specifies the maximum value the sequence cangenerate.

NOMAXVALUE specifies a maximum value of 1027. This is thedefault option.

MINVALUE n specifies the minimum sequence value.

NOMINVALUE specifies a minimum value of 1.

CYCLE | NOCYCLE specifies that the sequence continues to generatevalues after reaching either its maximum orminimum value or does not generate additionalvalues. NOCYCLE is the default option.

CACHE n | NOCACHE specifies how many values the Oracle7 Serverwill preallocate and keep in memory. Bydefault, the Server will cache 20 values.

For more information, seeOracle7 Server SQL Reference, Release 7.3, “CREATE SEQUENCE.”

Page 222: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� �� ��� ����� � ��� ��������� ����������)

Page 223: OCP - SQL&PL_SQL(Vol2)

�������� ������ ���*

�������� � ������ ���������

+(�,-��

Create a sequence named S_DEPT_ID to be used for the DEPT_ID column of theS_DEPT table. Start the sequence at 51. Do not allow caching and do not allow thesequence to cycle.

SQL> CREATE SEQUENCE s_dept_id2 INCREMENT BY 13 START WITH 514 MAXVALUE 99999995 NOCACHE6 NOCYCLE;

Sequence created.

Do not use the CYCLE option if the sequence is used to generate primary key values.

Page 224: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� �� ��� ����� � ��� ��������� �����������.

Page 225: OCP - SQL&PL_SQL(Vol2)

�������� ������ �����

�������� � ������ ���������

���/��,��� ������

Once you have created your sequence, it is documented in the data dictionary. Since asequence is a database object, you can identify it in the USER_OBJECTS datadictionary table.

You can also confirm the settings of the sequence by selecting from the datadictionary’s USER_SEQUENCES table.

+(�,-��

Display information about all the sequences that you own.

SQL> SELECT sequence_name, min_value, max_value, 2 increment_by, last_number3 FROM user_sequences;

SEQUENCE_NAME MIN_VALUE MAX_VALUE INCREMENT_BY LAST_NUMBER--------------- --------- --------- ------------ -----------S_CUSTOMER_ID 1 9999999 1 216S_DEPT_ID 1 9999999 1 51S_EMP_ID 1 9999999 1 26S_IMAGE_ID 1 9999999 1 1981S_LONGTEXT_ID 1 9999999 1 1369S_ORD_ID 1 9999999 1 113S_PRODUCT_ID 1 9999999 1 50537S_REGION_ID 1 9999999 1 6S_WAREHOUSE_ID 1 9999999 1 10502

9 rows selected.

Page 226: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� �� ��� ����� � ��� ��������� ������������

Page 227: OCP - SQL&PL_SQL(Vol2)

�������� ������ �����

� ��� � ������

Once you create your sequence, you can use the sequence to generate sequentialnumbers for use in your tables. Reference the sequence values by using theNEXTVAL and CURRVAL pseudocolumns.

0+123&� ��� ��443&� � ��������,�

The NEXTVAL pseudocolumn is used to extract successive sequence numbers from aspecified sequence. You must qualify NEXTVAL with the sequence name. When youreference sequence.NEXTVAL, a new sequence number is generated and the currentsequence number is placed in CURRVAL.

The CURRVAL pseudocolumn is used to refer to a sequence number that the currentuser has just generated. NEXTVAL must be used to generate a sequence number inthe current user’s session before CURRVAL can be referenced. You must qualifyCURRVAL with the sequence name. When sequence.CURRVAL is referenced, thelast value returned to that user’s process is displayed.

4��� /�� � ��� 0+123&� ��� ��443&�

You can use NEXTVAL and CURRVAL in

� The SELECT list of a SELECT statement that is not part of a subquery.

� The SELECT list of a subquery in an INSERT statement.

� The VALUES clause of an INSERT statement.

� The SET clause of an UPDATE statement.

You cannot use NEXTVAL and CURRVAL in

� A SELECT list of a view.

� A SELECT statement with the DISTINCT keyword.

� A SELECT statement with the GROUP BY, HAVING, or ORDER BY clauses.

� A subquery in a SELECT, DELETE, or UPDATE statement.

� A DEFAULT expression in a CREATE TABLE or ALTER TABLE command.

For more information, seeOracle7 Server SQL Reference, Release 7.3, “Pseudocolumns” section and “CREATESEQUENCE.”

Page 228: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� �� ��� ����� � ��� ��������� �����������!

Page 229: OCP - SQL&PL_SQL(Vol2)

�������� ������ ����"

� ��� � ������ ���������

���5��� ������ 3����

Cache sequences in the memory to allow faster access to those sequence values. Thecache is populated at the first reference to the sequence. Each request for the nextsequence value is retrieved from the cached sequence. After the last sequence is used,the next request for the sequence pulls another cache of sequences into memory.

��#��� �/ 6�- �� 7��� ������

Although sequence generators issue sequential numbers without gaps, this actionoccurs independent of a commit or rollback. Therefore, if you roll back a commandcontaining a sequence, the number is lost.

Another event that can cause gaps in the sequence is a system crash. If the sequencecaches values in the memory, then those values are lost if the system crashes.

Because sequences are not tied directly to tables, the same sequence can be used formultiple tables. If this occurs, each table can contain gaps in the sequential numbers.

3��#��� �5� 0�(� & ������� ������ 3���� 8��5��� �����,������ ��

It is possible to view the next available sequence value without incrementing it, onlyif the sequence was created with NOCACHE, by querying the USER_SEQUENCEStable.

Page 230: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� �� ��� ����� � ��� ��������� �����������$

Page 231: OCP - SQL&PL_SQL(Vol2)

�������� ������ ����%

&������� � ������

If you reach the MAXVALUE limit for your sequence, no additional values from thesequence will be allocated and you will receive an error indicating the sequenceexceeds the MAXVALUE. To continue to use the sequence, you can modify it byusing the ALTER SEQUENCE command.

'���(

ALTER SEQUENCE sequence[INCREMENT BY n][{MAXVALUE n | NOMAXVALUE}][{MINVALUE n | NOMINVALUE}][{CYCLE | NOCYCLE}][{CACHE n | NOCACHE}]

6��������

� You must own or you have the ALTER privilege for the sequence in order tomodify it.

� Only future sequence numbers are affected by the ALTER SEQUENCEcommand.

� Some validation is performed. For example, a new MAXVALUE cannot beimposed that is less than the current sequence number.

� The START WITH option cannot be changed using ALTER SEQUENCE. Thesequence must be dropped and re-created in order to restart the sequence at adifferent number.

For more information, seeOracle7 Server SQL Reference, Release 7.3, “ALTER SEQUENCE.”

Page 232: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� �� ��� ����� � ��� ��������� �����������)

Page 233: OCP - SQL&PL_SQL(Vol2)

�������� ������ ����*

4�,� ��� � ������

To remove a sequence from the data dictionary, use the DROP SEQUENCEcommand. You must be the owner of the sequence or have the DROP ANYSEQUENCE privilege to remove it.

'���(

DROP SEQUENCE sequence;

where: sequence is the name of the sequence generator.

For more information, seeOracle7 Server SQL Reference, Release 7.3, “DROP SEQUENCE.”

Page 234: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� �� ��� ����� � ��� ��������� �����������.

Page 235: OCP - SQL&PL_SQL(Vol2)

�������� ������ �����

�,,��'

The sequence generator can be used to automatically generate sequence numbers forrows in tables. This can be time saving, and can reduce the amount of applicationcode needed.

A sequence is a database object that can be shared with other users. Informationabout the sequence can be found in the USER_SEQUENCES table of the datadictionary.

To use a sequence, reference it with either the NEXTVAL or the CURRVALpseudocolumns.

� Retrieve the next number in the sequence by referencing sequence.NEXTVAL.

� Return the current available number by referencing sequence.CURRVAL.

Page 236: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� �� ��� ����� � ��� ��������� ������������

Page 237: OCP - SQL&PL_SQL(Vol2)

�������� ������ �����

�������� � �� ��#

In this practice, you will create a sequence to be used when populating yourDEPARTMENT and WORKER tables.

�������� �������

� Creating a sequence

� Modifying a sequence

� Using a sequence

Page 238: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� �� ��� ����� � ��� ��������� �����������!

Page 239: OCP - SQL&PL_SQL(Vol2)

�������� ������ ����"

�������� ��

1. Create a sequence to be used with the DEPARTMENT table’s primary keycolumn. The sequence should start at 76 and have a maximum value of 80. Besure that it increments by one number. Name the sequence DEPT_ID_SEQ.

2. Create another sequence. This sequence will be used with the WORKER table’sprimary key column. Start this sequence at 204, and set the maximum value to be9999999. Be sure that it increments by one number. Allow the sequence to cache5 numbers. Name the sequence WORKER_ID_SEQ.

3. Write a script to display the following information about your sequences:sequence name, cache size, maximum value, increment size, and last numbergenerated. Name the script p13q3.sql.

4. Write an interactive script to insert a row into the DEPARTMENT table. Nameyour script p13q4.sql. Be sure to use the sequence you created for the ID column.Create a customized prompt to enter the department name. Execute your script.Add two departments named Education and Administration. Confirm youradditions.

5. Display information about your sequences by executing the p13q3.sql script.Notice that the WORKER_ID_SEQ last number does not match the highestprimary key value in Exercise 6. Why?

If you completed Practice 12, Exercise 8, you can do the following two exercises.

6. Write a script to insert two rows into the WORKER table. Name your scriptp13q5.sql. Use the sequence you create for the ID column. Execute your script.Add Tomas Lira as the President in the last department you just added to thetable. The other employee is Anna Seigher who is the Vice President in theFinance department.

7. Confirm your additions to the DEPARTMENT table and WORKER table. Notethe highest primary key values for each table.

Page 240: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� �� ��� ����� � ��� ��������� �����������$

�������� �� ���������

If you have time, complete the following exercises:

8. Execute p13q4.sql to insert four additional departments named Accounting,Warehouse, Operations, and Research. What happened and why?

9. Modify your department sequence to allow no maximum value. Verify the changeto the sequence by executing the p13q3.sql script.

10. Add the Research department by using your script named p13q4.sql. Make thisaddition permanent.

11. Display the contents of the DEPARTMENT table and WORKER table.

Page 241: OCP - SQL&PL_SQL(Vol2)

�������� ���

Page 242: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� ��� ��� ������ ����� ��������� �������� ��

Page 243: OCP - SQL&PL_SQL(Vol2)

�������� ��� � ��

� !����"��

In this lesson, you will see how views can be used to present data to users in avariety of ways. In addition, you will see how integrity constraints can beenforced, if using a view to insert, update, or delete data.

At the end of this lesson, you should be able to

� Explain the concept of a view.

� Use data dictionary views.

� Create simple and complex views.

� Create a view with an option to enforce constraints.

� Modify a view.

� Remove a view.

Page 244: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� ��� ��� ������ ����� ��������� �������� �

Page 245: OCP - SQL&PL_SQL(Vol2)

�������� ��� � �#

�"��"��

Present logical subsets or combinations of data by creating views of tables.

$%�� �� � ��&

A view is a logical table based on a table or another view. A view contains no data ofits own, but is rather like a “window” through which data from tables can be viewedor changed. The tables upon which a view is based are called base tables. The view isstored as a SELECT statement in the data dictionary.

'�"������� �( ���

� Restrict access to the database because the view can display a selective portion ofthe database.

� Allow users to make simple queries to retrieve the results from complicatedqueries. For example, views allow users to query information from multiple tableswithout knowing how to write a join statement.

� Provide data independence for ad hoc users and application programs. One viewcan be used to retrieve data from several tables.

� Provide groups of users access to data according to their particular criteria.

For more information, seeOracle7 Server SQL Reference, Release 7.3, “CREATE VIEW.”

Page 246: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� ��� ��� ������ ����� ��������� �������� �)

Page 247: OCP - SQL&PL_SQL(Vol2)

�������� ��� � �*

�������� � ��

Create a view by embedding a subquery within the CREATE VIEW statement.

' ������ �+���,

CREATE [OR REPLACE] [FORCE|NOFORCE] VIEW view [(alias[, alias]...)]AS subquery[WITH CHECK OPTION [CONSTRAINT constraint]][WITH READ ONLY]

where: OR REPLACE recreates the view if it already exists.

FORCE creates the view regardless of whether the basetables exist or not.

NOFORCE creates the view only if the base tables exist.This is the default.

view is the name of the view.

alias specifies names for the expressions selected bythe view’s query. The number of aliases mustmatch the number of expressions selected by theview.

subquery is a complete SELECT statement. You can usealiases for the columns in the SELECT list.

WITH CHECK OPTION specifies that only rows accessible to the viewmay be inserted or updated.

constraint is the name assigned to the CHECK OPTIONconstraint.

WITH READ ONLY ensures that no DML operations can beperformed on this view.

-���������

� The query that defines a view can contain complex SELECT syntax, includingjoins, groups, and subqueries.

� The query that defines the view cannot contain an ORDER BY clause.

� If you do not specify a constraint name, the system will assign a default name inthe format SYS_Cn.

� You can use the OR REPLACE option to change the definition of the viewwithout dropping and re-creating it, or regranting object privileges previouslygranted on it.

Page 248: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� ��� ��� ������ ����� ��������� �������� �.

Page 249: OCP - SQL&PL_SQL(Vol2)

�������� ��� � �/

�������� � �� ���������

There are two classifications for views: simple and complex. The basic difference isrelated to the DML operations.

��01�� ��� ��01���� �� ��01��, ���

Characteristic Simple Views Complex Views

Number of tables Only one One or more

Contain functions No Yes

Contain groups of data (DISTINCTor group functions)

No Yes

DML through the view Yes No

2,�01��

Create a view containing the employee number, last name, and job title for employeesin department 45. Display the contents.

SQL> CREATE VIEW empvu452 AS SELECT id, last_name, title3 FROM s_emp4 WHERE dept_id = 45;

View created.

SQL> SELECT *2 FROM empvu45;

ID LAST_NAME TITLE------ ------------ --------------------- 10 Havel Warehouse Manager 24 Dancs Stock Clerk 25 Schwartz Stock Clerk

Page 250: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� ��� ��� ������ ����� ��������� �������� ��3

Page 251: OCP - SQL&PL_SQL(Vol2)

�������� ��� � ���

�������� � �� ���������

Control the column names by including column aliases within the subquery.

2,�01��

Create a view containing the employee number, first name with the alias FIRST, lastname with the alias LAST, and salary with the alias MONTHLY_SALARY fordepartment 41.

SQL> CREATE VIEW salvu412 AS SELECT id, first_name FIRST, last_name LAST,3 salary MONTHLY_SALARY4 FROM s_emp5 WHERE dept_id = 41;

View created.

Alternatively, control the column names by including column aliases in the CREATEVIEW clause. To change the view definition, use the CREATE OR REPLACEclause.

2,�01��

Modify EMPVU45 view. Change the employee number to have a headingID_NUMBER, last name to a heading EMPLOYEE, and title to a heading JOB.

SQL> CREATE OR REPLACE VIEW empvu45 2 (id_number, employee, job)3 AS SELECT id, last_name, title4 FROM s_emp5 WHERE dept_id = 45;

View created.

Note: When assigning column aliases in the CREATE VIEW clause, remember thatthe aliases are listed in the same order as the columns in the subquery.

Page 252: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� ��� ��� ������ ����� ��������� �������� ���

Page 253: OCP - SQL&PL_SQL(Vol2)

�������� ��� � ���

�������� � �� ���������

Create a complex view that contains group functions to display values from twotables.

2,�01��

Create a view of the department names, minimum salary, maximum salary, andaverage salary by department. Display the structure of the view and its contents.

SQL> CREATE VIEW dept_sum_vu 2 (name, minsal, maxsal, avgsal)3 AS SELECT d.name, min(e.salary), 4 max(e.salary), avg(e.salary)5 FROM s_emp e, s_dept d6 WHERE e.dept_id = d.id7 GROUP BY d.name;

View created.

SQL> DESCRIBE dept_sum_vu

Name Null? Type------------------------------- -------- ----NAME NOT NULL VARCHAR2(25)MINSAL NUMBERMAXSAL NUMBERAVGSAL NUMBER

SQL> SELECT *2 FROM dept_sum_vu;

NAME MINSAL MAXSAL AVGSAL-------------------- ---------- ---------- ----------Administration 1550 2500 2025Finance 1450 1450 1450Operations 750 1450 1086.8Sales 795 1525 1367.85714

Page 254: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� ��� ��� ������ ����� ��������� �������� ��

Page 255: OCP - SQL&PL_SQL(Vol2)

�������� ��� � ��#

���(��0��� 45� �1�������� �� � ��

You can perform DML operations on data through a view provided those operationsfollow the rules outlined below:

� You can remove a row from a view unless it contains any of the following:

� Group functions

� A GROUP BY clause

� The DISTINCT command

� You can modify data in a view unless it contains any of the above and any of thefollowing:

� Columns defined by expressions, for example, SALARY * 12.

� The ROWNUM pseudocolumn.

� You can add data through a view unless it contains any of the above and there areNOT NULL columns in the base table that are not selected by the view. Allrequired values must be present in the view. Remember that you are adding valuesdirectly into the underlying table through the view.

For more information, seeOracle 7 Server SQL Reference, Release 7.3, “CREATE VIEW.”

Page 256: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� ��� ��� ������ ����� ��������� �������� ��)

Page 257: OCP - SQL&PL_SQL(Vol2)

�������� ��� � ��*

���(��0��� 45� �1�������� �� � �� ���������

You can ensure that when you add or update data in a simple view, the added orupdated data can be queried through the view.

2,�01��

Create a view that contains all columns from the S_EMP table for department 45.Add the WITH CHECK OPTION clause.

SQL> CREATE OR REPLACE VIEW empvu412 AS SELECT *3 FROM s_emp4 WHERE dept_id = 415 WITH CHECK OPTION CONSTRAINT empvu41_ck;

View created.

Attempt to change the department number for employee 16 to department 42 throughthe view.

SQL> UPDATE empvu412 SET dept_id = 423 WHERE id = 16;

ERROR at line 3:ORA-01402: view WITH CHECK OPTION where-clauseviolation

Note: No rows are updated because if the department number were to change to 42,the view would no longer be able to see that employee. Therefore, with theWITH CHECK OPTION clause, the view can only see department 41employees, and does not allow the department number for those employees tobe changed through the view.

Page 258: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� ��� ��� ������ ����� ��������� �������� ��.

Page 259: OCP - SQL&PL_SQL(Vol2)

�������� ��� � ��/

���(��0��� 45� �1�������� �� � �� ���������

You can ensure that no DML operations occur on your view by creating it with theWITH READ ONLY option.

2,�01��

Modify the EMPVU45 view. Do not allow DML operations to occur on this view.Attempt to remove a row from the view.

SQL> CREATE OR REPLACE VIEW empvu45 2 (id_number, employee, job)3 AS SELECT id, last_name, title4 FROM s_emp5 WHERE dept_id = 456 WITH READ ONLY;

View created.

SQL> DELETE FROM empvu452 WHERE id_number = 10;

ERROR at line 1:ORA-01732: data manipulation operation not legal onthis view

Page 260: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� ��� ��� ������ ����� ��������� �������� ��3

Page 261: OCP - SQL&PL_SQL(Vol2)

�������� ��� � ���

���(��0��� �� 6�0�� ��� ����������

You can confirm the names and defining SELECT statements of views by queryingthe USER_VIEWS data dictionary table.

2,�01��

Describe the structure of the USER_VIEWS data dictionary table. Display the namesand contents of all views currently owned by the user.

SQL> DESCRIBE user_views

Name Null? Type------------------------------- -------- ----VIEW_NAME NOT NULL VARCHAR2(30)TEXT_LENGTH NUMBERTEXT LONG

SQL> SELECT *2 FROM user_views;

VIEW_NAME TEXT_LENGTH TEXT--------------- ----------- -----------------------------------DEPT_SUM_VU 121 SELECT d.name, MIN(e.salary), MAX(e .salary), AVG(e.salary) FROM s_emp e, s_dept EMPVU41 179 SELECT ”ID”,”LAST_NAME”,”FIRST_NAM E”,”USERID”,”START_DATE”,”COMMENTS” ,”MANAGER_ EMPVU45 56 SELECT id, last_name, title FROM s_emp WHERE dept_id=45 SALVU41 97 SELECT id, first_name first, last_n ame last, salary monthly_salary FROM s_emp WH

Page 262: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� ��� ��� ������ ����� ��������� �������� ���

Page 263: OCP - SQL&PL_SQL(Vol2)

�������� ��� � ���

7�0�"��� � ��

Use the DROP VIEW command to remove a view. The command removes the viewdefinition from the database. Dropping views has no affect on the tables on which theview was based. Views or other applications based on deleted views become invalid.Only the creator or a user with the DROP ANY VIEW privilege can remove a view.

�+���,

DROP VIEW view;

where: view is the name of the view.

Page 264: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� ��� ��� ������ ����� ��������� �������� ��

Page 265: OCP - SQL&PL_SQL(Vol2)

�������� ��� � ��#

��00��+

A view is based on a table or another view and acts as a window through which dataon tables can be viewed or changed. A view does not contain data. The definition ofthe view is stored in the data dictionary. You can see the definition of the view in theUSER_VIEWS data dictionary table.

'�"������� �( ���

� Restrict database access

� Simplify queries

� Provide data independence

� Allow multiple views of the same data

� Remove views without affecting the underlying data

�� �1�����

� Can be a simple view based on one table

� Can be a complex view based on more than one table, or contain groups orfunctions

� Can be replaced if one of the same name exists

� Contain a check constraint

� Can be read-only

Page 266: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� ��� ��� ������ ����� ��������� �������� ��)

Page 267: OCP - SQL&PL_SQL(Vol2)

�������� ��� � ��*

�������� �"��"��

In this practice, you will create simple and complex views, and attempt to performDML statements to the views.

�������� ��������

� Creating a simple view

� Creating a complex view

� Creating a view with a check constraint

� Attempting to modify data in the view

� Displaying view definitions

� Removing views

Page 268: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� ��� ��� ������ ����� ��������� �������� ��.

Page 269: OCP - SQL&PL_SQL(Vol2)

�������� ��� � ��/

�������� �

1. Create a view called EMP_VU based on the employee number, last name, anddepartment number from the WORKER table. Change the heading for the lastname to EMPLOYEE.

a. Display the content of the EMP_VU view.

b. Write a script to display the definition of a view. Pass the name of the view tothe script. Save the script as p14q1.sql. Execute the script to view thedefinition of the EMP_VU view.

c. Change the department number for Smith to 37 in the EMP_VU view.

d. Confirm that Smith is now assigned to department 37.

2. Create a view called MNS_VU that contains the employee number, full name, anddepartment name for all employees in the Marketing and Sales departments in theWORKER and DEPARTMENT tables.

a. Display the structure and contents of the MNS_VU view.

b. Display the definition of the MNS_VU view by executing the p14q1.sqlscript.

c. Display the department name and number of employees in each department.

3. Modify EMP_VU view contain only those employees in department 37. Add acheck constraint so that the department number cannot be modified.

a. Display the contents of the EMP_VU view.

b. Change the department number for Smith back to 54 through the EMP_VUview. Was your operation successful? Why or why not?

If you have time, complete the following exercises:

4. Modify the MNS_VU so that the rows can only be seen between 1:00 P.M. and4:00 P.M. You can edit the script named p14q1.sql. Execute the script. Displaythe contents of the view.

5. Remove all views from the data dictionary. Confirm that no views exist in thedata dictionary.

Page 270: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� ��� ��� ������ ����� ��������� �������� ��3

Page 271: OCP - SQL&PL_SQL(Vol2)

�������� �����

Page 272: OCP - SQL&PL_SQL(Vol2)

���������� �� ������� ��� �� ������ ����� �������� ������ ���

Page 273: OCP - SQL&PL_SQL(Vol2)

�������� ����� ���

�� ����!��

If you want to improve the performance of some queries, you should considercreating an index. You can also use indexes to enforce uniqueness on a column ora collection of columns.

At the end of this lesson, you should be able to

� Distinguish between the indexes that are created automatically and those that arecreated manually.

� Identify the uses for indexes.

� Explain the index structure and why it improves query speed.

� Create a non-unique index.

� Remove an index from the data dictionary.

� Evaluate guidelines for creating and using indexes.

Page 274: OCP - SQL&PL_SQL(Vol2)

���������� �� ������� ��� �� ������ ����� �������� ������ ��"

Page 275: OCP - SQL&PL_SQL(Vol2)

�������� ����� ���

�!��!��#

An Oracle7 Server index is a database object that can speed up the retrieval of rowsby using a pointer. Indexes can be created explicitly or automatically. They aretransparent to the user. If you do not have an index on the column, then a full tablescan will occur.

$%�� � �� ���&

An index is a database object that provides direct and fast access to rows in a table.Its purpose is to reduce the necessity of disk I/O by using a B*Tree indexed path tolocate data quickly. The index is automatically used and maintained by the Oracle7Server. Once an index is created, no direct activity is required by the user.

Indexes are logically and physically independent of the table they index. This meansthat they can be created or dropped at any time and have no effect on the base tablesor other indexes.

'�# (�� ����� ������&

Two types of indexes can be created. One type is a unique index. The Oracle7 Serverautomatically creates this index when you define a column in a table to have aPRIMARY KEY or a UNIQUE constraint. The name of the index is the name givento the constraint.

The other type of index a user can create is a non-unique index. For example, you cancreate a FOREIGN KEY column index for a join in a query to improve retrievalspeed.

For more information, seeOracle7 Server Concepts Manual, Release 7.3, “Schema Objects” section, “Indexes”topic.

Page 276: OCP - SQL&PL_SQL(Vol2)

���������� �� ������� ��� �� ������ ����� �������� ������ ��)

Page 277: OCP - SQL&PL_SQL(Vol2)

�������� ����� ��*

$%�� � �%� ��� ���&

Once the index has been created, the Oracle7 Server will use it whenever possible tospeed up access to the data. Note that this use is automatic and usually requires noaction by the user. A brief guideline is provided below on how the Server determinesto use the index.

�+��,�-����� .��%��/���

When an index is used depends partly on the Oracle Optimizer being used at the time.The Oracle7 Server uses both rule-based and cost-based optimization.

Rule-based optimization is when the Oracle7 Server decides when it is appropriate touse an index based on its internal rules. The Server identifies the columns that areindexed and the index types.

The cost-based optimization method uses statistics about tables along withinformation about available indexes to select an execution plan for the SQLstatements.

For more information, seeTune Oracle7 Applications course description.

Page 278: OCP - SQL&PL_SQL(Vol2)

���������� �� ������� ��� �� ������ ����� �������� ������ ��0

Page 279: OCP - SQL&PL_SQL(Vol2)

�������� ����� ��1

��� ���������

An index is an optional structure that is independent of the table structure. Each indexis composed of column values that the index is on and pointers (or ROWIDs) to therow containing that value. The pointer directly points to the appropriate row in thetable, therefore avoiding a full table scan.

�2.���

The Oracle7 Server uses a balanced B*tree index structure. This is a binary,self-balancing search structure to equalize access times to any row. It is an efficientmethod of ensuring that access to any specified value will take approximately thesame time whether the row is at the beginning, middle, or end of the table.

Each index that the Oracle7 Server builds consists of a number of pages (or branches)of storage arranged in a tree. Each page (or branch) holds a series of key values andpointers to pages (or branches) lower in the structure until eventually the key valuesindicate the location of the data itself. The location identifier at the database level iscalled a ROWID.

Page 280: OCP - SQL&PL_SQL(Vol2)

���������� �� ������� ��� �� ������ ����� �������� ������ �� 3

Page 281: OCP - SQL&PL_SQL(Vol2)

�������� ����� ��

��� ��������� ���������

��� .4+��

Type Description

Unique Ensures that values in specified columns areunique.

Non-unique Ensures fastest possible results when queryingdata.

Single column Only one column exists in the index.

Concatenated or composite Can contain up to 16 columns in the index foreither performance or uniqueness checkpurposes. The columns need not be adjacent.

Index types are not mutually exclusive. For example, you can create a unique,concatenated index.

Page 282: OCP - SQL&PL_SQL(Vol2)

���������� �� ������� ��� �� ������ ����� �������� ������ �� �

Page 283: OCP - SQL&PL_SQL(Vol2)

�������� ����� �� �

�������� �� ���

Create an index on one or more columns by issuing the CREATE INDEX command.

(����� �4����

CREATE INDEX indexON table (column[, column]...);

where: index is the name of the index.

table is the name of the table.

column is the name of the column in the table to beindexed.

5��,+��

Create an index to improve the speed of query access on the LAST_NAME columnin the S_EMP table.

SQL> CREATE INDEX s_emp_last_name_idx2 ON s_emp(last_name);

Index created.

For more information, seeOracle7 Server SQL Reference, Release 7.3, “CREATE INDEX.”

Page 284: OCP - SQL&PL_SQL(Vol2)

���������� �� ������� ��� �� ������ ����� �������� ������ �� "

Page 285: OCP - SQL&PL_SQL(Vol2)

�������� ����� �� �

�������� �� ��� ���������

6��� � 7�� (�#�4� ������

More indexes on a table does not mean it will speed up queries. Each DML operationthat is committed on a table with indexes means that the indexes must be updated.The more indexes you have associated with a table, the more effort the Server mustmake to update all the indexes after a DML.

$%�� �� ������ �� ���

� The column is used frequently in the WHERE clause or in a join condition.

� The column contains a wide range of values.

� The column contains a large number of null values.

� Two or more columns are frequently used together in a WHERE clause or joincondition.

� The table is large and most queries are expected to retrieve less than 2–4% of therows.

Remember that if you want to enforce uniqueness, you should define a uniqueconstraint in the table definition. Then, a unique index is automatically created.

$%�� �� 7�� ������ �� ���

� The table is small.

� The columns are not often used as a condition in the query.

� Most queries are expected to retrieve more than 2–4% of the rows.

� The table is updated frequently.

Page 286: OCP - SQL&PL_SQL(Vol2)

���������� �� ������� ��� �� ������ ����� �������� ������ �� )

Page 287: OCP - SQL&PL_SQL(Vol2)

�������� ����� �� *

���8��,��� �����

Confirm the existence of indexes from the USER_INDEXES data dictionary view.You can also check the columns involved in an index by querying theUSER_IND_COLUMNS view.

5��,+��

Display all previously created indexes, affected column names, and uniqueness on theS_EMP table.

SQL> SELECT ic.index_name, ic.column_name,2 ic.column_position col_pos, ix.uniqueness3 FROM user_indexes ix, user_ind_columns ic4 WHERE ic.index_name = ix.index_name5 AND ic.table_name = ’S_EMP’;

INDEX_NAME COLUMN_NAME COL_POS UNIQUENESS–––––––––––––––––––– ––––––––––– –––––––– ––––––––––S_EMP_ID_PK ID 1 UNIQUES_EMP_LAST_NAME_IDX LAST_NAME 1 NONUNIQUES_EMP_USERID_UK USERID 1 UNIQUE

Page 288: OCP - SQL&PL_SQL(Vol2)

���������� �� ������� ��� �� ������ ����� �������� ������ �� 0

Page 289: OCP - SQL&PL_SQL(Vol2)

�������� ����� �� 1

9�,�!��� �� ���

You cannot modify indexes. To change an index, you must drop it and then re-createit. Remove an index definition from the data dictionary by issuing the DROP INDEXcommand. In order to drop an index, you must be the owner of the index or have theDROP ANY INDEX privilege.

�4����

DROP INDEX index;

where: index is the name of the index.

Page 290: OCP - SQL&PL_SQL(Vol2)

���������� �� ������� ��� �� ������ ����� �������� ������ ���3

Page 291: OCP - SQL&PL_SQL(Vol2)

�������� ����� ���

��,,��4

Indexes are used to improve the query retrieval speed. They are database objects andtherefore take up disk space. Indexes use the B*tree search method to retrieve thepointer to the rows in the tables.

Unique indexes for the PRIMARY KEY and UNIQUE KEY constraints in a tabledefinition are created automatically.

Users can create non-unique indexes to speed up searches by using the CREATEINDEX command.

Indexes are maintained automatically by the Oracle7 Server. Users can view thedefinitions of the indexes in the USER_INDEXES data dictionary view.

An index can be dropped by the creator or a user with the DROP ANY INDEXprivilege by using the DROP INDEX command.

Page 292: OCP - SQL&PL_SQL(Vol2)

���������� �� ������� ��� �� ������ ����� �������� ������ ����

Page 293: OCP - SQL&PL_SQL(Vol2)

�������� ����� ����

�������� �!��!��#

In this practice you will create an index on the WORKER table.

�������� ��������

� Creating non-unique indexes

� Displaying data dictionary information about the index

� Dropping indexes

Page 294: OCP - SQL&PL_SQL(Vol2)

���������� �� ������� ��� �� ������ ����� �������� ������ ���"

Page 295: OCP - SQL&PL_SQL(Vol2)

�������� ����� ����

�������� �

1. Would any indexes specified be used with the following queries and why?

a. Non-unique index on LAST_NAME.Yes/No

SQL> SELECT *2 FROM s_emp3 WHERE last_name = ’Biri’;

b. Unique index on ID and non-unique index on CUSTOMER_ID.Yes/No

SQL> SELECT id, customer_id, total2 FROM s_ord3 WHERE date_ordered = ’31-AUG-92’;

c. Unique index on S_DEPT.ID and non-unique index on S_EMP.DEPT_ID.Yes/No

SQL> SELECT e.last_name, d.name2 FROM s_emp e, s_dept d3 WHERE e.dept_id = d.id;

Page 296: OCP - SQL&PL_SQL(Vol2)

���������� �� ������� ��� �� ������ ����� �������� ������ ���)

�������� � ���������

2. Create a non-unique index on the foreign key column in the WORKER table.

3. Since users will frequently query on the employee last name, create a non-uniqueindex on that column in the WORKER table.

4. Display the indexes and uniqueness that exist in the data dictionary for theWORKER and DEPARTMENT tables. Save the command into a script namedp15q4.sql.

5. Remove the primary key constraint on the WORKER table.

6. Re-display the indexes and uniqueness that exist in the data dictionary for theWORKER and DEPARTMENT tables by executing the p15q4.sql script. Whatchanges do you observe and why?

If you have time, complete the following exercises:

7. Re-create the primary key constraint on the WORKER table. Confirm theconstraint in the data dictionary by executing pl2q2.sql. Confirm the unique indexin the data dictionary by executing pl5q4.

8. Remove the index on the employee last name from the WORKER table.

Page 297: OCP - SQL&PL_SQL(Vol2)

����������� �� � �

��

Page 298: OCP - SQL&PL_SQL(Vol2)

������� ���� �� ��� ��� ��� ��� ������ ��� ��� ����� �����������

Page 299: OCP - SQL&PL_SQL(Vol2)

����������� �� � � ����

�� � ��!�

This lesson describes the Oracle7 Server decentralized security system. Usingthe commands covered in this lesson, you can control database access to specificobjects and add new users with different levels of access privileges. You canprovide alternative names for objects by using the CREATE SYNONYMcommand.

At the end of this lesson, you should be able to

� Explain the concept of the database security model.

� Describe system privileges.

� Set up and maintain database access by using roles.

� Identify object privileges.

� Change a password.

� Grant and revoke object privileges.

� Create synonyms for ease of table access.

Page 300: OCP - SQL&PL_SQL(Vol2)

������� ���� �� ��� ��� ��� ��� ������ ��� ��� ����� ����������"

���!��

É ÉÉ

Page 301: OCP - SQL&PL_SQL(Vol2)

����������� �� � � ���#

�!��!��$

In a multiple-user environment, you want to maintain security of the database accessand use. Oracle7 Server database security allows you to

� 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 datasecurity. System security covers access and use of the database at the system level,such as username and password, disk space allocated to users, and system operationsallowed by the user. Database security covers access and use of the database objectsand the actions that those users can have on the objects.

���!�����

Privileges are the right to execute particular SQL statements. The databaseadministrator is a high level user with the ability to grant users access to the databaseand its objects. The users require system privileges to gain access to the database andobject privileges to manipulate the content of the objects in the database. Users canalso be given the privilege to grant additional privileges to other users or to roles,which are named groups of related privileges.

� %�&�

A schema is a collection of objects, such as tables, views, and sequences. The schemais owned by a database user and has the same name as that user.

For more information, seeOracle7 Server Application Developer’s Guide, Release 7.3, “Establishing a SecurityPolicy” section and Oracle7 Server Concepts Manual, “Database Security” topic.

Page 302: OCP - SQL&PL_SQL(Vol2)

������� ���� �� ��� ��� ��� ��� ������ ��� ��� ����� �����������

Page 303: OCP - SQL&PL_SQL(Vol2)

����������� �� � � ���'

�(��& ���!�����

There are more than eighty system privileges available for users and roles. Systemprivileges are typically provided by the database administrator.

)(*� �� +�� ���!�����

System Privilege Operations Authorized

CREATE USER Allows grantee to create other Oracle users (aprivilege required for a DBA role).

DROP USER Drops another user.

DROP ANY TABLE Drops a table in any schema.

BACKUP ANY TABLE Backs up any table in any schema with the exportutility.

�������� � ��

The DBA creates a new Oracle7 Server user by allocating a number of systemprivileges to that user. These privileges in turn determine what the user can do at thedatabase level. The DBA creates the user by executing the CREATE USERcommand. The user does not have any system privileges.

�������� �(���,

CREATE USER user IDENTIFIED BY password;

where: user is the name of the user to be created.

password specifies that the user must log in with thispassword.

For more information, seeOracle7 Server SQL Reference, Release 7.3, “GRANT” (System Privileges andRoles) and “CREATE USER.”

Page 304: OCP - SQL&PL_SQL(Vol2)

������� ���� �� ��� ��� ��� ��� ������ ��� ��� ����� ����������-

Page 305: OCP - SQL&PL_SQL(Vol2)

����������� �� � � ���.

�(��& ���!����� ���������

Now that the DBA has created a user, the DBA can assign privileges to that user.

)(*� �� �� ���!�����

System Privilege Operations Authorized

CREATE SESSION Connect to the database.

CREATE TABLE Create tables in the user’s schema.

CREATE SEQUENCE Create a sequence in the user’s schema.

CREATE VIEW Create a view in the user’s schema.

CREATE PROCEDURE Create a stored procedure, function, or package inthe user’s schema.

/������� �(��& ���!�����

The DBA uses the GRANT command to allocate system privileges to the user. Oncethe user has been granted the privileges, the user can immediately use thoseprivileges.

�(���,

GRANT privilege [, privilege...] TO user [, user...];

where: privilege is the system privilege to be granted.

user is the name of the user.

Note: The above syntax is abridged.

Page 306: OCP - SQL&PL_SQL(Vol2)

������� ���� �� ��� ��� ��� ��� ������ ��� ��� ����� �����������0

Page 307: OCP - SQL&PL_SQL(Vol2)

����������� �� � � �����

1%�� � � 2���3

A role is a named group of related privileges that can be granted to the user. Thismethod makes granting and revoking privileges easier to perform and maintain.

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

�������� ��� ������� � 2���

First, the DBA must create the role. Then, the DBA can assign privileges to the roleand users to the role.

�(���,

CREATE ROLE role;

where: role is the name of the role to be created.

Now that the role is created, the DBA can use the GRANT command to assign usersto the role as well as assign privileges to the role.

4,�&*��

Allow the managers to create tables and views. Give these privileges to Velasquezand to Ropeburn.

SQL> CREATE ROLE manager;

Role created.

SQL> GRANT create table, create view TO manager;

Grant succeeded.

SQL> GRANT manager TO cvelasqu, aropebur;

Grant succeeded.

Page 308: OCP - SQL&PL_SQL(Vol2)

������� ���� �� ��� ��� ��� ��� ������ ��� ��� ����� ������������

Page 309: OCP - SQL&PL_SQL(Vol2)

����������� �� � � �����

�%������ 5��� ��$���

Every user has a password that is initialized by the DBA when the user is created.You can change your password by using the ALTER USER command.

�(���,

ALTER USER user IDENTIFIED BY password;

where: user is the name of the user.

password specifies the new password.

Note: Although this command can be used to change your password, there are manyother options. You must have the ALTER USER privilege to change any otheroption.

For more information, seeOracle7 Server SQL Reference, Release 7.3, “ALTER USER.”

Page 310: OCP - SQL&PL_SQL(Vol2)

������� ���� �� ��� ��� ��� ��� ������ ��� ��� ����� �����������"

Page 311: OCP - SQL&PL_SQL(Vol2)

����������� �� � � ����#

/������� �� � � ���!�����

The DBA can allow users to perform a particular action on a specific table, view,sequence, or stored procedure by granting them object privileges. The objectprivileges vary from object to object. The table on the facing page outlines theprivileges. An object owner has all privileges on the object. To give another useraccess to your database objects, execute the GRANT command.

�(���,

GRANT {object_priv(, object_priv...)|ALL}[(columns)]ON objectTO {user[, user...]|role|PUBLIC}[WITH GRANT OPTION];

where: object_priv is an object privilege to be granted.

ALL all object privileges.

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

ON object is the object on which the privileges are granted.

TO identifies to whom the privilege is granted.

PUBLIC grants object privileges to all users.

WITH GRANT OPTION allows the grantee to grant the object privilegesto other users and roles.

Note: A procedure refers to standalone procedures and functions, and publicpackage constructs. The INDEX and REFERENCES privileges cannot begranted to a role.

For more information, seeOracle7 Server SQL Reference, Release 7.3, “GRANT.”

Page 312: OCP - SQL&PL_SQL(Vol2)

������� ���� �� ��� ��� ��� ��� ������ ��� ��� ����� ������������

Page 313: OCP - SQL&PL_SQL(Vol2)

����������� �� � � ����'

/������� �� � � ���!����� ���������

/��������

� To grant privileges on an object, the object must be in your own schema or youmust have been granted the object privileges WITH GRANT OPTION.

� An object owner can grant any object privilege on the object to any other user orrole of the database.

� The owner of an object automatically acquires all object privileges on that object.

4,�&*��

Grant users Sue and Rich the privilege to query your S_EMP table.

SQL> GRANT select2 ON s_emp3 TO sue, rich;

Grant succeeded.

Grant UPDATE privileges on specific columns in the S_DEPT table to Scott and tothe manager role.

SQL> GRANT update (name, region_id)2 ON s_dept3 TO scott, manager;

Grant succeeded.

Page 314: OCP - SQL&PL_SQL(Vol2)

������� ���� �� ��� ��� ��� ��� ������ ��� ��� ����� �����������-

Page 315: OCP - SQL&PL_SQL(Vol2)

����������� �� � � ����.

/������� �� � � ���!����� ���������

)%� 1�)6 /2�7) ��)��7 8�($���

A privilege that is granted WITH GRANT OPTION can be passed on to other usersand roles by the grantee. Object privileges granted WITH GRANT OPTION arerevoked when the grantor’s privilege is revoked.

4,�&*��

As user Alice, allow user Scott to access your S_DEPT table with the privileges toquery the table and add rows to the table. Allow Scott to give others these privileges.

SQL> GRANT select, insert2 ON s_dept3 TO scott4 WITH GRANT OPTION;

Grant succeeded.

)%� ����� 8�($���

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

4,�&*��

As user Scott, allow all users on the system to query data from Alice’s S_DEPT table.

SQL> GRANT select2 ON alice.s_dept3 TO PUBLIC;

Grant succeeded.

Page 316: OCP - SQL&PL_SQL(Vol2)

������� ���� �� ��� ��� ��� ��� ������ ��� ��� ����� �����������0

Page 317: OCP - SQL&PL_SQL(Vol2)

����������� �� � � �����

���9��&��� ���!����� /������

If you attempt to perform an unauthorized operation, for example, deleting a rowfrom a table for which you do not have the DELETE privilege, the Oracle7 Serverwill not permit the operation to take place.

If you receive the Oracle7 Server error message “table or view does not exist,” youhave done either 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 havethe appropriate privilege

1%�� ���!����� +� 5�� 6�!�3

You can access the data dictionary to view the privileges you have.

Data Dictionary Table Description

ROLE_SYS_PRIVS System privileges granted to roles.

ROLE_TAB_PRIVS Table privileges granted to roles.

USER_ROLE_PRIVS Roles accessible by the user.

USER_TAB_PRIVS_MADE Object privileges granted on the user’s objects.

USER_TAB_PRIVS_RECD Object privileges granted to the user.

USER_COL_PRIVS_MADE Object privileges granted on the columns of theuser’s objects.

USER_COL_PRIVS_RECD Object privileges granted to the user on specificcolumns.

Page 318: OCP - SQL&PL_SQL(Vol2)

������� ���� �� ��� ��� ��� ��� ������ ��� ��� ����� ������������

Page 319: OCP - SQL&PL_SQL(Vol2)

����������� �� � � �����

2�!�:��� �� � � ���!�����

Remove privileges granted to other users by using the REVOKE command. Whenyou use the REVOKE command, the privileges you specify are revoked from theusers you name, and from any other users to whom those privileges may have beengranted.

�(���,

REVOKE {privilege [, privilege...] | ALL}ON objectFROM {user[, user...]|role|PUBLIC}[CASCADE CONSTRAINTS]

where: CASCADE are required to remove any referential integrityCONSTRAINTS constraints made to the object by means of the

REFERENCES privilege.

SQL> REVOKE select, insert2 ON s_dept3 FROM scott;

Revoke succeeded.

For more information, seeOracle7 Server SQL Reference, Release 7.3, “REVOKE.”

Page 320: OCP - SQL&PL_SQL(Vol2)

������� ���� �� ��� ��� ��� ��� ������ ��� ��� ����� �����������"

Page 321: OCP - SQL&PL_SQL(Vol2)

����������� �� � � ����#

�������� � �(���(& 9�� �� �� � �

To refer to a table owned by another user, you need to prefix the table name with thename of the user who created it followed by a period. Creating a synonym eliminatesthe need to qualify the object name with the schema, and provides you with analternative name for a table, view, sequence, procedure, or other objects. This methodcan be especially useful with lengthy object names, such as views.

�(���,

CREATE [PUBLIC] SYNONYM synonymFOR object;

where: PUBLIC creates a synonym accessible to all users.

synonym is the name of the synonym to be created.

object identifies the object for which the synonym iscreated.

/��������

� The object cannot be contained in a package.

� A private synonym name must be distinct from all other objects owned by thesame user.

4,�&*��

As user Scott, create a private synonym named S_DEPT for Alice’s S_DEPT table.

SQL> CREATE SYNONYM s_dept2 FOR alice.s_dept;

Synonym created.

For more information, seeOracle7 Server SQL Reference, Release 7.3, “CREATE SYNONYM.”

Page 322: OCP - SQL&PL_SQL(Vol2)

������� ���� �� ��� ��� ��� ��� ������ ��� ��� ����� ������������

Page 323: OCP - SQL&PL_SQL(Vol2)

����������� �� � � ����'

�������� � �(���(& 9�� �� �� � � ���������

4,�&*��

Create a synonym for the DEPT_SUM_VU for quicker reference.

SQL> CREATE SYNONYM d_sum2 FOR dept_sum_vu;

Synonym created.

The DBA can create a public synonym accessible to all users.

SQL> CREATE PUBLIC SYNONYM s_dept2 FOR alice.s_dept;

Synonym created.

2�&�!� � �(���(&

To drop a synonym, use the DROP SYNONYM command. Only the DBA can drop apublic synonym.

4,�&*��

SQL> DROP SYNONYM s_dept;

Synonym dropped.

For more information, seeOracle7 Server SQL Reference, Release 7.3, “DROP SYNONYM.”

Page 324: OCP - SQL&PL_SQL(Vol2)

������� ���� �� ��� ��� ��� ��� ������ ��� ��� ����� �����������-

Page 325: OCP - SQL&PL_SQL(Vol2)

����������� �� � � ����.

��&&��(

DBAs establish initial database security for users by assigning privileges to the users.

� The DBA creates users who must have a password. The DBA is also responsiblefor establishing the initial system privileges for a user.

� Once the user has created an object, the user can pass along any of the availableobject privileges to other users or to all users by using the GRANT command.

� A DBA can create roles by using the CREATE ROLE command to pass along acollection of system or object privileges to multiple users. Roles make grantingand revoking privileges easier to maintain.

� Users can change their password by using the ALTER USER command.

� You can remove privileges from users by using the REVOKE command.

� DBAs can create public synonyms, and users can create private synonyms forconvenience by using the CREATE SYNONYM command. They permit shortnames or alternative names for objects. Remove synonyms by using the DROPSYNONYM command.

� Data dictionary views allow users to view the privileges granted to them and thatare granted on their objects.

Page 326: OCP - SQL&PL_SQL(Vol2)

������� ���� �� ��� ��� ��� ��� ������ ��� ��� ����� �����������0

Page 327: OCP - SQL&PL_SQL(Vol2)

����������� �� � � �����

��� �� � �!��!��$

Team up with other students for this exercise of controlling database object access.

��� �� � �������

� Granting other users privileges to your table

� Modifying another user’s table through the privileges granted to you

� Creating a synonym

� Querying the data dictionary views related to privileges

Page 328: OCP - SQL&PL_SQL(Vol2)

������� ���� �� ��� ��� ��� ��� ������ ��� ��� ����� ������������

Page 329: OCP - SQL&PL_SQL(Vol2)

����������� �� � � �����

��� �� � ��

1. What privilege should a user be given to log in to the Oracle7 Server? Is thisprivilege a system or object privilege?

2. What privilege should a user be given to create tables?

3. If you create a table, who can pass along privileges to other users on your table?

4. You are the DBA. You are creating many users who require the same systemprivileges. What would you use to make your job easier?

5. What command do you use to change your password?

6. Grant other users query access to your S_REGION table. Have them grant youquery access to their S_REGION table.

7. Query all the rows in your S_REGION table.

8. Add a new row to your S_REGION table. Team 1 should add Central America asregion number 6. Team 2 should add Micronesia as region number 7. Make thechanges permanent.

9. Query the other team’s S_REGION table.

10. Create a synonym for the other team’s S_REGION table.

11. Display the other team’s S_REGION table contents by using your synonym.

12. Confirm the privileges for your team’s tables.

13. Revoke the SELECT privilege from the other team.

14. Attempt to SELECT from the other team’s S_REGION table.

15. Drop the synonym you created.

Page 330: OCP - SQL&PL_SQL(Vol2)

������� ���� �� ��� ��� ��� ��� ������ ��� ��� ����� �����������"

Page 331: OCP - SQL&PL_SQL(Vol2)

������� �� � ��� � ����

��

Page 332: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� � ��� ��� ����� ��������� �����������

�����

!�"��

#������ $��

%�&

������� $��

Page 333: OCP - SQL&PL_SQL(Vol2)

������� �� � ��� � ���� ���'

������� �� � ��� � ����

The SQL and SQL*Plus module of the Introduction to Oracle course coveredrelational database concepts, the SQL command language, and SQL*Plus commandsto execute and format SQL commands.

(���"��� !����������

Concept Description

Table A table is the basic storage structure of an RDBMS, consistingof one or more columns and zero or more rows.

Row A row is a combination of column values in a table; forexample, the information about one department in the tableS_DEPT. A row is sometimes called a “record.”

Column A column represents one kind of data in a table; for example,the department name in the example table S_DEPT. It isdescribed with a column name and holds data of a specific typeand size.

Field At the intersection of a row and a column, you find a field. Thefield can contain data. If there is no data in the field, it is said tocontain a null value.

Primary key A primary key is the column or set of columns that uniquelyidentifies each row in a table; for example a departmentnumber. It must contain a value.

Foreign key A foreign key is a column or set of columns that refers to aprimary key in the same table or in another table. You createthem to enforce relational database design rules.

Page 334: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� � ��� ��� ����� ��������� ����������)

Page 335: OCP - SQL&PL_SQL(Vol2)

������� �� � ��� � ���� ���*

������� �� � ��� � ���� ���������

Structured Query Language, SQL*Plus, and PL/SQL commands are used to accessand manipulate data stored in an Oracle database.

� ����+ �+ ��� ���

Language or Tool Description

SQL A command language for communication with theOracle7 Server from any tool or application. OracleSQL contains many extensions.

SQL*Plus An Oracle tool that recognizes and executes SQL andPL/SQL statements and contains its own commandlanguage.

PL/SQL An Oracle procedural language for writing applicationlogic and manipulating data outside the database.

� �������

There are many commands available in SQL. The table below describes thecommands covered in this course.

Command Description

SELECT Retrieves data from the database. Most commonly usedcommand.

INSERTUPDATEDELETE

Enters new rows, changes existing rows, and removes unwantedrows from tables in the database, respectively. Collectivelyknown as Data Manipulation Language (DML) commands.

CREATEALTERDROPRENAMETRUNCATE

Sets up, changes, and removes data structures from tables.Collectively known as Data Definition Language (DDL)commands.

COMMITROLLBACKSAVEPOINT

Manage the changes made by DML statements. Changes to thedata can be grouped together into logical transactions.

GRANTREVOKE

Gives or removes access rights to both the Oracle database andthe structures within it. Collectively known as Data ControlLanguage (DCL) commands.

Page 336: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� � ��� ��� ����� ��������� ����������,

Page 337: OCP - SQL&PL_SQL(Vol2)

������� �� � ��� � ���� ����

������� �� � ��� � ���� ���������

������ (��� (���������

The data dictionary is a set of tables that the user can access through views. The datadictionary holds all the data about the database. Whenever the database is inoperation, the data dictionary is updated and maintained by the Oracle7 Server. Writea SELECT statement to view the contents of the data dictionary views.

The following are some frequently accessed data dictionary tables:

� DICTIONARY

� USER_OBJECTS

� OBJ (alias for USER_OBJECTS)

� USER_CONSTRAINTS

� USER_SEQUENCES

� ���� �������

SQL*Plus commands may be divided into the following main categories:

Category Purpose

Environment Affects the general behavior of SQL statements for thesession.

Format Formats query results.

File manipulation Saves, loads, and runs script files.

Execution Sends SQL or PL/SQL commands from SQL buffer toOracle7 Server.

Edit Modifies SQL commands in the buffer.

Interaction Allows users to create and pass variables to SQLstatements, print variable values, and print messages tothe screen.

Miscellaneous Various commands to connect to the database,manipulate the SQL*Plus environment, and displaycolumn definitions.

Page 338: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� � ��� ��� ����� ��������� ����������-

Page 339: OCP - SQL&PL_SQL(Vol2)

������� �� � ��� � ���� ���.

�������� �/��/��&

This practice has you build a set of database tables for a video application. Once youcreate the tables, you will insert, update, and delete records in a video store database,and generate a report. The database contains only the essential tables.

�������� �������

� Creating tables and sequences based on a database design

� Modifying data in the tables

� Modifying a table definition

� Creating a view

� Writing scripts containing SQL and SQL*Plus commands

� Generating a simple report

Note: If you want to build the tables, you can execute the buildtab.sql script inSQL*Plus. If you want to drop the tables, you can execute the dropvid.sqlscript in SQL*Plus. Then, you can execute the buildvid.sql script in SQL*Plusto create and populate the tables.

Page 340: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� � ��� ��� ����� ��������� �����������0

Page 341: OCP - SQL&PL_SQL(Vol2)

������� �� � ��� � ���� �����

�������� ��

1. Create the tables based on the entity relationship diagram on the previous pageand the table instance charts below. Choose the appropriate datatypes and be sureto add the integrity constraints.

a. Table name: MEMBER

ColumnName

MEMBER_ID

LAST_NAME

FIRST_NAME ADDRESS CITY PHONE JOIN_DATE

Key Type PK

Null/Unique

NN, U NN NN

DefaultValue

System date

Datatype number char char char char char date

Length 10 25 25 100 30 15

b. Table name: TITLE

Note: Do not create the PRICE column while creating the TITLE table. Youwould be modifying the TITLE table, in Exercise 7, to add the PRICEcolumn.

ColumnName

TITLE_ID TITLE

DESCRIP–TION RATING CATEGORY

RELEASE_DATE

Key Type PK

Null/Unique

NN, U NN NN

Check G, PG, R,NC17, NR

DRAMA,COMEDY,ACTION,CHILD, SCIFI,DOCUMENTARY

Default Value DRAMA

Datatype number char char char char date

Length 10 60 400 4 20

Page 342: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� � ��� ��� ����� ��������� ������������

�������� �� ���������

1.—continued

c. Table name: TITLE_COPY

ColumnName COPY_ID TITLE_ID STATUS

Key Type PK PK, FK

Null/Unique

NN, U NN, U NN

Check AVAILABLE, DESTROYED, RENTED,RESERVED

FK Ref Table title

FK Ref Col title_id

Datatype number number char

Length 10 10 15

d. Table name: RENTAL

ColumnName

BOOK_DATE

MEMBER_ID COPY_ID

ACT_RET_DATE

EXP_RET_DATE TITLE_ID

Key Type PK FK PK, FK PK, FK

Null/Unique

NN,U NN NN,U NN,U

DefaultValue

Systemdate

2 days afterbook date

FK RefTable

member title_copy title_copy

FK Ref Col member_id copy_id title_id

Datatype date number number date date number

Length 10 10 10

Page 343: OCP - SQL&PL_SQL(Vol2)

������� �� � ��� � ���� ����'

�������� �� ���������

1.—continued

e. Table name: RESERVATION

Column Name RES_DATE MEMBER_ID TITLE_ID

Key Type PK PK, FK PK, FK

Null/Unique NN,U NN,U NN,U

FK Ref Table member title

FK Ref Col member_id title_id

Datatype date number number

Length 10 10

2. Verify that the tables and constraints were created properly by checking the datadictionary.

3. Create sequences to uniquely identify each row in the MEMBER table and theTITLE table.

a. Member number for the MEMBER table, start with 101, do not allow cachingof the values.

b. Title number for the TITLE table, start with 92, no caching.

c. Verify the existence of the sequences in the data dictionary.

Page 344: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� � ��� ��� ����� ��������� �����������)

�������� �� ���������

4. Add data to the tables. Create a script for each set of data to add.

a. Add movie titles to the TITLE table. Write a script to enter the movieinformation. Save the script as p17q4a.sql. Use the sequence to uniquelyidentify each title. Remember that single quotation marks in a character fieldmust be specially handled. Verify your additions.

Title Description Rating Category Release date

Willie andChristmasToo

All of Willie’s friends made aChristmas list for Santa, butWillie has yet to add his ownwish list.

G CHILD 05-OCT-95

Alien Again Yet another installment ofscience fiction history. Canthe heroine save the planetfrom the alien life form?

R SCIFI 19-MAY-95

The Glob A meteor crashes near asmall American town andunleashes carnivorous goo inthis classic.

NR SCIFI 12-AUG-95

My Day Off With a little luck and a lot ofingenuity, a teenager skipsschool for a day in NewYork.

PG COMEDY 12-JUL-95

Miracles onIce

A six-year-old has doubtsabout Santa Claus. But shediscovers that miracles reallydo exist.

PG DRAMA 12-SEP-95

Soda Gang After discovering a cache ofdrugs, a young couple findthemselves pitted against avicious gang.

NR ACTION 01-JUN-95

Page 345: OCP - SQL&PL_SQL(Vol2)

������� �� � ��� � ���� ����*

�������� �� ���������

4.—continued

b. Add data to the MEMBER table. Write a script named p17q4b.sql to promptusers for the information. Execute the script. Be sure to use the sequence toadd the member numbers.

Firstname Last name Address City Phone Join date

Carmen Velasquez 283 KingStreet

Seattle 206-899-6666 08-MAR-90

LaDoris Ngao 5Modrany

Bratislava 586-355-8882 08-MAR-90

Midori Nagayama 68 ViaCentrale

Sao Paolo 254-852-5764 17-JUN-91

Mark Quick-To-See 6921 KingWay

Lagos 63-559-7777 07-APR-90

Audry Ropeburn 86 ChuStreet

HongKong

41-559-87 18-JAN-91

Molly Urguhart 3035LaurierBlvd

Quebec 418-542-9988 18-JAN-91

Page 346: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� � ��� ��� ����� ��������� �����������,

�������� �� ���������

4.—continued

c. Add the following movie copies in the TITLE_COPY table:

Title Copy number Status

Willie and Christmas Too 1 Available

Alien Again 1 Available

2 Rented

The Glob 1 Available

My Day Off 1 Available

2 Available

3 Rented

Miracles on Ice 1 Available

Soda Gang 1 Available

d. Add the following rentals to the RENTAL table:

TitleCopynumber Customer Date rented

Date returnexpected

Datereturned

92 1 101 3 days ago 1 day ago 2 days ago

93 2 101 1 day ago 1 day fromnow

95 3 102 2 days ago Today

97 1 106 4 days ago 2 days ago 2 days ago

5. Create a view named TITLE_AVAIL to show the movie titles and the availabilityof each copy and its expected return date if rented. Query all rows from the view.

Page 347: OCP - SQL&PL_SQL(Vol2)

������� �� � ��� � ���� �����

�������� �� ���������

6. Make changes to data in the tables.

a. Add a new title. The movie is “Interstellar Wars”, which is rated PG, andclassified as a SCIFI movie. The release date is 07-JUL-77. The description is“Futuristic interstellar action movie. Can the rebels save the humans from theevil Empire?” Be sure to add a title copy record for two copies.

b. Enter two reservations. One reservation is for Carmen Velasquez who wantsto rent “Interstellar Wars.” The other is for Mark Quick-To-See who wants torent “Soda Gang”.

c. Customer Carmen Velasquez rents the movie “Interstellar Wars”, copy 1.Remove her reservation for the movie. Record the information about therental. Allow the default value for the expected return date to be used. Verifythe rental was recorded by using the view you created.

7. Make a modification to one of the tables.

a. Add a PRICE column to the TITLE table to record the purchase price of thevideo. The column should have a total length of eight digits and two decimalplaces. Verify your modification.

b. Create a script named p17q7b.sql to update each video with a price accordingto the following list:

Title Price

Willie and Christmas Too 25

Alien Again 35

The Glob 35

My Day Off 35

Miracle on Ice 98

Soda Gang 35

Interstellar Wars 29

c. Ensure that in the future all titles will contain a price value. Verify theconstraint.

8. Create a report titled Customer History Report. This report will contain eachcustomer’s history of renting videos. Be sure to include the customer name,movie rented, dates of the rentals, and duration of rentals. Count up the totalnumber of rentals for all customers for the reporting period. Save the script in afile named p17q8.sql.

Page 348: OCP - SQL&PL_SQL(Vol2)

������������ �� ������� � ��� ��� ����� ��������� �����������-


Recommended