Sie sind auf Seite 1von 40

C H A P T E R

Schema Manager for Tables

7
3 3

In This Chapter
Defining Columns Examining datatypes Using Security Manager for creating Tables Modifying an existing Tables structure Adding relationships and other Constraints Creating Indexes

F
See Reference Section

inally, Oracle has a tool that makes creating Tables, Indexes, Constraints, and relationships easy!

This chapter explores how you use Schema Manager to create Tables and Indexes, assign Primary and Foreign Keys, and control Constraints. Like many of the other Enterprise Manager tools, the Schema Manager generates and runs SQL code. You can also save the SQL for later use. Whenever a task described here has an equivalent SQL command, there will be a reference to the command in other parts of this book. Watch for the See Reference icon in the margin, like the one you see next to this paragraph.

Tables
Tables are the cornerstone of a relational database. Now that Oracle8 is a hybrid (or Object-relational) database, you have additional Objects with which to store information in the database: Objects and Object-Tables. First, lets examine a few important concepts regarding columns and null values. I present these concepts in the next two subsections, followed by step-by-step instructions on using the Schema Manager to create and modify Tables.

Defining Columns in Oracle8


Oracle8 needs Tables, and Tables need Columns. Even if a Table contains no rows, it must have Columns. When creating Columns, youll want to consider names, datatypes, and null values.

148

Chapter 7 3 Schema Manager for Tables

Oracle8 enforces the same naming convention for Columns, Tables, Indexes, and other database Objects. This section details Column datatypes and null values in your data.
See Reference Section

DATATYPE

Columns are defined during the process of creating a new Table in the database. You must name the Column; then you tell Oracle8 what kind of data goes into the Column by specifying the datatype of the Column. Table 7-1 shows all your choices when you define Columns in Oracle8. You may want to mark the table for later reference.

Table 7-1 Oracle8 Datatypes


Datatype BFILE BLOB CHAR(n) CLOB DATE Parameters none none n=1 to 255 none none Description Large binary Object (LOB) stored outside the database. Maximum size is 4GB. LOB with 4GB maximum size. String with fixed length. The default length is 1. Specify the maximum length (n) when defining the Column. LOB with 4GB maximum size. Valid dates range from January 1, 4712 B.C., to December 31, 4712 A.D. Oracle8 stores DATE internally as a seven-byte number and, by definition, also includes the time in hours, minutes, and seconds. Binary number. Specify the precision (n), which is the number of digits. Text string with variable length. Maximum length is 2GB LONG is for large amounts of data. Raw binary data of variable length. The maximum length is 2GB. Binary format of a label used on a secure operating system. This datatype is used only with Trusted Oracle to mediate access to information. See CHAR. The NCHAR(n) has the same attributes except it stores Characters that depend on a national character set (Chinese characters, for example). Oracle8 supports many languages this way. LOB with 4GB maximum size.

FLOAT(n) LONG LONG RAW MLSLABEL

p=1 to 126 none none none

NCHAR(n)

n=1 to 2,000

NCLOB

none

Chapter 7 3 Tables

149

Datatype NUMBER(p,s)

Parameters p=1 to 38, s= -84 to 127, or FLOAT number n=1 to 4,000

Description Specify the precision (p), which is the number of digits, and the scale (s), which is the number of digits to the right of the decimal place. See VARCHAR. The NVARCHAR2 has the same attributes except it stores characters for any language (national character set) supported by Oracle8. Raw binary data of variable length. You must specify the maximum length (n) when defining the Column. Hexadecimal format identical to the format of the Pseudocolumn rowID. Text string with variable length. Specify the maximum length (n) when defining the Column. This is an obsolete data type provided only to support older Oracle databases. Text string with variable length. You must specify the maximum length (n) when defining the Column.

NVARCHAR2(n)

RAW(n) ROWID VARCHAR(n)

n=1 to 255 none n=1 to 4,000

VARCHAR2(n)

n=1 to 4,000

The most common datatypes are VARCHAR2, DATE, and NUMBER. The CHAR datatype is frequently used for coded data of a constant length, such as state abbreviations. The other datatypes are rather specialized and infrequently used unless youre creating a database with delivery-on-demand music CD selections or other fun elements.

What is null?
When the Column of a row has no data, Oracle8 describes the Column as null or having a null value. The most appropriate use for null value is when you do not know the value of the data. For example, a Table that lists magazine subscribers may have a null value (no data) in the SUBSCRIBER_AGE Column of the row for a current subscriber. This value signifies you do not know the age of the subscriber. Oracle8 allows null values in Columns of all datatypes. Oracle8 only disallows null values in two cases: 3 Primary Key Columns 3 Any Column defined with the NOT NULL Constraint Heres another example of a null value. You have a checkbook register Table for your home business. One Column is called CLEARED_FLAG. The Column is null when you insert a record for a check you wrote recently. You update the rows CLEARED_FLAG to YES when you reconcile your bank statement with the register

150

Chapter 7 3 Schema Manager for Tables

and find a paid check. You dont know when a check clears your account until you receive your statement. Imagine check number 2001 just cleared your account. Your check register has no value (null) in the row for check number 2001, yet the check cleared. Therefore, when the check register CLEARED_FLAG Column has a null value, it could mean that the check has not cleared or has cleared unbeknownst to you. The lack of data (null value) indicates the state of the CLEARED_FLAG Column for check number 2001 is unknown at this time. Do not use null to represent zero. Zero is a known quantity. You can add, subtract, and generally use zero in calculations. You cannot add, subtract, or use null values in calculations. When you add a null to ten, the results equal null. To repeat: Add an unknown quantity to ten, and you get another unknown quantity. Nulls do not equal nulls or any other value. For example, even with a null value in the SELLING_PRICE Column and a null value in the WHOLESALE_PRICE, the following WHERE clause evaluates as false when both Columns contain null values:
... WHERE SELLING_PRICE = WHOLESALE_PRICE

