Beruflich Dokumente
Kultur Dokumente
12
C H A P T E R
T
See Reference Section CrossReference
his chapter explores how you use SQL commands to create Tables and Indexes, assign Primary and Foreign Keys, and control Constraints. Some consider this approach as the old-fashioned way. SQL, however, is a precise language and creating Objects with SQL is fast and easy. All the SQL commands shown in this chapter are also listed in the Commanmd Reference section of the book. Watch for the See Reference Section icon in the margin that appears next to this paragraph. All the tasks described in this chapter are described in Chapter 7 using Schema Manager, the Enterprise Manager tool. If you prefer using the Schema Manager over SQL commands, refer to Chapter 7.
In This Chapter
Using SQL for creating Tables Modifying an existing Tables structure Adding relationships and other Constraints Creating Indexes
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. This section shows how to create and modify Tables using SQL commands. You can use SQL commands in SQL*Plus, SQL Worksheet, or Server Manager (svrmgr). Generally, the DBA or the Schema (the User that owns the Table) creates Tables.
CrossReference
See Chapter 24 for information and examples on creating Object-Tables, nested Tables, arrays, and other Objectoriented Objects. If you need a refresher on Oracle8 datatypes, refer to Table 7-1: Oracle8 Datatypes in Chapter 7 for a complete list of datatypes. For a good discussion of null values, their use and implications, refer to Chapter 7, section What is null?
CrossReference
248
On the CD-ROM
CrossReference
See Chapter 11 for details on using SQL to create a User. See Chapter 6 for step-bystep instructions on creating a User with Security Manager. All Tables are assigned to a Tablespace upon creation. If no Tablespace is named, the Users default Tablespace receives the Table. Use the Storage Manager to create a new Tablespace or allocate additional space to the Tablespace.
CrossReference
CREATE TABLESPACE
You can also create a Tablespace using SQL. See the Command Reference section 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 12-1 shows the SEAPARK Tables and their corresponding relationships.
Chapter 12 3 Tables
249
CARETAKER CARETAKER_NAME
CHECKUP CHECKUP_TYPE
Figure 12-1: Sample Tables used in this chapter track sea life in an aquatic park.
See Reference Section
CREATE TABLE
When you do not specify Tablespace parameters, Oracle8 places the Table in the Users default Tablespace. The default Tablespace is defined by the profile of which the User is a member.
250
If you leave any of the storage space parameters (PCTFREE, PCTUSED, STORAGE) out of the CREATE TABLE command, Oracle8 substitutes the missing parameter(s) with the corresponding defaults for the Tablespace in which the Table is created.
CrossReference
The Clusters section in Chapter 22 describes how to use the cluster parameter. Chapter 24 discusses partitioned Tables (a new Oracle8 feature) and Chapter 23 discusses Tables containing LOBs. The AS query parameter enables you to copy another Tables data into a new Table that inherits the old Tables Column definitions. You can also use this parameter to create a Table whose Columns match any query you choose. See the following Adjusting Table Structure while preserving Column data section for an example of this parameter. At a minimum, you must define the Table name and the Columns. The following SQL command creates the sample CHECKUP_HISTORY Table without Constraints or storage parameters except for a NOT NULL Constraint on the CHECKUP_NO Column, which will be the Primary Key Column.
CREATE TABLE CHECKUP_HISTORY (CHECKUP_NO NUMBER(10,0) NOT NULL, ID_NO NUMBER(10,0), CHECKUP_TYPE VARCHAR2(30), CHECKUP_DATE DATE, DOCTOR_NAME VARCHAR2(50))
The Primary Key, Foreign Key, and other Constraints are added later using the ALTER TABLE command. The following SQL command creates the sample CHECKUP_HISTORY Table using parameters to specify the Schema, Primary Key, Foreign Key, Tablespace, and storage.
CREATE TABLE SEAPARK.CHECKUP_HISTORY (CHECKUP_NO NUMBER(10,0) NOT NULL, ID_NO NUMBER(10,0), CHECKUP_TYPE VARCHAR2(30), CHECKUP_DATE DATE, DOCTOR_NAME VARCHAR2(50), FOREIGN KEY (CHECKUP_TYPE) REFERENCES SEAPARK.CHECKUP (CHECKUP_TYPE), PRIMARY KEY (CHECKUP_NO)) PCTFREE 20 PCTUSED 60 INITRANS 2 MAXTRANS 255 STORAGE ( INITIAL 1250K NEXT 2K MINEXTENTS 1 MAXEXTENTS 121
Chapter 12 3 Tables
251
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. The next section shows how to add, remove, move, or modify the datatype of Columns in existing Tables.
ALTER TABLE
This section shows you how to make Table changes without special handling of your Tables data. You can make these kinds of changes any time, regardless of what data you have in the Table: 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 12-1 to find the appropriate section for other Table changes.
252
Table 12-1 Where to Find Instructions for Revising Column Specifications in a Table
Change Lengthen a Column Change not null to nulls allowed Change nulls allowed to not null Change nulls allowed to not null Add a Column at end of Table Change datatype of Column Change datatype of Column Shorten Column Shorten Column Remove a Column Rename a Column Add Column in the middle Reorder Columns Data in Column? N/A N/A Yes (all rows have data) No (some or all rows have nulls) N/A No Yes No Yes N/A N/A N/A N/A Section Adjusting Table structure Adjusting Table structure Adjusting Table structure Adjusting Table structure while adding default Column data Adjusting Table structure Adjusting Table structure Adjusting Table structure while preserving Column data Adjusting Table structure Adjusting Table structure while preserving Column data Adjusting Table structure by re-creating Table Adjusting Table structure by re-creating Table Adjusting Table structure by re-creating Table Adjusting Table structure by re-creating Table
All Table structure changes are made in the ALTER TABLE command. For all the changes listed in this section (except adding a Column at the end of the Table), the general syntax of the ALTER TABLE command follows:
ALTER TABLE [USER.] TABLE MODIFY ( COLUMN1 DATATYPE [COLUMN_CONSTRAINT] )
The general syntax for adding a Column to the end of the Table follows:
Chapter 12 3 Tables
253
For example, use the following SQL command to change the length of the CHIEF_CARETAKER_NAME Column from thirty to fifty characters in the TANK Table:
ALTER TABLE TANK MODIFY ( CHIEF_CARETAKER_NAME VARCHAR2(50))
Use the following SQL command to add a Column at the end of the AQUATIC_ANIMAL Table:
ALTER TABLE AQUATIC_ANIMAL ADD ( PHYSICAL_DESC VARCHAR2(500))
Use the following SQL command to change the CHECKUP_TYPE Column in the CHECKUP_HISTORY Table to not null:
ALTER TABLE CHECKUP_HISTORY MODIFY ( CHECKUP_TYPE NOT NULL)
The next section discusses changes that require a closer look at your data before making the change.
This section shows you how to make changes in your existing Tables that require you to remove data from the Column. The following changes require a null value for every row in the Table: 3 Shorten Column 3 Change datatype of 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
254
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 section called Adjusting Table structure. If you choose to preserve the data, follow these general steps: 1. Create a new Table by copying the Primary Key and the Column data to be preserved. 2. Remove data from the Column to be changed. 3. Modify the existing Table structure. 4. Update the existing Table with the data saved in the new Table.
Example
I present complete step-by-step instructions below. To illustrate the steps, the sample Table (TANK) has its Column (CHIEF_CARETAKER_NAME) length changed from sixty characters to fifty characters. 1. Create a new Table by copying the Primary Key and the Column data to be preserved. The Table must contain the original Tables Primary Key Column(s) and the Column that will be changed. The following SQL command creates a Table with the Primary Key (TANK_NO) and the Column to be changed (CHIEF_CARETAKER_NAME). The following command creates the Table and inserts the data in one step:
CREATE TABLE HOLD_TANK AS SELECT TANK_NO, CHIEF_CARETAKER_NAME FROM TANK;
2. Remove data from the Column to be changed. Use an UPDATE command to change every rows data in the CHIEF_CARETAKER_NAME Column to null value:
UPDATE TANK SET CHIEF_CARETAKER_NAME = NULL;
3. Modify the Table structure of the Table. Use the following ALTER TABLE command:
ALTER TABLE TANK MODIFY ( CHIEF_CARETAKER_NAME VARCHAR(50))
4. Update the Table with the data saved in the new Table. Use the UPDATE command to move the data back into the appropriate row:
UPDATE TANK SET CHIEF_CARETAKER_NAME = (SELECT CHIEF_CARETAKER_NAME FROM HOLD_TANK WHERE HOLD_TANK.TANK_NO = TANK.TANK_NO)
Chapter 12 3 Tables
255
CrossReference
To learn more about the correlated subquery (used in the preceding SQL command), refer to the Correlated Subqueries section in Chapter 9. 5. Save your changes.
COMMIT
6. Remove the Table created to hold the data. The last task is important: remove the holding Table. Use the following SQL command to remove the HOLD_TANK TABLE created in step two:
DROP TABLE HOLD_TANK
The next section shows another technique for modifying Table structure.
Some Column changes require every row contain data in the Column to be changed. 3 Change Nulls Allowed to Not Null If you try to add the not null Constraint to a Column in which some of the 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, the MEASURE_WEIGHT_FLAG Column in the CHECKUP Table will be changed to not null. To do this, follow the steps here. 1. Populate the rows where the Column is null with a default value. In the example, the MEASURE_WEIGHT_FLAG is updated so that null values are changed to N.
UPDATE CHECKUP SET MEASURE_WEIGHT_FLAG = 'N' WHERE MEASURE_WEIGHT_FLAG IS NULL
256
When you make a Data Definition Language (DDL) type of command in SQL, all previous commands in your transaction are committed to the database along with the DDL command. Therefore, in the preceding example, the UPDATE commands changes to the Table data are committed as a result of the ALTER TABLE command that follows. The next section covers the most difficult type of Table alteration.
The most involved 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 (such as Indexes and 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.
Chapter 12 3 Tables
257
Caution
One of the steps in this section removes (drops) 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 disappear and must be re-created. 3 Any Foreign Keys in other Tables that refer to this Tables Primary Key also are removed. 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: 1. Make a copy of the Table to preserve existing data. For the example, the name of the new Table is HOLD_AQUATIC_ANIMAL. The following SQL command makes a copy of the Table:
CREATE TABLE HOLD_AQUATIC_ANIMAL AS SELECT * FROM AQUATIC_ANIMAL
2. Review all related Objects and preserve scripts to restore them. Find all related Objects to be removed when you drop the Table. Record them so they can be restored later with 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.) 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.
258
You cannot roll back or undo the act of dropping a Table. For the example, drop the AQUATIC_ANIMAL Table with the following SQL command:
DROP TABLE AQUATIC_ANIMAL
4. Create the Table with new structure. Write a CREATE TABLE command that contains your desired changes. Create the Table with the following CREATE TABLE command:
CREATE TABLE AQUATIC_ANIMAL (ID_NO NUMBER(10,0) NOT NULL, TANK_NO NUMBER(10,0), ANIMAL_NAME VARCHAR2(30), MARKINGS_DESCRIPTION VARCHAR2(500) , BIRTH_DATE DATE , DEATH_DATE DATE )
5. Insert data back into the Table. The following INSERT command inserts data back into the re-created AQUATIC_ANIMAL Table. Since a new Column was created, it does not include data from the holding Table and is therefore omitted from the Insert command.
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
CrossReference
See Chapter 10 for details on writing the INSERT command. 6. Commit your changes.
COMMIT
The inserted rows are now preserved in the database. 7. Restore all related Objects. Re-create Foreign Keys, Indexes, Triggers, grants, and so forth. 8. Remove the holding Table. The following command removes the Table created in step one:
DROP TABLE AQUATIC_ANIMAL_HOLD
259
DROP TABLE
The CASCADE CONSTRAINTS parameter causes all Foreign Keys that reference the Table to be dropped along with the Table. When you drop a Table, the following related Objects are also dropped: 3 Indexes on this Table. 3 Foreign Keys on other Tables that reference this Table. 3 Triggers on this Table. 3 Partitions on this Table. 3 Snapshot logs on this Table. 3 Grants to Roles or Users on this Table. 3 All Constraints on this Table.
Caution
You cannot roll back a DROP TABLE command. You must recover a dropped Table by restoring it from a backup.
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.
CrossReference
You can define the Primary Key for a Table during or after you create the 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.
260
Tip
Oracle8 will validate a new Primary Key if all rows have a unique value on the Primary Key.
ALTER TABLE
The general syntax for adding a Primary Key to an existing Table follows:
ALTER TABLE [schema.]tablename ADD ( CONSTRAINT_NAME PRIMARY KEY (column1 [, Column2, ...) )
For example, the following SQL command adds a Primary Key named PARK_REV_PK to the PARK_REVENUE Table (the Key contains the Column ACCOUNT_NO):
ALTER TABLE PARK_REVENUE ADD ( PARK_REV_PK PRIMARY KEY (ACCOUNT_NO) )
When Oracle8 executes the SQL, the Index required to enforce your Primary Key is also created. Oracle8 verifies every row in the Table has a unique value in the new Primary Key. If not, you receive the following error message:
ORA-02437: Cannot enable (tablename, keyname) - primary key violated.
Adjust the data in the Primary Key Column(s) so every row has a unique Primary Key.
ALTER TABLE
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, use the following general syntax for the ALTER TABLE command:
ALTER TABLE [SCHEMA.]tablename DISABLE CONSTRAINT_NAME
If Foreign Keys depend on the Primary Key, you will receive an error message like the following:
261
In this case, you must either disable or drop the Foreign Keys that require this Primary Key before you can disable the Primary Key.
When you remove a Primary Key, you can optionally remove all Foreign Keys that refer to this Primary Key using the CASCADE parameter. Oracle8 removes the Primary Key Constraint and the associated Index. If you add the CASCADE parameter, Oracle8 also removes 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. It 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.
ALTER TABLE
262
The following SQL command adds a Foreign Key named TANK_CARETAKER_FK to the TANK Table. The CHIEF_CARETAKER_NAME Column in the TANK Column is a Foreign Key for the Primary Key of the CARETAKER Table.
ALTER TABLE TANK ADD ( TANK_CARETAKER_FK FOREIGN KEY (CHIEF_CARETAKER_NAME) REFERENCES CARETAKER (CARETAKER_NAME) )
Oracle8 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 following error message:
ORA-02298: Cannot enable (SEAPARK.TANK_CARETAKER_FK) - parent keys not found.
Correct the data so every row has either nulls or a valid Key in the Foreign Key Column.
ALTER TABLE
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, use the following general syntax:
ALTER TABLE [SCHEMA.]tablename DISABLE CONSTRAINT_NAME
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 CONSTRAINTS option) and a Foreign Key references the Table, 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 CONSTRAINTS option or remove or disable the offending Foreign Key.
Chapter 12 3 Indexes
263
To remove a Foreign Key with SQL, use the following command syntax:
ALTER TABLE [schema.]tablename DROP CONSTRAINT CONSTRAINT_NAME
The next section describes 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.
CrossReference
See Chapter 7 for a description of the Row ID. Unlike most 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. 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.
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 then create an Index for the LAST_NAME Column. This Index is used by the application that generates the SQL commands for searching. A new feature of Oracle8 creates Indexes on certain kinds of Objects. You can create an Index on a nested Table and on a scaled Object-attribute Column.
CrossReference
Chapter 24 shows how to add Indexes on Objects. Chapter 22 describes how to create Indexes on clustered Tables and Chapter 23 shows how Indexing works with partitioned Tables.
264
CREATE INDEX
You can allow the storage parameters (INITRANS, MAXTRANS, PCTFREE, STORAGE, TABLESPACE) to default to the Users default values for these parameters. The NO SORT parameter tells Oracle8 the Table itself is stored in sorted order and therefore the Index need not be sorted. A Table is stored in sorted order if it is created using the ORGANIZATION Index parameter for the Table. The following command creates a new Index called TANK_CARETAKER_X on the CHIEF_CARETAKER_NAME Column in the TANK Table:
CREATE INDEX TANK_CARETAKER_X ON TANK ( CHIEF_CARETAKER_NAME )
The next section shows how to modify and remove an Index from the database.
Chapter 12 3 Summary
265
Changing an Index
See Reference Section
ALTER INDEX
The most common changeable parts of an Index are the storage parameters. To modify the storage parameters using SQL, use the following general syntax:
ALTER [UNIQUE] INDEX [user.]index [INITRANS n] [MAXTRANS n] [STORAGE n]
DROP INDEX
Removing an Index by using SQL is similar to dropping a Table. Simply use the following syntax:
DROP INDEX [schema.]indexname
Like other DDL commands, you cannot roll back a dropped Index.
Summary
Modifying a Tables structure can be easy or difficult depending on the kind of change you want to make. The most difficult kinds of changes require the removal and re-creation of the Table. In these cases, many related Objects such as Indexes and Foreign Keys must be preserved and restored. The next chapter describes how to use SQL for the following Objects: views, Synonyms, and sequences.