• A list of column names, the datatype associated with the column, and certainconstraints associated with that column such as NOT NULL• The tablespace that the table is assigned to • Tab
Trang 1addition of Oracle objects and partitioning, the format of the native database ROWIDneeded to be expanded, and the extended ROWID was born Let’s look at each ofthese ROWID types in a bit more detail.
Extended ROWIDs
The extended ROWID is the native form of a ROWID in Oracle8i and was first duced with Oracle8 Extended ROWIDs are relative only to a given tablespace This isdifferent from the relative ROWID that was present in Oracle7, which made everyrow in the database unique throughout the entire database The extended ROWID is
intro-an 18-character value that represents four different values:
Data object number This is a six-character representation of a 32-bit dataobject number This number uniquely identifies the database segment Each time
an object changes, the data object number associated with this object changes aswell Thus, the data object number also serves as a version number for the object
Relative datafile number This is a three-character representation of therelative datafile number The relative datafile number is relative to the tablespace
to which that tablespace belongs Thus, objects in different tablespaces will likelyhave different relative datafile numbers
Data block This is a six-character representation of the data block This blocknumber is relative to the tablespace to which it belongs
Row number in the block This is a three-character representation of therow in the block
An example of an extended ROWID is shown in the query below
SQL> SELECT rowid FROM test;
ROWID -AAAAx/AABAAADhBAAAAAAAx/AABAAADhBAABAAAAx/AABAAADhBAACAAAAx/AABAAADhBAAD
As you can see, the ROWID is a rather odd-looking thing All of the different letters
do not translate into anything usable by the DBA, except that they can be useddirectly in a SQL statement’s WHERE clause in certain cases (for example, if you storeROWIDs in a table)
To effectively use an extended ROWID, you will probably need to employ the Oraclepackage DBMS_ROWID This package has several functions that can be used to translate
Trang 2the extended ROWID into its component parts, which can then be used to determinesuch things as which datafile or block the row is in The DBMS_ROWID package alsoprovides procedures and functions that can convert extended ROWIDs into restrictedROWIDs, and vice versa.
Restricted ROWIDs
The restricted ROWID can be determined from the extended ROWID, and anextended ROWID can be created from a restricted ROWID The restricted ROWID hasthree components:
• The first number in the restricted ROWID is an eight-digit number that sents the block number that the row belongs in This number relates to theV$LOCK column in the DBA_EXTENTS dictionary view
repre-• The second number is a four-digit number that represents the row number inthe block The first row in each block is always a 0
• The last number is a four-digit number that represents the absolute datafile towhich the row belongs This number relates to the FILE_ID column in theDBA_EXTENTS data dictionary view
An example of a restricted ROWID looks something like this:
00000011.0000.0001
Each component of the restricted ROWID is separated by a dot, and unlike theextended ROWID, you do not need to use any package to determine the values beingprovided for each component
NOTE It is a common misconception that the restricted ROWID has been totally doneaway with In fact, Oracle indexes still store restricted ROWIDs for each table row that theypoint to Also, there are those who mistakenly suppose that there is some sort of ROWIDconversion that occurs during a migration from Oracle 7.3 to Oracle8i This is not the case,since the ROWIDs for tables are not stored in the database, but are generated on the flywhen the ROWID pseudocolumn is used in a query
Creating Heap Tables
To create a table, use the CREATE TABLE DDL statement In its typical form, the ATE TABLE statement includes the following:
CRE-• The table name
Oracle Database Administration
P A R TII
Trang 3• A list of column names, the datatype associated with the column, and certainconstraints associated with that column (such as NOT NULL)
• The tablespace that the table is assigned to
• Table attributes such as PCTFREE and PCTUSED
• The STORAGE clause associated with the table
• Table attribute settings, such as CACHE or NOLOGGING
To create a table in your own schema, you must have the CREATE TABLE privilege
If you want to create a table in another user’s schema, you need to have the CREATEANY TABLE privilege Also, you will need to have a sufficient QUOTA assigned to thetablespace(s) in which you will be creating tables (and any associated primary keyindexes) If you create a primary key on the table, you also need to have the privileges
to create an index, since the primary key is enforced through a unique index
NOTE A QUOTA is a limitation on how much space a user can use in a given tablespace.For example, if your quota is 0 (the default for new users), you will not be able to add any-thing to the tablespace Users are assigned a QUOTA as a part of their configuration andsetup See Chapter 21 for more details on setting up user accounts
If you are using an Oracle TYPE in the table (we will discuss TYPEs in Chapter 8),you will need EXECUTE privileges on the TYPE you will be using, if your schemadoesn’t own the TYPE If you wish to grant access to the table to other users, you willneed to have EXECUTE privileges on the TYPE with the ADMIN option
There are several miscellaneous types of settings that you may wish to considerwhen creating a table in Oracle Table 6.1 lists these settings
TABLE 6.1: MISCELLANEOUS TABLE OPTIONS
CACHE No Causes full table scans to be put on the head of the
LRU list This clause has been deprecated in favor ofthe use of the new KEEP BUFFER_POOL option.NOCACHE Yes Causes Oracle to follow the default full table scan
behavior, by putting the blocks read for a full tablescan on the tail of the LRU list
Trang 4TABLE 6.1: MISCELLANEOUS TABLE OPTIONS (CONTINUED)
NOLOGGING No Reduces redo generated by DML activity on the table
Table data inserted after backup will not be able This can reduce the time required to create thetable
MONITORING No Causes Oracle to record DML activity on the table
You can then use the DBMS_STATS.GATHER STALEprocedure to update the statistics of just the tablesthat have changed
NOMONITORING Yes Sets the default for this parameter
NOTE CACHE remains in Oracle only for backward compatibility You should configureand use a keep buffer pool (described in Chapter 5) and assign an object to that bufferpool rather than use the CACHE option
Creating a Table
Listing 6.1 shows a simple example of using the CREATE TABLE statement
Listing 6.1: Creating a Heap Table
CREATE TABLE PARENT(parent_id NUMBER PRIMARY KEY,last_name VARCHAR2(30) NOT NULL,first_name VARCHAR2(30) NOT NULL,middle_int CHAR(1),
sex CHAR(1),married_status CHAR(1))
TABLESPACE usersPCTFREE 10PCTUSED 60STORAGE(INITIAL 10m NEXT 10m PCTINCREASE 0);
Oracle Database Administration
P A R TII
Trang 5This creates a table named PARENT with six columns The first column,PARENT_ID, is defined as a NUMBER datatype and the primary key of this table.Because the keyword PRIMARY KEY is included in the definition of the PARENT_IDcolumn, an index will be created on this primary key column Since we didn’t givethe index a name in this CREATE TABLE statement, Oracle will assign a name to it bydefault The system-generated name will always start with a SYS and then be followed
by a series of numbers Also, the primary key index will be created in the defaulttablespace of the user creating the table, and the index associated with the primarykey will also have a system-generated name The query and results below show theprimary key created as a result of the creation of this table
SQL> SELECT table_name, index_name, tablespace_name
2 FROM user_indexes
3 WHERE table_name like ‘PARENT’;
TABLE_NAME INDEX_NAME TABLESPACE_NAME - - -PARENT SYS_C00780 USERS
This shows that the system-generated index name is SYS_C00780 Also note thatthe primary key index has been assigned to the USERS tablespace, which is the defaulttablespace of the user who created the index In the next section, you will see anexample of how to give the primary key index a meaningful name and control wherethe primary key index is created
The LAST_NAME and FIRST_NAME columns in the table are VARCHAR2 datatypesthat are sized to hold up to 30 characters each The MIDDLE_INT, SEX, and MAR-RIED_STATUS columns are fixed-length CHAR datatypes, each holding 1 byte Notice the NOT NULL keyword in the LAST_NAME and FIRST_NAME column defi-
nitions The NOT NULL keyword establishes a constraint on the table A constraint is a
rule In this case, the NOT NULL constraint prohibits this column from having aNULL value in it at any time Thus, you will need to provide a value for the column ineach INSERT statement, by including it in the INSERT statement, through the use of atrigger (see Chapter 1 and Appendix F for more on triggers) or by defining a defaultvalue for the column When you create a primary key, the columns of the primarykey will be set to the NOT NULL status automatically
The other types of constraints you can create in Oracle are check, foreign key, NOTNULL, primary, and unique When creating a table, you may define the various con-straints in the CREATE TABLE statement either for individual rows (check constraints)
or a group of rows (primary keys) (See Chapter 7 for a detailed discussion of straints.)
Trang 6con-Viewing the Table
After you’ve created the table, you can query the DBA_TABLES view to see your table:
SELECT owner, table_name,tablespace_name, initial_extent, next_extentFROM dba_tables
WHERE owner = ‘SCOTT’ AND table_name LIKE ‘PARENT’;
OWNER TABLE_NAME TABLESPACE_NAME INITIAL_EXTENT NEXT_EXTENT - - - - -SCOTT PARENT USERS 10485760 10485760
Also, you can query the DBA_TAB_COLS data dictionary view and discover thatyou have rows in it for each of the columns in your table:
SELECT owner, table_name, column_name, data_type, nullable
The DBA_TABLES and DBA_TAB_COLS views are discussed in more detail in the
“Viewing Table Information” section a bit later in this chapter
Specifying the Primary Key and Index Location
Listing 6.2 shows another example of a CREATE TABLE statement
Listing 6.2: Creating a Table with Primary Key and Index Location Specifications
CREATE TABLE children(child_id NUMBER CONSTRAINT pk_children PRIMARY KEYUSING INDEX TABLESPACE indexes
STORAGE (INITIAL 200k NEXT 200k),parent_id NUMBER,
Oracle Database Administration
P A R TII
Trang 7last_name VARCHAR2(30),first_name VARCHAR2(30),middle_int CHAR(1),medical_code VARCHAR2(30) CONSTRAINT children_check_upper
CHECK (medical_code = UPPER(medical_code) ))
TABLESPACE usersPCTFREE 10PCTUSED 60STORAGE(INITIAL 10m NEXT 10m PCTINCREASE 0);
This one looks a bit different from the CREATE TABLE statement in Listing 6.1 First,the second line, where the CHILD_ID column is being defined, includes a CONSTRAINTclause that names the primary key constraint In this example, the primary key con-straint is named PK_CHILDREN The associated index enforcing that primary key willalso be called PK_CHILDREN
Next, the USING INDEX clause is associated with the first column It is throughthis clause that you can control in which tablespace the primary key index is created,
as well as define storage characteristics for that index with a separate STORAGE clause.Finally, note the check constraint in the definition of the MEDICAL_CODE col-umn The definition of the constraint begins with the word CONSTRAINT, followed
by the name of the constraint, then the keyword CHECK Following the CHECK word is the actual constraint This example uses the UPPER function to ensure thatany values for MEDICAL_CODE are entered in uppercase If someone tried to enter alowercase medical code in this column, the transaction would fail and the followingerror would be returned:
key-ORA-02290: check constraint (SCOTT.CHECK_UPPER) violated
Creating a Two-Column Primary Key and Foreign Key Constraint
Let’s look at another example of a CREATE TABLE statement The example shown inListing 6.3 re-creates the CHILD table with a two-column primary key and a foreignkey constraint to the PARENT key
Listing 6.3: Creating a Table with a Two-Column Primary Key and eign Key Constraint
For-CREATE TABLE children(child_id NUMBER,parent_id NUMBER,last_name VARCHAR2(30),
Trang 8first_name VARCHAR2(30),middle_int CHAR(1),medical_code VARCHAR2(30) CONSTRAINT children_check_upper
CHECK (medical_code = UPPER(medical_code) ),CONSTRAINT pk_children PRIMARY KEY (child_id, parent_id)USING INDEX TABLESPACE indexes
STORAGE (INITIAL 10k NEXT 10k),CONSTRAINT fk_child_parent FOREIGN KEY (parent_id)REFERENCES parent (parent_id)
)TABLESPACE usersPCTFREE 10PCTUSED 60STORAGE(INITIAL 10m NEXT 10m PCTINCREASE 0)
Both the primary key constraint and the foreign key constraint are created in thesame clause where the table columns are created Since the example creates a two-column primary key, it adds a separate CONSTRAINT clause, rather than just the PRIMARY KEY clause at the end of each column In other words, you cannot create atwo-column primary key like this:
CREATE TABLE children(child_id NUMBER PRIMARY KEY,parent_id NUMBER PRIMARY KEY,last_name VARCHAR2(30),first_name VARCHAR2(30),middle_int CHAR(1) );
This code would result in an error because you are incorrectly trying to define a column primary key
two-Creating a Table from an Existing Table Definition
The CREATE TABLE AS SELECT (CTAS) command allows you to create a table from thedefinition of an existing table, or create a new table based on a join of one or moretables This is handy to have for a variety of reasons First, this is one method you canuse to defragment a table Also, you can use CTAS to create a separate table with asample set of data Listing 6.4 shows an example of using CTAS to create a table fromtwo existing tables
Listing 6.4: Using the CREATE TABLE AS SELECT (CTAS) Command
Using CTAS from an existing table (or tables in this case)
We are also limiting the number of rows returned to 9
Oracle Database Administration
P A R TII
Trang 9CREATE TABLE create_view_table_one TABLESPACE users
STORAGE (INITIAL 100k NEXT 100k BUFFER_POOL RECYCLE)AS
SELECT a.parent_id AS parent_id,a.last_name AS parent_last_name,a.first_name AS paremt_first_name,b.last_name AS child_last_name,b.first_name AS child_first_nameFROM parent a, children bWHERE a.parent_id=b.parent_idAND rownum < 10;
You can also use CTAS to create a table using a view, as shown in Listing 6.5 Thisexample executes this statement using a view as the source for the new table
Listing 6.5: Creating a Table Using a View with CTAS
Create the view firstCREATE VIEW v_parent_child ASSELECT a.parent_id AS parent_id,a.last_name AS parent_last_name,a.first_name AS parent_first_name,b.last_name AS child_last_name,b.first_name AS child_first_nameFROM parent a, children bWHERE a.parent_id=b.parent_id;
Now, create a table via CTAS using the viewCREATE TABLE ctas_from_view_pc
TABLESPACE dataSTORAGE (INITIAL 100k NEXT 100k )
AS SELECT * FROM v_parent_child;
NOTE CTAS is particularly handy for use with LogMiner, which is discussed in Chapter 14.This is because some of the critical views that LogMiner populates with information arepersistent only for the duration of the user session that created those views Using CTAS tocreate a table allows you to retain the LogMiner results
Trang 10Creating a Temporary Table
A temporary table is like a regular table in many ways It is created by the use of the
GLOBAL TEMPORARY keywords in the CREATE TABLE command The data in a porary table is visible to only the session that created that data, yet the temporarytable is available for use by all transactions
The temporary table will persist until it is dropped; however, the data in the porary table is not persistent Using the ON COMMIT keywords, you can choose fromtwo different options that control when the data in the temporary table is removed Ifyou create the temporary table using the ON COMMIT DELETE clause (the default),the session data in the table is removed as soon as the transaction completes Usingthe ON COMMIT PRESERVE clause will cause that session’s data to be removed onlyafter the session is disconnected
tem-A temporary table uses temporary segments to store session data, and along withthe data in the segments, the segments themselves are de-allocated Since temporarytables use temporary segments, they use the temporary tablespace defined for the userwho is using the temporary table Therefore, no TABLESPACE clause, STORAGE clause,
or physical attributes clauses are allowed in the CREATE TABLE statement When anindex is created on a temporary table, its data segments are temporary as well There-fore, a USING INDEX clause is not permitted when creating a temporary table TheCONSTRAINT clause is allowed, but some constraints are not permitted
Here is a summary of the restrictions on temporary tables:
• They can be only hash tables (so index-organized tables and clusters are notallowed as temporary tables)
• You cannot partition a temporary table
• Most constraints are not supported, but you can specify check constraints andNOT NULL constraints You can create temporary tables with primary keys, butforeign key relationships are not supported
• Temporary tables do not support nested tables or VARRAYs, which are part ofOracle’s object-oriented features
• Parallel DML and parallel queries are not supported on temporary tables
• You cannot use a temporary table as a part of a distributed transaction
Listing 6.6 shows an example of creating a temporary table
Listing 6.6: Creating a Temporary Table
CREATE GLOBAL TEMPORARY TABLE temp_children(child_id NUMBER CONSTRAINT pk_temp_children PRIMARY KEY,parent_id NUMBER,
Oracle Database Administration
P A R TII
Trang 11last_name VARCHAR2(30),first_name VARCHAR2(30),middle_int CHAR(1));
Altering Tables
You can alter many of the settings of a table through the ALTER TABLE DDL command.The following are some of the things you can do with the ALTER TABLE command:
• Alter or drop column definitions, sizes, and constraints
• Alter table storage parameters, including NEXT and FREELISTS
• Enable constraints (without validating them) and disable constraints
• Move or rename a table
• Manually allocate an extent to a table
• Modify table parameters
• Add, drop, move, or alter partitions
• Modify several table attributes, such as CACHE and NOLOGGINGThere are certain parameters that cannot be changed once an object is created Inparticular, you cannot change the INITIAL parameter in the STORAGE clause The following are several examples of using the ALTER TABLE command:
• To alter the storage clause of a table:
ALTER TABLE dodo STORAGE (NEXT 100k);
• To enable a constraint on the table:
ALTER TABLE my_table ENABLE CONSTRAINT fk_my_table_01;
• To add a unique constraint to a table:
ALTER TABLE phone_list ADD user_code CONSTRAINT line_code UNIQUE;
• To add a primary key to the table:
ALTER TABLE studentADD CONSTRAINT pk_student_idPRIMARY KEY (student_id)USING INDEX
TABLESPACE pk_indexSTORAGE (INITIAL 100k NEXT 100k);
Trang 12• To add a column:
ALTER TABLE student ADD COLUMN (maiden_name VARCHAR2(20));
• To drop a column:
ALTER TABLE student DROP COLUMN maiden_name;
De-allocating Unused Table Space
You may discover that a table has had excessive space allocated to its structure It might
be that the unused space would be better used in another object When this is thecase, you can de-allocate space from the table using the DEALLOCATE UNUSED clause
in an ALTER TABLE statement When this command is issued, Oracle will de-allocatespace from the table Two settings influence how much space you can de-allocate withthis command:
The high-water mark You can only de-allocate space in the table from thehigh-water mark up Recall that the high-water mark is the highest position in thetable that has ever been used to store data Oracle will de-allocate space from theend of the table being de-allocated (this same command can be used for indexes,table partitions, and clusters as well) to the high-water mark The optional KEEPclause allows you to reserve some space in the table, rather than de-allocate all ofthe space above the high-water mark
The MAXEXTENTS clause Oracle will not allow you to de-allocate spacesuch that the number of extents allocated to the object will fall below the MAX-EXTENTS clause of the object from which you are de-allocating space The de-allocation process can actually cause Oracle to modify the INITIAL STORAGEclause value as well as the MINEXTENTS value, if the DEALLOCATE commandwill cause space to be de-allocated below these points
Here are examples of using the DEALLOCATE UNUSED clause
ALTER TABLE student DEALLOCATE UNUSED;
ALTER TABLE parent DEALLOCATE UNUSED KEEP 200m;
Dropping Tables
Removing a table (hash, temporary, or index-organized) is done via the DROP TABLEstatement In most cases, this is a straightforward process The DROP TABLE com-mand includes an optional CASCADE CONSTRAINTS clause The CASCADE CON-STRAINTS clause will cause all associated referential integrity constraints to be removedwhen you drop the table If there is a foreign key associated with the table to be
Oracle Database Administration
P A R TII
Trang 13dropped, you will need to use the CASCADE CONSTRAINTS clause in order to dropthe table
Here are examples of using the DROP TABLE statement:
DROP TABLE dodo;
DROP TABLE my_table CASCADE CONSTRAINTS;
Viewing Table Information
Several data dictionary views can be used to manage tables in Oracle These views areused to locate the table and identify its columns and the other information in thetable Each of the views discussed here comes not only in the DBA_ variety, but also
in USER_ and ALL_ versions
The DBA_TABLES View
The DBA_TABLES view provides basic table information, including the owner of thetable, the name of the table, the tablespace the table resides in, and many of the sta-tistics collected by the Oracle statistics collection process If you need to find out whoowns a table or what its storage characteristics are, this is the place to go
The following is a listing of the description of the view
SQL> DESC dba_tablesName Null? Type - - -OWNER NOT NULL VARCHAR2(30)TABLE_NAME NOT NULL VARCHAR2(30)TABLESPACE_NAME VARCHAR2(30)CLUSTER_NAME VARCHAR2(30)IOT_NAME VARCHAR2(30)PCT_FREE NUMBERPCT_USED NUMBERINI_TRANS NUMBERMAX_TRANS NUMBERINITIAL_EXTENT NUMBERNEXT_EXTENT NUMBERMIN_EXTENTS NUMBERMAX_EXTENTS NUMBERPCT_INCREASE NUMBERFREELISTS NUMBERFREELIST_GROUPS NUMBERLOGGING VARCHAR2(3)
Trang 14BACKED_UP VARCHAR2(1)NUM_ROWS NUMBERBLOCKS NUMBEREMPTY_BLOCKS NUMBERAVG_SPACE NUMBERCHAIN_CNT NUMBERAVG_ROW_LEN NUMBERAVG_SPACE_FREELIST_BLOCKS NUMBERNUM_FREELIST_BLOCKS NUMBERDEGREE VARCHAR2(10)INSTANCES VARCHAR2(10)CACHE VARCHAR2(5)TABLE_LOCK VARCHAR2(8)SAMPLE_SIZE NUMBERLAST_ANALYZED DATEPARTITIONED VARCHAR2(3)IOT_TYPE VARCHAR2(12)TEMPORARY VARCHAR2(1)SECONDARY VARCHAR2(1)NESTED VARCHAR2(3)BUFFER_POOL VARCHAR2(7)ROW_MOVEMENT VARCHAR2(8)GLOBAL_STATS VARCHAR2(3)USER_STATS VARCHAR2(3)DURATION VARCHAR2(15)SKIP_CORRUPT VARCHAR2(8)MONITORING VARCHAR2(3)
Here is an example of a query against the view and its results:
SELECT owner, table_name, initial_extent, next_extent, pct_free, pct_used
FROM dba_tablesWHERE owner=’SCOTT’;
OWNER TABLE_NAME INITIAL_EXTENT NEXT_EXTENT PCT_FREE PCT_USED - - - - - -SCOTT BONUS 10240 10240 10 40SCOTT CHILD 10240 10240 10 40SCOTT DEPT 10240 10240 10 40SCOTT EMPLOYEE 102400 102400 10 40
Oracle Database Administration
P A R TII
Trang 15SCOTT GIJOE 10240 10240 10 40SCOTT PARENT 10240 10240 10 40SCOTT PLAN_TABLE 10240 10240 10 40SCOTT RANK 10240 10240 10 40SCOTT SALGRADE 10240 10240 10 40SCOTT STUDENTS 10240 10240 10 40SCOTT ZOCALO 10240 10240 10 40
The DBA_TAB_COLUMNS View
The DBA_TAB_COLUMNS view is used to locate specific information about columns
in a table, including the name of the column, the datatype of the column, the sion of the column, and statistical information gathered by the Oracle statistics col-lection process The following is a listing of the description of this view
preci-SQL> DESC dba_tab_columnsName Null? Type - - -OWNER NOT NULL VARCHAR2(30)TABLE_NAME NOT NULL VARCHAR2(30)COLUMN_NAME NOT NULL VARCHAR2(30)DATA_TYPE VARCHAR2(106)DATA_TYPE_MOD VARCHAR2(3)DATA_TYPE_OWNER VARCHAR2(30)DATA_LENGTH NOT NULL NUMBERDATA_PRECISION NUMBERDATA_SCALE NUMBERNULLABLE VARCHAR2(1)COLUMN_ID NOT NULL NUMBERDEFAULT_LENGTH NUMBERDATA_DEFAULT LONGNUM_DISTINCT NUMBERLOW_VALUE RAW(32)HIGH_VALUE RAW(32)DENSITY NUMBERNUM_NULLS NUMBERNUM_BUCKETS NUMBERLAST_ANALYZED DATESAMPLE_SIZE NUMBERCHARACTER_SET_NAME VARCHAR2(44)CHAR_COL_DECL_LENGTH NUMBER
Trang 16GLOBAL_STATS VARCHAR2(3) USER_STATS VARCHAR2(3) AVG_COL_LEN NUMBER
Here is an example of a query against the view and its results:
SELECT owner, table_name, column_name, data_type, data_length, column_id
FROM dba_tab_columns WHERE owner=’SCOTT’
AND table_name=’GIJOE’
ORDER BY column_id;
OWNER TABLE_NAME COLUMN_NAM DATA_TYPE DATA_LENGTH COLUMN_ID
- - -
-SCOTT GIJOE PART_ID NUMBER 22 1
SCOTT GIJOE TOY_NAME VARCHAR2 30 2
SCOTT GIJOE TOY_RANK NUMBER 22 3
The DBA_EXTENTS View The DBA_EXTENTS view provides information about extent allocations for a given object in Oracle, including tables and indexes Here is a description of the view: SQL> DESC dba_extents Name Null? Type - - -OWNER VARCHAR2(30) SEGMENT_NAME VARCHAR2(81) PARTITION_NAME VARCHAR2(30) SEGMENT_TYPE VARCHAR2(18) TABLESPACE_NAME VARCHAR2(30) EXTENT_ID NUMBER FILE_ID NUMBER BLOCK_ID NUMBER BYTES NUMBER BLOCKS NUMBER RELATIVE_FNO NUMBER
The following is an example of using this view to determine how many extents an object has been allocated
SELECT owner, segment_name, segment_type, count(*) “Total_extents”
FROM dba_extents
Oracle Database Administration
P A R T II
Trang 17WHERE owner=’SCOTT’
GROUP BY owner, segment_name, segment_type ORDER BY 1,3,2;
OWNER SEGMENT_NAME SEGMENT_TYPE Total_extents
- -
-SCOTT TEST CLUSTER 2
SCOTT TEST2 CLUSTER 1
SCOTT IX_TEST_RGF INDEX 1
SCOTT IX_TEST_RGF_01 INDEX 1
SCOTT PK_CHILD INDEX 1
SCOTT PK_CHILDREN INDEX 1
SCOTT PK_PARENT INDEX 1
SCOTT AUDIT_TABLE TABLE 1
SCOTT BONUS TABLE 1
SCOTT CHILD TABLE 1
SCOTT DEPT TABLE 1
SCOTT DUMMY TABLE 1
SCOTT EMPLOYEE TABLE 1
SCOTT GIJOE TABLE 1
SCOTT HOLD_EVENTS TABLE 4
The DBA_SEGMENTS View The DBA_SEGMENTS view provides a look at the individual segments in the database, including tables, indexes, and clusters The following is a description of the view SQL> DESC dba_segments Name Null? Type - - -OWNER VARCHAR2(30) SEGMENT_NAME VARCHAR2(81) PARTITION_NAME VARCHAR2(30) SEGMENT_TYPE VARCHAR2(18) TABLESPACE_NAME VARCHAR2(30) HEADER_FILE NUMBER HEADER_BLOCK NUMBER BYTES NUMBER BLOCKS NUMBER EXTENTS NUMBER INITIAL_EXTENT NUMBER
Trang 18NEXT_EXTENT NUMBERMIN_EXTENTS NUMBERMAX_EXTENTS NUMBERPCT_INCREASE NUMBERFREELISTS NUMBERFREELIST_GROUPS NUMBERRELATIVE_FNO NUMBERBUFFER_POOL VARCHAR2(7)
Here is an example of using this view to get information about segments:
SELECT owner, segment_name, segment_type, tablespace_name, sum(bytes) bytes
FROM dba_segmentsWHERE owner=’SCOTT’
GROUP BY owner, segment_name, segment_type,tablespace_name
ORDER BY 5;
OWNER SEGMENT_NAME SEGMENT_TY TABLESPACE_NAME BYTES - - - - -SCOTT AUDIT_TABLE TABLE USERS 10,240SCOTT BONUS TABLE USERS 10,240SCOTT CHILD TABLE USERS 10,240SCOTT DUMMY TABLE USERS 10,240SCOTT GIJOE TABLE USERS 10,240SCOTT IX_TEST_RGF INDEX INDEXES 10,240SCOTT HOLD_EVENTS TABLE USERS 71,680SCOTT EMPLOYEE TABLE USERS 102,400SCOTT TEST2 CLUSTER SYSTEM 102,400SCOTT NEWTABLE TABLE USERS 4,382,720
Oracle Database Administration
P A R TII
Trang 19Index Fundamentals
Oracle uses different kinds of indexes The primary index types are B*Tree indexes andbitmap indexes Oracle8i introduces function-based indexes Let’s look at how theseindexes are handled internally and when using an index is helpful
N OTE Indexes do not store columns with values that are NULL Thus, if you have aquery with a limiting condition that is NULL, Oracle will not be able to use any index to sat-isfy that particular condition However, queries with NOT NULL limitation criteria can useindexes
B*Tree Indexes
The standard type of index that Oracle uses is called a B*Tree index
Think of a B*Tree index as something like a tree (hence the name) At the top of
the tree is a single node called the root Extending up (or down if you are in the
south-ern hemisphere) from this node is a series of leaf blocks There may be one or moreleaf blocks associated with the root node In the root, there are pointers to the differ-ent data stored in each leaf node
For example, in a phone book, in the head node, all last names from A to L mighthave a pointer to the first leaf block, and all last names from M to Z might have apointer to the second leaf block as shown in Figure 6.2 This progression will continuethrough a third (and perhaps more) level of nodes Now suppose that you are lookingfor the name Adams You would go from the root node to the first node below it,because the first node below the head node contains all last names beginning with Athrough L In the second-level node, you find pointers for the values A through Lagain This time, they are pointing to another level of leaf blocks below this level Say,for example, that there are 13 leaf nodes below the middle leaf node The middle leafnode, for the name beginning with A, would point to the node below it that containsthe A records Finally, in the bottom leaf node, you would search for Adams, whichyou would find quickly
B*Tree indexes can be associated with one or more columns in a given table Alongwith the values of the specific index columns, the B*Tree index also contains theROWID of each row associated with an index entry Oracle will return the ROWID toanother process during the execution of the statement Typically, that process willthen access the table via ROWID, which is the fastest method of getting to distinctdata in a table
Trang 20be inefficient You should build B*Tree indexes on columns with high cardinality, or ahigh degree of distinct values If your column were populated with only Ys and Ns, itwould not make a good candidate for a B*Tree index in most cases This is becausethere are about two to four times the I/O operations required to get one row from atable using an index than are required to do a full table scan
For example, suppose that you have a table with 10,000 rows It has a columncalled YES_NO, which is populated with 6000 values of Y and 4000 values of N If youwant to count all records with a Y, how many I/O operations would that take? For afull table scan, you are looking at 10,000 logical I/O operations (one for each row)
With an indexed lookup, there will be 6000 logical I/O operations to the index, plus
6000 lookups in the table, plus 1 or 2 I/O operations for the root and leaf blocklookups needed to get to the proper leaf nodes That makes 12,002 logical I/O opera-tions for an indexed lookup, compared with 10,000 for a full table scan In this case,the index is not the best way to get the information
Now suppose that the YES_NO column in the sample table has 9999 Ys in it andjust 1 N In this case, a full table scan requires a 10,000-row lookup With the index lookup, only three or four I/O operations are involved (two to three for the indexlookup, and one for the table lookup) So, in this case, the index is the best choice
Bitmap Indexes
Bitmap indexes were introduced in Oracle 7.3, and they can be very powerful if usedproperly Bitmap indexes are used to provide performance improvements for queriesagainst nonselective columns in a table, if these nonselective columns are part of theselectivity criteria (the WHERE clause) For example, performance might improve
Freeman (ROWID)Lewis (ROWID)
Oracle Database Administration
P A R TII