How do you compare two null Columns? Use the NVL function to convert the null value to a number or character string. For example, the following WHERE clause evaluates as true when both Columns contain null values:
... WHERE NVL(SELLING_PRICE, -1) = NVL(WHOLESALE_PRICE, -1)

When using the preceding technique, be careful to use a default value (in the example, -1) that is not equal to any values in the Column. Otherwise, you will not get the desired effect of comparing a null value with another null value. A second way to check for null values in a WHERE clause uses the IS Null and IS NOT Null phrases. These two phrases are special operators for null values. For example, the following clause evaluates as true when the SELLING_PRICE Column contains a null value:
... WHERE SELLING_PRICE IS Null

Likewise, Oracle8 evaluates the following statement as false when the SELLING_PRICE Column contains a null value:
... WHERE SELLING_PRICE IS NOT Null
CrossReference

Suppose you want to define the Column to disallow Nulls. Just add the NOT NULL Constraint to the Column when creating the Table (see the next section).

Chapter 7 3 Tables

151

Creating a new Table


All Tables are owned by an Oracle User. The resource Role must be assigned to the Oracle8 User that creates Tables. A default Tablespace is also assigned during User creation. All Tables are assigned to a Tablespace upon creation. If no Tablespace is named, the Users default Tablespace receives the Table. You can use the Storage Manager to create a new Tablespace or allocate additional space to the Tablespace.
See Reference Section CrossReference

See the Storage Manager section in Chapter 5 for more information.

CREATE TABLESPACE

You can also create a Tablespace using SQL. See the Command Reference for more details. The following example scenario illustrates this chapters concepts and instructions for creating Tables, relationships, Indexes, and Constraints. The scenario is a database for tracking the animals bred and raised in a sea life park. The database tracks each animal and its medical checkups. A database Schema is created under the Username SEAPARK. The database contains six Tables: 3 TANK. Stores information about each of the aquatic habitats in the park. 3 AQUATIC_ANIMAL. Contains one row for each animal, regardless of the habitat in which it lives. 3 CHECKUP_HISTORY. Lists each medical exam that a creature receives. 3 CHECKUP_TYPE. Describes the types of checkups. Each medical checkup falls into one CHECKUP_TYPE reference Table. The type of checkup determines what tests and measurements you undertake. 3 CARETAKER. Lists the caretakers that handle the animals. 3 PARK_REVENUE. Accounts income and outgo for the Sea Park. Figure 7-1 shows the SEAPARK Tables and their corresponding relationships.

152

Chapter 7 3 Schema Manager for Tables

CARETAKER CARETAKER_NAME

TANK TANK_NO CHIEF_CARETAKER_NAME (fk)

CHECKUP CHECKUP_TYPE

AQUATIC_ANIMAL ID_NO TANK_NO (fk) PARK_REVENUE CHECKUP_HISTORY CHECKUP_TYPE ID_NO ACCOUNT_NO

Figure 7-1: Sample Tables used in this chapter track sea life in an aquatic park.

See Reference Section

CREATE TABLE Here are the steps for using Schema Manager to create a Table. This sequence creates the CHECKUP_HISTORY Table in the chapters sample schema, but you can apply these steps to create your own Tables. 1. Start Schema Manager and log in as the DBA. Click the Schema Manager icon (which looks like a small three-Table diagram) in the Enterprise Manager toolbar. Schema Manager prompts you to log in. After logging in, you see the main window of the Schema Manager. 2. Choose Object Create. The Create Object dialog box appears, as illustrated in Figure 7-2. 3. Select Table and then click OK. The next window prompts you to select a method for creating the Table, as shown in Figure 7-3. 4. Choose the Create Table Manually option button and then click OK. Use the manual method when you are familiar with creating Tables. If you are new to Oracle, use the wizard. 5. Name the Table. Click the Name box and then type the name of the Table. Create a Table named CHECKUP_HISTORY for the example. Figure 7-4 shows the Create Table dialog box.

Chapter 7 3 Tables

153

Figure 7-2: Select Table in this window to create a new Table.

Figure 7-3: Choose the option to create the Table manually.

154

Chapter 7 3 Schema Manager for Tables

Figure 7-4: Defining the CHECKUP_HISTORY Table

6. Select the Schema. Click the arrow and select one of the available Schema. The selected Schema is the Table Owner. For the example, select SEAPARK. 7. Select the Tablespace (optional). Click the Tablespace selection arrow for a list of available Tablespaces. When you select Default, the Table is placed into the default Tablespace of the User named in the Schema box. 8. Define Columns. Follow these steps to define your Columns: a. Type the Column name in the Name textbox. b. Select a datatype in the datatype Column. c. Type the Column length. d. For Columns with Number datatype, you can define the number of decimal places allowed (optional). Type a number in the Precision box. e. Use the tab key or the draw bar to reveal the remaining Column parameters. f. Click the Nulls box to activate Nulls Allowed (optional). g. Type a Default Value (optional). The Default Value is assigned to the Column for all new rows where the Column Value would otherwise be Null. Figure 7-5 shows the defined Columns for the CHECKUP_HISTORY Table.

Chapter 7 3 Tables

155

Figure 7-5: The CHECKUP_HISTORY Table has several Columns.

9. Add more Columns as needed.


Tip

To add a Column in between other Columns, select the button next to the adjacent Column where you want to add a Column. The Column changes to a blue background. Then right-click the Column. Next select Insert Above or Insert Below. A row opens for a new Column. To remove a Column, click the button next to the Column. The Column changes to a blue background. Then right-click on the Column. Next select Delete. The Column is removed. 10. Define a Primary Key (optional). If you want to create a Primary Key for the Table, click the Constraints tab. The Constraints window is displayed. a. Type in a name for the Primary Key Constraint (optional). b. Select Primary from the Type list. c. In the lower portion of the window, click the arrow in the Table Columns box. Select the Primary Key Column or Columns. Figure 7-6 displays a Primary Key named CHK_HST_PK defined for the CHECKUP_NO Column.

156

Chapter 7 3 Schema Manager for Tables

Name Primary Key here

Select Primary Key Columns here

Figure 7-6: Define a Primary Key in the Constraints tab.

11. Click the Storage tab (optional). Here you have a choice of defining the exact storage parameters (Explicit button) or letting Schema Manager calculate the storage parameters for you (Auto Calculation button). Select the appropriate option and then complete the information. Figure 7-7 shows the window you see after you select the Auto Calculation button. Using this option, you define the number of rows and the growth and kind of activity. Schema Manager bases its calculations on this information and the Column definitions. 12. Click the Create button to complete the creation process. The Table is created by the Schema Manager and appears in the list of Tables, as shown in Figure 7-8. 13. Refresh your view if you do not see the new Table listed. Choose View Refresh to refresh the Schema Managers list of Tables (see Figure 7-8 ) You should now see your new Table in the List.

Chapter 7 3 Tables

157

Figure 7-7: Define the storage parameters for your Table.

Figure 7-8: The new Table appears in the list of Tables in Schema Managers main window.

158

Chapter 7 3 Schema Manager for Tables

Where to find other Table parameter information


Figure 7-9 illustrates the chapters that discuss each area of the Table Definition window.

Chapter 7 (SQL in Chapter 12) Chapter 22 Chapter 23

Figure 7-9: Here is a quick reference to chapters with more information about Table parameters. This chapter shows you how to create a Table and set up Constraints using the Schema Manager. Chapter 12 shows you how to create a Table and set up Constraints using SQL commands. To add a new Primary Key, Foreign Key, or other Constraint after defining a Table, see the following Constraints section in this chapter. Chapter 22 provides information on how to define a cluster Table with cluster Columns. Chapter 23 discusses partitioned Tables (a new Oracle8 feature).

Chapter 7 3 Tables

159

Tip

Some designers arrange Columns in alphabetical order while others arrange Columns in a logical order (name, address, city, state, and so forth). If you use SQL*Forms or other tools that generate data-entry screens, arrange the Columns (except the Primary Key, which should be on top) in the order entered by the end User. Screen-building tools often arrange the data-entry screen Columns in the same order as the database Table Columns.

Changing Columns in a Table


In Oracle8, you can easily add new Columns to a Table. Other changes, such as removing a Column or modifying the datatype of a Column, are more difficult. Table 7-2 outlines the types of structure changes and corresponding sections with step-by-step instructions.

Table 7-2 Where to Find Instructions for Revising Column Specifications in a Table
Change Lengthen a Column Change not null to nulls allowed Data in Column? N/A N/A Tool(s) Schema Manager Schema Manager Schema Manager Schema Manager and SQL Worksheet Schema Manager Schema Manager Schema Manager and SQL Worksheet Schema Manager Schema Manager and SQL Worksheet Schema Manager and SQL Worksheet Section Adjusting Table structure Adjusting Table structure Adjusting Table structure Adjusting Table structure while adding default Column data Adjusting Table structure Adjusting Table structure of Column Adjusting Table structure while preserving Column data Adjusting Table structure Adjusting Table structure while preserving Adjusting Table structure by recreating Table

Change nulls allowed Yes (all rows have to not null data) Change nulls allowed No (some or all to not null rows have nulls) Add a Column at end of Table Change datatype Change datatype of Column Shorten Column Shorten Column Column data Remove a Column N/A No Yes

No Yes N/A

160

Chapter 7 3 Schema Manager for Tables

Table 7-2 (Continued)


Change Rename a Column Add Column in the middle Reorder Columns Data in Column? N/A N/A N/A Tool(s) Schema Manager and SQL Worksheet Schema Manager and SQL Worksheet Schema Manager and SQL Worksheet Section Adjusting Table structure by recreating Table Adjusting Table structure by recreating Table Adjusting Table structure by recreating Table

The final four changes in Table 7-2 require extra work: when recreating a Table, you must preserve and then restore all Objects connected to the Table. For example, you must save and restore Foreign Key connections defined in other Tables.

Adjusting Table structure


See Reference Section

ALTER Table This section shows you how to make Table changes without special handling of your Tables data. Regardless of the data in your Table, you can make the following changes at any time: 3 Lengthen a Column. 3 Change not null to nulls allowed. 3 Change nulls allowed to not null. All rows must have data in the Column to be changed. 3 Add a Column at end of Table. 3 Change datatype of Column. All rows must have null value in the Column to be changed. 3 Shorten Column. All rows must have null value in the Column to be changed. See Table 7-2 to find the appropriate section for other Table changes. All Table structure changes are made in the Table General Properties box. The following steps illustrate how to access the Table General Properties box and adjust your Table: 1. Start the Schema Manager and log in as the DBA. 2. Double-click the Table icon in the left frame. A list of Schemas appears below the icon in the left frame and a list of all Tables in all Schemas appears in the right frame.

Chapter 7 3 Tables

161

3. Double-click the Schema that owns the Table you want to change. 4. Click the Table that needs adjustment. The properties window for the Table appears in the right frame. 5. Type the changes. To change Column length, for example, type the appropriate length in the Length box of the chosen Column. Figure 7-10 shows the AQUATIC_ANIMAL Table and illustrates where the six types of changes are made.
Change Datatype Lengthen Shorten

Add column to end of the table Null to Not Null Not Null to Null

Figure 7-10: Modify Table structure in the Tables General Propertieswindow of the Schema Manager.

6. Click the Apply button to commit the changes. Schema Manager makes the change. If you dont receive an error message, your change is committed to the database.

162

Chapter 7 3 Schema Manager for Tables

Adjusting Table structure while preserving Column data


See Reference Section

CREATE TABLE INSERT ALTER TABLE DROP TABLE This section shows you how to make Table changes that require the removal of Column data. The changes covered here are: 3 Change datatype of Column 3 Shorten Column If you have data in any row of the Column you want to change, you must first eliminate the data in this Column for all rows in your Table. If you make the change before removing the data, you receive one of these error messages:
ORA-01439: column to be modified must be empty to change Datatype ORA-01441: column to be modified must be empty to decrease column length

To fix the data, either remove the data permanently or preserve the data and restore it after the change. If you choose not to preserve the data, simply update the Table and then follow the instructions in the preceding Adjusting Table structure section. If you choose to preserve the data, follow these general steps: 1. Create a new Table containing the Primary Key and the Column to be preserved. 2. Insert data from the existing Table to be changed into the new Table. 3. Modify the existing Table structure. 4. Update the existing Table with the data saved in the new Table.
Example

The step-by-step instructions to perform all four steps listed above are presented below. To illustrate the steps, the sample Table (TANK) has its Column (CHIEF_CARETAKER) length changed from 60 characters to 50 characters. 1. Start SQL Worksheet and log in as the Table Owner. 2. Create and populate a new Table for holding the data. The Table must contain the original Tables Primary Key Column(s) and the Column to be changed. The following SQL command creates a Table with the Primary Key (TANK_NO) and the Column to be changed (CHIEF_CARETAKER_NAME). This command creates the Table and inserts the data in one step.

Chapter 7 3 Tables

163

CREATE TABLE HOLD_TANK AS SELECT TANK_NO, CHIEF_CARETAKER_NAME FROM TANK;

After it creates the Table, Oracle8 replies:


Statement Processed.

3. Update the original Table so all rows contain null values in the Column to be changed. The following SQL command updates the CHIEF_CARETAKER_ NAME of the TANK Table.
UPDATE TANK SET CHIEF_CARETAKER_NAME = Null;

Oracle8 complies and tells you how many rows were updated:
4 rows Updated.

Commit the change.


COMMIT

4. Modify the length or datatype of the Column. Use Schema Manager or SQL Worksheet for this step.
Note

If you choose Schema Manager, follow the steps in the preceding Adjusting Table Structure section. If you choose SQL Worksheet, write an alter Table command to modify the Table. (See Chapter 11 for further details). The following SQL command modifies the TANK Table.
ALTER TABLE TANK MODIFY (CHIEF_CARETAKER_NAME VARCHAR2(50))

CrossReference

5. Copy the data back in the newly-modified Column. The following SQL command completes this procedure for the TANK example.
UPDATE TANK SET CHIEF_CARETAKER_NAME = (SELECT CHIEF_CARETAKER_NAME FROM HOLD_TANK WHERE HOLD_TANK.TANK_NO = TANK.TANK_NO)

Oracle8 complies and tells you how many rows were updated:
4 rows Updated.

Commit the change.


COMMIT
CrossReference

To learn more about the correlated subquery (used in the above SQL command), see the Correlated Subqueries section in Chapter 9. 6. Remove the Table created to hold the data. The last task is important: remove the holding Table. The following SQL Command removes the HOLD_TANK Table created in step two.
DROP TABLE HOLD_TANK

164

Chapter 7 3 Schema Manager for Tables

Oracle8 replies:
Table Dropped.

Adjusting Table structure while adding default data


See Reference Section

UPDATE ALTER TABLE One Column change requires that every row contain data in the Column to be changed changing a Column from nulls allowed to not null. If you try to add the not null constraint to a Column in which some rows contain null values, Oracle8 sends the following error message:
ORA-02296: cannot Enable ... Null Values found.

The following general steps modify the Table structure: 1. Populate the rows where the Column is null with a default value. 2. Change the Table structure. The exact data you place into the Column depends on your individual circumstances.
Example

To illustrate the steps involved, modify the CHECKUP Table, changing the MEASURE_WEIGHT_FLAG Column to not null, and complete the following steps. 1. Log in to SQL Worksheet as the Table Owner. 2. Update rows containing null values in the Column to be changed. The following SQL command updates MEASURE_WEIGHT_FLAG so that null values are changed to N
UPDATE CHECKUP SET MEASURE_WEIGHT_FLAG = N WHERE MEASURE_WEIGHT_FLAG IS NULL

Oracle8 replies:
Statement Processed.

Commit the change.


COMMIT

Chapter 7 3 Tables

165

3. Modify the Column to not null. Here you have two choices: Schema Manager or SQL Worksheet. If you choose Schema Manager, follow the steps shown in the preceding Adjusting Table Structure section. If you choose SQL Worksheet, write an alter Table command to modify the Table.
CrossReference

See the Chapter 12 section Adjusting Table structure for more details on how to write the Alter Table command. Use the following SQL command to modify the CHECKUP Table:
ALTER TABLE CHECKUP MODIFY (MEASURE_WEIGHT_FLAG NOT NULL)

The next section covers the most difficult type of Table alteration.

Adjusting Table structure by re-creating Table


See Reference Section

CREATE TABLE DROP TABLE CREATE TABLE INSERT The most involved type of Table alterations are the changes Oracle8 doesnt allow. You must remove and re-create the entire Table to perform the following alterations: 3 Remove a Column 3 Rename a Column 3 Add Column in the middle 3 Reorder Columns Oracle8s great storage efficiency and retrieval speed have a cost: you cannot change certain parts of a Table structure without a complete rebuild of the Table.

Caution

You lose many Objects (Indexes, Foreign Key Constraints) connected to a Table when you drop the Table. Consider the serious ramifications before making cosmetic changes, such as rearranging the order of Columns. The general steps in this process follow: 1. Make a copy of the Table to preserve existing data. 2. Review all related Objects and preserve scripts to restore them. 3. Drop the Table. 4. Create the Table with new structure. 5. Insert data back into the Table. 6. Restore all related Objects. 7. Drop the copy of the Table.

166

Chapter 7 3 Schema Manager for Tables

Removing a Table causes the loss of other Objects related to the Table
One of the steps in this section removes a Table from the database. When you remove a Table, you also remove other important database Objects that depend on the Table: 3 Any Indexes you created on the Table are dropped and must be re-created. 3 Any Foreign Keys in other Tables that refer to this Tables Primary Key are also deleted. 3 Any privileges you granted on the Table are lost and must be restored. A view that uses the dropped Table stays in the database. The view, however, is rendered invalid when you drop the Table. Furthermore, when you restore the Table, the view may become valid again or remain invalid. It remains invalid if the newly-modified Table cannot be used in the view. For example, if a Column named in the view is removed, the view is invalid and must be corrected to reflect the change.

Example

To illustrate the many steps involved in the task, I use the sample AQUATIC_ANIMAL Table. The following steps insert a new Column, MARKINGS_DESCRIPTION, after the ANIMAL_NAME Column. To restructure a Table by using Schema Manager, follow these steps: 1. Start the Schema Manager and log in as the DBA. 2. Select the Table to be modified. Double-click the Table folder in the left frame. Then double-click the Schema that owns the Table you want to change. Next click the Table to be restructured. The General properties window for the Table appears in the right frame. Figure 7-11 shows the General properties tab of the AQUATIC_ANIMAL Table. 3. Click the Create Like button. Located in the toolbar, the button has two green shapes on it. The Create Table box appears as shown in Figure 7-12. 4. Fill in the Name box. For the example, the name of the new Table is HOLD_AQUATIC_ANIMAL. 5. Select the Default Tablespace. Click the arrow at the end of the Tablespace box and choose Default. Important: this option is the only operative option when you create a new Table using the Define Query option. 6. Click the Define Query radio button. Schema Manager displays the message box shown in Figure 7-13. Click Yes. The window where you ordinarily define your Columns turns into a blank box, where you type a query instead.

Chapter 7 3 Heading 1

167

Figure 7-11: Preparing to modify a Table in Schema Manager

Figure 7-12: The Create Table properties box contains information from the old Table when you click the Create Like button.

168

Chapter 7 3 Schema Manager for Tables

Figure 7-13: Schema Manager sends a warning message when you click on the Define Query button.

7. Click the box and type the Query. This query defines the data loaded into the new Table during creation. The query also defines the Columns for the new Table. To copy all the rows and Columns from the old Table to the new Table, use a query like the following:
SELECT * FROM OWNER.TABLENAME

Replace OWNER with the Schema of the Table you want to copy. Replace TABLENAME with the name of the Table to copy. In the example, the query is:
SELECT * FROM SEAPARK.AQUATIC_ANIMAL

8. Click the Constraints tab. Clicking the Constraints tab brings in all the Constraints from the old Table. Schema Manager automatically creates the Constraints, but does not copy the Constraint Names because Constraint names must be unique within the Schema. Oracle8 uses a system-generated name for each Constraint. 9. Click the Create button. Schema Manager automatically creates the Table and the Constraints, copies all the data, and returns you to the original Tables property window. 10. Record all related Objects to be restored. Find all related Objects to be removed when you drop the Table. Record them so they can be restored later. Use your own method for documenting each Object. Some methods include: Query the Data Dictionary views and generate commands to re-create the Objects. See Appendix C for example query code.

Chapter 7 3 Heading 1

169

Use Schema Manager to display SQL commands that create the Objects and copy and paste the SQL into files for later use. Write down the Objects and re-create them using Schema Manager. The following Objects should be recorded: Indexes on this Table. Foreign Keys on other Tables that reference this Table. Triggers on this Table. Partitions on this Table. Snapshot Logs on this Table. Grants to Roles or Users on this Table. 11. Click the Remove button. The button looks like a red X. Schema Manager asks for verification as shown in Figure 7-14.
Caution

You cannot roll back or undo the act of dropping a Table.

Click here to drop table

Figure 7-14: Verify the Table name and click Yes to drop a Table.

12. Verify the Table name and click Yes. When you remove the Table, Schema Manager returns to its main menu. 13. Select the Table you just created. 14. Click the Create Like button.

170

Chapter 7 3 Schema Manager for Tables

15. Type the old Table name in the Name box. This action re-creates the Table you removed. In the example, the Table name is AQUATIC_ANIMAL. 16. Select the Tablespace (optional). Click the arrow at the end of the Tablespace box and select a Tablespace. 17. Make adjustments in the Columns, as needed. To remove a Column: Click the gray box just to the left of the name of the Column you want to remove. This action highlights the entire Columns definition. Right-click and choose Delete from the submenu. To add a Column between two Columns: Click the gray box just to the left of the name of the Column where you want to insert the new Column. Right-click and choose Insert Above or Insert Below to open a new row where you can specify the new Columns definition. To change a Column, type over the existing attributes. To add a Column at the end, type in the open row below the last Column. Figure 7-15 shows the new AQUATIC_ANIMAL Table structure with the new Column, MARKINGS_DESCRIPTION.

Figure 7-15: Adjust the Table structure here.

Chapter 7 3 Primary Keys

171

18. Click the Constraints tab. This action brings up the list of Constraints you copied from your original Table. The names are system-generated Names that Oracle8 uses. 19. Make adjustments in the Constraints as needed. If you made changes in any of the Columns involved in the Constraints, verify the Constraints are still valid. 20. Click Create. Schema Manager creates your new Table. 21. Start SQL Worksheet and log in as the Table Owner. 22. Write an Insert command to add the data from the copy of the old Table to the new Table.
CrossReference

See Chapter 10 for details on writing the Insert command. The following Insert command is used for the example.
INSERT INTO AQUATIC_ANIMAL (ID_NO, TANK_NO, ANIMAL_NAME, BIRTH_DATE, DEATH_DATE) SELECT ID_NO, TANK_NO, ANIMAL_NAME, BIRTH_DATE, DEATH_DATE FROM AQUATIC_ANIMAL_HOLD

23. Run your command by clicking the Execute button. Oracle8 replies with the number of rows processed:
3 rows Created.

24. Commit your changes.


COMMIT

Click the Execute button to commit the inserted rows. 25. Close SQL Worksheet. Click the X in the top-right corner. 26. Restore all related Objects. Re-create Foreign Keys, Indexes, Triggers, grants, and so forth. 27. Remove the holding Table. Use Schema Manager or SQL Worksheet to drop the holding Table. In the example, drop the AQUATIC_ANIMAL_HOLD Table. 28. Verify the Table name and click Yes. This verification completes the process.
CrossReference

If you prefer to use SQL commands without Schema Manager, refer to Chapter 12, which depicts the same scenario using only SQL commands.

Primary Keys
When you name a Column or set of Columns as the Primary Key, Oracle8 automatically creates an Index on that Primary Key. The Index enforces the uniqueness rule for the Primary Key and also allows fast retrieval of rows using the Primary Key value.

172

Chapter 7 3 Schema Manager for Tables

CrossReference

You can define the Primary Key for a Table during or after creation of a Table. The Creating a new Table section in this chapter shows how to add a Primary Key during the creation of a new Table. This section shows how to add or remove a Primary Key to an existing Table. You cannot successfully create a new Primary Key unless all rows have a unique value in the Column or Columns that make up the Primary Key. If you install the sample Tables included on the CD-ROM, you can perform the stepby-step instructions on the sample Tables. Appendix B has instructions on how to install the Tables.

Tip

On the CD-ROM

Creating a new Primary Key


The process of adding a Primary Key was already illustrated in the section on creating a new Table. The steps specific to creating a new Primary Key are repeated here as a convenient reference. You can easily add a Primary Key by using Schema Managers Table window. The Constraints tab of the Table window has selections for Primary Key, as shown in Figure 7-16. Follow these steps to add a Primary Key with the Schema Manager.
See Reference Section

ALTER Table

1. Start the Schema Manager and log in as the DBA. 2. Double-click the Table icon in the left frame. 3. Double-click the Schema that owns the Table you want to change. 4. Click the Table that needs a Primary Key. A properties window for the Table appears in the right frame. 5. Click the Constraints tab. Now you see a list of any Constraints that already exist for this Table. The sample Table, PARK_REVENUE, has no Constraints defined, as illustrated in Figure 7-17. 6. Click the Name box and (optional) type in a Constraint name. The name of the Constraint appears in error messages, so a name that indicates the kind of Constraint and Table can be useful. For the example, use PARK_REV_PK for the name. 7. Select Primary in the Type Column. 8. Leave the red X in the Disable Column.

Chapter 7 3 Primary Keys

173

Figure 7-16: The Constraint Tab in the Table window of Schema Manager handles Primary Keys.

Figure 7-17: Add Primary Key Constraints for the PARK_REVENUE Table now.

174

Chapter 7 3 Schema Manager for Tables

9. Select the Column or Columns in the Primary Key. Go to the box labeled Constraint Definition. The first Column is labeled Table Columns. Click the arrow to see a list of Columns. Select the Primary Key Column(s). In the sample Table, PARK_REVENUE, the Primary Key Column is named PARK_REV_PK. 10. Click the Show SQL button (optional). This action displays the actual SQL code generated to create the Primary Key. Figure 7-18 shows the SQL for creating a Primary Key named PARK_REV_PK on the SEAPARK.PARK_REVENUE Table. 11. Click Apply to commit the change. Oracle8 executes the generated SQL and creates the Index required to enforce your Primary Key. Oracle8 verifies every row in the Table has a unique value in the new Primary Key. If not, you will see the following error message.
ORA-02437: cannot Enable (tablename, Keyname) - Primary Key violated

To remedy the situation, you need to adjust the data in the Primary Key Column(s) so every row has a unique Primary Key.

SQL Command for Creating Primarry Key Figure 7-18: Viewing the SQL enables you to learn SQL syntax.

Chapter 7 3 Primary Keys

175

Changing a Primary Key


You cannot modify the Columns named in a Primary Key or the name of the Primary Key. You can only disable or enable the Primary Key. To execute this action, click the Disable Column, as shown in Figure 7-19. If Foreign Keys depend on the Primary Key, you receive an error message like the following:
ORA-02297: Cannot Disable Constraint (SEAPARK.TANK_PK) dependencies exist.

In this case, you must either disable or drop the Foreign Keys that require this Primary Key before you can disable the Primary Key.

Click here to enable or disable the Constraints

Figure 7-19: Disable or Enable a Primary Key using the Disable checkbox.

176

Chapter 7 3 Schema Manager for Tables

Removing a Primary Key


Caution

When you remove a Primary Key in Schema Manager, you automatically remove all Foreign Keys that refer to this Primary Key. Remember: you receive neither a warning nor a list of your changes. Heres how to remove a Primary Key: 1. Locate the Primary Key in the Schema Manager. Follow steps one through five in the preceding section. 2. Double-click the Primary Key Column. This action removes the Primary Key from the window.

Tip

If you change your mind after removing the Primary Key, you can restore it by clicking the Revert button. Important: this works only before you click the Apply button. 3. Click the Apply button. Oracle8 removes the Primary Key Constraint, the Index, and all Foreign Keys that reference this Primary Key.

Foreign Keys
When you name a Column or set of Columns as a Foreign Key, Oracle8 creates a Constraint but does not create an Index. If the Foreign Key is used in Queries, an Index on the Foreign Key Columns (in the exact order of the Foreign Key) improves performance. This section shows you how to create or remove a Foreign Key Constraint.
Tip

When you add a Foreign Key, Oracle8 looks at the parent Table referenced by the Foreign Key. Oracle8 verifies each row in the child Table has either a null value or a valid Key in the Foreign Key Columns. If Oracle8 finds any Foreign Keys that do not match, you cannot create the Foreign Key. To add a Foreign Key, use the same Schema Manager dialog box you used to create and change a Table. You can also use the dialog box to remove the Foreign Key. The process is similar to adding a Primary Key.

Adding a Foreign Key


See Reference Section

ALTER TABLE Follow these steps to create a Foreign Key using the Schema Manager. 1. Start the Schema Manager and log in as the DBA. Click the Schema Manager icon (which looks like a small three-table diagram) in the Enterprise Manager toolbar. Schema Manager prompts you to log in.

Chapter 7 3 Foreign Keys

177

2. Double-click the Table icon in the left frame. A list of Schemas appears below the icon in the left frame and a list of all Tables appears in the right frame. 3. Double-click the Schema that owns the Table you want to change. 4. Click the Table that needs a Foreign Key. The properties window for the Table appears in the right frame. 5. Click the Constraints tab. This action displays a list of any Constraints that already exist for this Table. As an example, Figure 7-20 shows the TANK Table. The TANK Table, owned by the SEAPARK Schema, contains a Primary Key but does not contain a Foreign Key.

Figure 7-20: Add a Foreign Key in the Constraint tab of the Table properties.

6. Type a Constraint name in an empty row in the name Column. Oracle8 uses this Constraint name in error messages. Therefore, a name that indicates both the nature and Table location of the Constraint may help you debug errors later. 7. Select Foreign in the Type Column. 8. Leave the red X in the Disable Column.

178

Chapter 7 3 Schema Manager for Tables

9. Select the referenced Schema. Click the arrow in the Column to obtain a selection list. Select the owner of the Table that this Foreign Key will reference. In the sample Table TANK, choose SEAPARK as the referenced Schema. 10. Scroll to the right and select the referenced Table. Click and drag the scroll bar to bring the Columns off to the right into view. Click the arrow in the referenced Table Column to reveal a list of Tables choose a Table by clicking it. In the sample Table TANK, choose CARETAKER as the referenced Table. 11. Select the Column or Columns in the Foreign Key. Go to the box labeled Constraint Definition. The first Column is labeled Table Columns. Click the arrow to see a list of available Columns in the current Table. Click the first Column in the Foreign Key. If your Foreign Key contains more than one Column, select each one in order so you see all Columns listed. 12. Select the corresponding Column or Columns in the referenced Table. The second Column in the Constraint Definition box is called Referenced Columns. Click the arrow to obtain a list of Columns in the referenced Table. Click the Column that corresponds with the Column in this Table. Repeat this sequence for each Column in the Foreign Key. 13. Click the Show SQL button (Optional). This action shows you the actual SQL code generated to create your new Foreign Key. Figure 7-21 shows the Constraint parameters and the SQL for adding a new Foreign Key to the TANK Table. 14. Click Apply to generate the Foreign Key. Oracle8 executes the generated SQL and checks the Foreign Key Constraint against every row of data. If Oracle8 finds any invalid Foreign Key values other than nulls, which it ignores you receive the error message:
ORA-02298: cannot Enable (SEAPARK.TANK_CARETAKER_FK) parent Keys not found.

To remedy the situation, you must correct the data so every row has either nulls or a valid Key in the Foreign Key Column.

Changing a Foreign Key


You cannot modify the Columns named in a Foreign Key or the name of the Foreign Key. You can only disable or enable the Foreign Key. To execute this action, click the disable Column, as shown in Figure 7-22 below.

Chapter 7 3 Foreign Keys

179

Foreign Key named here

Foreign Key columns selected here

SQL Command generated

Figure 7-21: This example Foreign Key references the Primary Key of the CARETAKER Table.
Click here to Disable or enable foreign key

Figure 7-22: Disable or enable a ForeignKey using the disable checkbox.

180

Chapter 7 3 Schema Manager for Tables

Removing a Foreign Key


See Reference Section

ALTER TABLE You may need to remove a Foreign Key if you change or drop the referenced Table. When you drop a Table (without the CASCADE CONSTRAINT option) containing a Foreign Key reference, Oracle8 does not drop the Table and sends an error message like the following:
ORA-02266: Unique/primary Keys in Table Referenced by enabled Foreign Keys

To avoid this error, either remove the Table with the CASCADE CONSTRAINT option or remove the offending Foreign Key. The following steps show how to remove a Foreign Key using Schema Manager. 1. Go to the Constraints tab in the Table Properties window. Follow steps one through five of the preceding section. 2. Double-click the Foreign Key. The Foreign Key disappears from the window. 3. Click the Apply button. Oracle8 removes the Foreign Key Constraint. The next section shows how to create and modify Indexes for your Tables.

Indexes
The Oracle Optimizer is an internal component of Oracle8 that determines the fastest way to retrieve data. The most common way to speed up data retrieval is to add an Index on Columns commonly found in the WHERE clause of SQL commands. Oracle8 keeps Indexes as independent Objects in the database. In terms of internal structure, an Index is like a Table. An Index has rows of data. The Columns in the Index include a copy of the Indexed Column(s) and the row ID of the corresponding row in the Indexed Table. Unlike Tables, Indexes are kept in perfect sorted order by the Index Columns. Every new row added to a Table creates a row in the Index. You add the row in the Index in its sorted order. This procedure allows Oracle8 to use fast search algorithms on the Index. After Oracle8 finds the row in the Index, it uses the row ID to retrieve the Table row.

Chapter 7 3 Indexes

181

Indexes are used for two primary purposes: 3 Faster queries. Indexing Columns frequently referenced in queries helps Oracle8 retrieve data at maximum speed. 3 Unique values. Oracle8 automatically generates an Index to enforce unique values in the Primary Key of a Table. You can also use this feature for any other Column (or set of Columns) that requires unique values in your Table. Indexes require more overhead during inserts because an entry is added in both the Table and the Index at the time the row is inserted. This can slow response time. Add Indexes only when you need them. Measure response time for queries and for inserts with and without the new Index to determine how the new Index affects performance.

What is a row ID?


Every row has a row ID that contains hexadecimal codes indicating the physical location of a row. A rows row ID can change if the Table is restructured if you remove and then replace all the data. Adding more information to a single row in an update does not change the row ID. If there is not enough room to store the additional data before reaching the next rows data, the row is chained to another Block. The data in the row then spans two blocks and chained rows are inefficient to retrieve.
CrossReference

See Chapter 15 for information on how to detect and correct chaining. Retrieving data using the row ID is the fastest Oracle8 retrieval method. Indexes contain the value of the Indexed Columns and the row ID. When Oracle8 uses an Index, it reads the Index and finds the values of the Indexed Columns and the row ID of the associated row. Then the Index reads the row data from the Tables blocks by going directly to the rows location, using the row ID. You may be tempted to use the row ID as a Foreign Key in other Tables. You can copy the row ID to a normal Column and use it for looking up data from the Table. This retrieval method may seem to be logical because it is the fastest way to the Tables data. Oracle8 and I recommend you do not use row ID this way, however, because the row ID of a row may change. When a Table gets reorganized, such as during Export and Import of the entire Table or database, the row ID changes. The Foreign Key connections that use that row ID are now invalid.

Tip

Indexes can speed response time in your online application screens. If you create a screen in which users search for phone numbers based on a persons last name, for example, you can create an Index for the LAST_NAME Column. This Index is used by the application that generates the SQL commands for searching.

182

Chapter 7 3 Schema Manager for Tables

The twenty percent rule


Retrieving decreases in performance as the proportion of rows retrieved increases. If you are retrieving approximately twenty percent of the rows in a Table, using an Index is just as fast. But beyond that magic twenty percent, not using an Index is faster. Keep this rule in mind when you create Indexes to help speed a query. Queries vary in the rows they select from a Table. If you frequently use a given query, determine the number of rows it selects from the Table. If this number is more than 20 percent of the total number of rows in the Table, an Index on the Table may not improve the performance of the query. You may want to try both methods. If the number of rows is less than 20 percent, an Index will almost certainly help performance.
Caution

Avoid adding an Index on a Column that includes identical values in many rows. A Column called SEX, for example, has three possible Values: MALE, FEMALE, and null. In a Table with ten thousand rows, an Index that narrows down the number of rows to 3,333 may not significantly speed performance. A new feature of Oracle8 creates Indexes on certain kinds of Objects. You can create an Index on a nested Table and on an array Column (VARRAY).

CrossReference

Chapter 24 shows how to add Indexes on Objects. Chapter 22 describes how to create Indexes on clustered Tables. Chapter 23 shows how Indexing works with very large Tables.

Creating new Indexes on Tables


Oracle8 has few restrictions on Index creation. The main rules are the following: 3 You cannot make two Indexes that include the same Columns. 3 You cannot Index Columns with the LONG or LONG RAW datatype. An Index can be either unique or nonunique. A unique Index validates every new or changed row in a Table for a unique value in the Column or set of Columns in the Index. A nonunique Index allows duplicate Values in rows. You add a nonunique Index to speed the query.
See Reference Section

CREATE Index

Follow these steps to create a new Index using Schema Manager:

Chapter 7 3 Indexes

183

1. Start the Schema Manager and log in as the DBA. 2. Double-click the Table icon in the left frame. 3. Double-click the Schema that owns the Table you want to Index. 4. Click the Table that needs an Index. The properties window for the Table appears in the right frame. 5. Right-click the Table in the left frame and select Create Index On from the submenu that pops up. This sequence brings up a window to complete the Index definition. Figure 7-23 shows the Create Index dialog box. The sample Table TANK needs a new Index on the CHIEF_CARETAKER_NAME Column. 6. Fill in the Index Name and select the Schema. Because you are logged in as the DBA, the Schema shown is probably not correct. Modify the Schema by selecting the appropriate Schema. For the example, select SEAPARK. 7. Select the Indexed Columns in order. Click each Column you want to Index. Select the first Column in the Index first, the second one next, and so forth until youve numbered all the Columns in the Index. Figure 7-24 shows the sample Index TANK_CARETAKER_X on the CHIEF_CARETAKER_NAME Column. Each Column you click is assigned a sequence number showing the order of the Indexed Columns. 8. Choose appropriate Options. Leave the sorted box checked (default). If your Index is unique, check the Unique box. The Bitmap box is for an alternative method of sorting. The recoverable box tells Oracle8 to write this event (creation of the Index) into its redo logs for later recovery, if necessary. 9. Click the Create button to finish. Schema Manager executes the generated SQL and returns you to the main window.

Figure 7-23: Fill in the boxes to create a new Index.

184

Chapter 7 3 Schema Manager for Tables

Click here to add column to the index

Figure 7-24: Choose the Columns by clicking them in order.

The next sections show how to modify and remove an Index from the database.

Changing an Index
See Reference Section

ALTER INDEX The only changeable parts of an Index are the storage parameters. To modify the storage parameters using Schema Manager, follow these steps: 1. Start the Schema Manager and log in as the DBA. 2. Double-click the Index icon in the left frame. 3. Double-click the Schema that owns the Index you want to remove. 4. Click the Index you want to modify. 5. Click the Storage tab. The Storage properties tab for the Index appears in the right frame, as shown in Figure 7-25. 6. Make changes as needed. Change storage parameters to fit the Index. 7. Click Apply to complete. The Schema Manager modifies the Index and returns you to the main window.

Chapter 7 3 Indexes

185

Figure 7-25: Modify storage parameters here.

Removing an Index
See Reference Section

DROP INDEX Removing an Index by using Schema Manager is simple. Follow these steps: 1. Start the Schema Manager and log in as the DBA. 2. Double-click the Index icon in the left frame. 3. Double-click the Schema that owns the Index you want to remove. 4. Click the Index you want to remove. A properties window for the Index appears in the right frame, as shown in Figure 7-26. 5. Click the red X to remove. Schema Manager displays a window verifying you want to proceed with removing the Index. 6. Click Yes. The Schema Manager removes the Index and returns you to the main window, where you see Oracle8 has removed the Index from the list of Indexes.

186

Chapter 7 3 Schema Manager for Tables

Click here to remove index

Figure 7-26: Click the red X to drop the Index.

Summary
Creating Tables and adding Constraints and Indexes are easily accomplished within the Schema Manager. As the DBA, you may want to consider allowing your application developers access to the Schema Manager so they can use this tool. Modifying a Tables structure can be easy or difficult, depending on the kind of desired change. The most difficult kinds of changes occur when you must actually drop the Table and re-create it. In this case, there are many related Objects, such as Indexes and Foreign Keys, that must be preserved and restored. The Schema Manager has a new feature that enables you to use a calculator instead of explicitly naming the storage sizes. This feature applies to both Tables and Indexes. The next chapter shows how to use the Schema Manager for more Objects: views, Synonyms, and sequences.

Das könnte Ihnen auch gefallen