Oracle Database ObjectsThe following sections provide some interesting information on Oracle database objects (tablespaces, tables, indexes). To keep the reading lively, I’ll intersperse some tuning information and hints, tips and tricks in the discussion. This section is not an all-encompassing guide to administering Oracle objects, rather it is a collection of information that I felt that was important to all DBAs, regardless of the experience level.
What Database Are You Working In?Working in the wrong database is a common problem for database experts as well as their less experienced counterparts. How many times have YOU found yourself running statements in the wrong environment? Feel free to include me in that not so select group. The operating system command SET can be used in Windows systems to display environment variables. The ENV command can be used to display the environment variables in UNIX. Many seasoned database administrators change their UNIX shell prompt in their.profile to display the current Oracle SID. Displaying the current Oracle SID in the shell’s prompt provides a continuous reminder to the DBA of the database they are working in.
GLOGIN.SQL and LOGIN.SQLAdministrators are able to use two configuration files, glogin.sql and login.sql to customize their SQL*PLUS environment (including the prompt). When a user activates SQL*PLUS and connects to the database, SQL*PLUS will execute the contents of the glogin.sql configuration file in $ORACLE_HOME/sqlplus/admin.
After the glogin.sql file has been executed, SQL*PLUS will execute login.sql. Oracle will look for the login.sql file in the current working directory (where you started SQL*PLUS) and the operating system environment variable sqlpath. Remember that the statements in the login.sql file take precedence over glogin.sql. The exact names of these files may be different on some operating systems. Check the Oracle installation and administration guides provided for your operating system for the exact names.
Here's an example of my glogin.sql file on my PC that displays the time and instance name in my SQL*PLUS prompt. The file also contains a few formatting commands to format SQL*PLUS output.
Glogin.sql
COLUMN file_name FORMAT a44
COLUMN tablespace_name FORMAT a20
COLUMN owner FORMAT a15
COLUMN segment_name FORMAT a20
set lines 132
set pages 100
set termout off
col dbname new_value prompt_dbname
select instance_name dbname from v$instance;
set sqlprompt "&&prompt_dbname> "
set termout on
set time onChoosing a Database Block SizeMany database specifications can be changed after the database has been created. For releases prior to Oracle9i, one important exception is the database block size. Although Oracle9i allows you to specify different block sizes, choosing the default block size for an Oracle9i database is still critical.
Configuring the Oracle database to use bigger blocks often leads to an increase in performance since bigger blocks allow more data to be transferred per I/O call (the database block is the unit of I/O for the database engine). Larger blocks sizes also allow more key values to be stored in B-tree index blocks, which reduces the index’s height and improves the performance of SQL statements that use the index structures.
Since you are storing more data per block, bigger blocks may increase the number of transactions that access data and index blocks concurrently. If you have a very high number of concurrent users, you may need to adjust the initrans and maxtrans parameters for data objects that have a higher than normal transactional concurrency.
A few quick thoughts on database block sizes:
A block size of 2048 used to be the preferred database block size. This was before the era of high-speed disk drives and controllers. Now that more data can be transferred more quickly, 2048 has been replaced with 8192.
A database block size of 8192 is currently the recommended block size for most database configurations.
Use database block sizes of 16K and 32K for applications that have row sizes greater than 8K. If the application data has row sizes that are greater than 8K, using 16K or 32K block sizes allows more rows to be stored per block and decreases the I/O costs of accessing a single or multiple row(s).
Use database block sizes of 16K and 32K for data warehouses and decision support systems. Decision support systems and data warehouses, by their nature, access large volumes of data to provide users with the information required to make business decisions. You will reduce disk I/O by storing more data in each block.
The Oracle Database Fundamentals I (1Z0-031) and the Oracle Database Performance Tuning (1Z0-033) certification tests will have a few questions on database blocks. Test candidates should know:
The db_block_size parameter
How to specify non standard block sizes in Oracle9i
What tablespaces must use the default Oracle block size
How to change the default Oracle block size
The contents of an Oracle block
What affect the PCTFREE and PCTUSED parameters have on data block free space
The differences between PCTFREE/PCTUSED and automatic segment space management
What row chaining and row migration are and the affect they have on database performance
How to correctly size the default Oracle block size
Copying Databases Between ServersDon't use the EXPORT/IMPORT utility to copy databases between servers running the same operating system. Execute the following steps to speed the transfer:
1. Execute the ALTER DATABASE BACKUP CONTROLFILE TO TRACE; statement on the source server.
2. Bring the database down and copy the trace file, parameter file, all datafiles, control files and redo logs to the new server.
3. Make the following changes to the trace file created in step 1:
4. If you are changing the database name, change the first line of the create statement to reflect the new name and change the REUSE keyword to SET.
5. Change NORESETLOGS to RESETLOGS.
6. Change directory names if they have changed on the new database server.
7. Delete all comments and lines that have a # in front of them (#s aren't comments in all Oracle tools).
8. Connect as INTERNAL and run the SQL statement contained in the trace file. It will start up the database in NOMOUNT stage and recreate the control files. The SQL statement’s final step will be to MOUNT and then OPEN the database.
What happens if you can’t take the database down? You’ll have to execute a hot backup, which means your database will have to be in ARCHIVELOG mode. Here are the steps you will have to perform to copy an online database to a new server.
Execute the hot backup, making sure all of the files are backed up. Note the time after the last tablespace is backed up.
Execute ALTER SYSTEM SWITCH LOGFILE; to archive the last redo log that was active during the hot backup.
Execute the ALTER DATABASE BACKUP CONTROLFILE TO TRACE; statement on the source server.
Execute the ALTER DATABASE BACKUP CONTROLFILE TO filename; statement on the source server.
Copy the datafile backups, both controlfile backups (backup to trace, backup to filename) and the archived redo logs that were generated during the hot backups. Make sure you match the directory structures that are on the source platform.
Execute the RECOVER DATABASE UNTIL TIME XXXXX USING BACKUP CONTROLFILE; to recover the database on the new platform. Pick a time just after the hot backup was complete. If the file or directory names will be different on the target server, bring the database to MOUNT stage and issue the ALTER DATABASE RENAME FILE oldfilename TO newfilename command to point the control file to the new locations.
If you need to change the database name, execute the following changes to the trace file created in step 1:
o Change the first line of the create statement to reflect the new name and change the REUSE keyword to SET.
o Change NORESETLOGS to RESETLOGS.
o Change directory names if they have changed on the new database server.
o Delete all comments and lines that have a # in front of them (#s aren't comments in all Oracle tools).
o Connect as INTERNAL and run the SQL statement contained in the trace file. It will start up the database in NOMOUNT stage and recreate the control files. The SQL statement’s final step will be to MOUNT and then OPEN the database.
Oracle TablespacesStudents that are new to Oracle often become confused when instructors begin discussing Oracle’s logical and physical storage structures. Every Oracle database is made up of data files that contain the database’s data. The logical database structures (tables, indexes, etc.) define and format the data that is physically stored in the datafiles. The logical storage structure that ties the physical structures (files, blocks of data) to the logical structures (tables, indexes, etc.) is the tablespace. The DBA specifies the datafile name, size, and location during tablespace creation. The physical datafile(s) are created when the create tablespace statement is executed. The DBA then assigns various logical objects to a specific tablespace during their creation.
Temporary TablespacesSorting rows as efficiently as possible is one of the keys to high performance database applications. Oracle will automatically perform sorting operations on row data requested by CREATE INDEX, SQL ORDER BY, SQL GROUP BY statements and some join operations. For optimal performance, most sorts should occur in memory. Oracle8i allocates a private sort area (defined by the sort_area_size and sort_area_retained_size parameters) while Oracle9i also allows a shared sort area (pga_aggregate_target parameter) to be defined.
For many applications, sorting on disk cannot be avoided. Administrators are able to increase the performance of disk sorts by creating a tablespace that is optimized for sorting. Data sorted in a permanent tablespace requires many space allocation calls to allocate and deallocate temporary segments. If a sort tablespace is declared to be temporary, all processes requesting a sort operation share one sort segment in that tablespace. The first user process to sort creates the initial sort segment. All other sort operations share that sort segment by taking extents in the segment that was initially created.
Temporary tablespaces improve the performance of sorts that cannot be performed completely in memory. The performance benefits of bypassing the normal space allocation mechanism should not be taken lightly. The processing costs of each space allocation/deallocation execution can be roughly compared to the resources consumed by ten insert/update/delete statements.
You create a temporary tablespace to be temporary by using the TEMPORARY keyword of the CREATE TABLESPACE and ALTER TABLESPACE commands. It is important to note that temporary tablespaces cannot contain permanent objects (tables, indexes, rollback segments, etc.).
The Oracle Database Fundamentals I (1Z0-031) and the Oracle Database Performance Tuning (1Z0-033) certification tests will have a few questions on temporary tablespaces. Test candidates should have a firm understanding of:
What the temporary tablespace is used for
The differences between permanent and a temporary tablespace used for sorting
How to create a default temporary tablespace in Oracle9i
The impact default temporary tablespaces have on user administration
Where the user sorts if a default temporary tablespace is not specified
Create Tablespace Temporary vs. Create Temporary Tablespace
The Oracle SQL reference manual provides two different statements to create a temporary tablespace:
CREATE TABLESPACE temp DATAFILE ‘d:\oradata\orcl\tempdata.dbf.’ The statement above creates a tablespace that, although described as "temporary" in dba_tablespaces, has one or more permanent datafiles associated with it. The tablespace is designed to hold sort data and manages segments and extents differently (see above) than its permanent tablespace counterparts.
CREATE TEMPORARY TABLESPACE temp TEMPFILE ‘d:\oradata\tempdata.dbf.’ This statement creates a true temporary tablespace. This eliminates the need to back up the temporary tablespace, which results in faster backups and a reduction in disk space. Information describing true temporary tablespaces is found in the v$tempfile and dba_temp_file views. No information is stored in the dba_data_files and v$datafile views, which describe permanent datafiles.
The database will start even if this file is missing. The only way the administrator will know that the file is gone is when the first sort tries to overflow to disk. A very explicit error message will be generated stating that the sort could not complete due to a missing or invalid sort file. The administrator will be forced to drop and recreate the temporary tablespace before sorting to disk can take place.
PartitioningData partitioning is an absolute requirement for the administration and management of large database tables and indexes. In Oracle, a partitioned table is divided into components called tablespace partitions (see Figure 1). All table partitions have the same logical attributes (columns, datatypes, and integrity constraints). Oracle allows administrators to store each partition in a separate tablespace. Separate tablespaces allow each partition to have different physical storage characteristics (PCTFREE, PCTUSED, PCTINCREASE etc.).
Partitioning of data into separate tablespaces provides the following advantages:
Increases availability - Data corruption is less likely to occur across multiple tablespaces. If data does become corrupted in a single, partitioned tablespace, all other partitions are still available for queries and DML. In addition, you can perform certain administrative operations against a single tablespace partition. Once again, all other tablespace partitions remain unaffected and are available for access.
Easier administration - Administrative operations (import/export, analyze, backup/recovery and load) can be performed on individual partitions. Remaining partitioned tablespaces continue to be available for access.
Partitioning allows applications to take advantage of "rolling window" data operations. Rolling windows allow administrators to roll off (and un-plug data using Oracle’s transportable tablespace feature) that are no longer needed. For example, a DBA may roll off the data in the tablespace containing last April’s data as they add this year’s data for April. If the data is ever needed again, administrators are able to pull the data from tape and plug the data back into the database using the transportable tablespace.
Increases performance - Partitioning allows you to distribute data and balance the I/O load across several devices. The Oracle optimizer is partition aware and will create query plans that access only those partitions and subpartitions needed to satisfy the query's request (partition pruning). Partition pruning is critical in providing quick access to data that is logically grouped together (i.e. date, customer id, etc.).
Partition pruning allows administrators to create large data stores and still provide fast access to the data. There is no difference in query performance between a 20 GIG database and a 200 GIG database if the optimizer prunes the data to create access paths to only those partitions required to solve the query. Partitioned tablespaces also increase the performance of bulk data loads. Oracle’s SQL*Loader supports concurrent loading of individual partitions and entire partitioned tables.
Oracle 8 - Range PartitioningOracle8 introduced the first partitioning technique called range partitioning. To create a range partitioned table in Oracle, you code a partitioning clause for the table that includes a key-based specification that is used to map rows to specific partitions and a partition description that describes each partition:
CREATE TABLE sales_account_history_data
(acct_no NUMBER (5),
person VARCHAR2 (30),
week_no NUMBER (2))
PARTITION BY RANGE (week_no)
(PARTITION p1 VALUES LESS THAN (4) TABLESPACE TSP1,
PARTITION p2 VALUES LESS THAN (8) TABLESPACE TSP2,
…
PARTITION px VALUES LESS THAN(53) TABLESPACE TSPx);Rows are placed in the different partitions based on the table’s partitioning key. A partitioning key is a column or set of columns that is associated with a specific tablespace. The example above shows a table that is partitioned by a range of values based on a number.
With range partitioning, the best partition keys are dates, primary keys or foreign key columns. To prevent the overhead associated with migrating rows among partitions, application programs should not update partitioning key columns. To change a value in one of these columns, the application program should delete the row and then reinsert it with the new values. To define a partition, an upper boundary of partitioning key values is hard-coded into the table’s definition. These upper boundaries should distribute the data (more or less) evenly among the different partitions.
Index PartitioningOracle also allows you to create range-partitioned indexes. Oracle uses the same range-partitioning algorithm as it does for tables. Like partitioned tables, Oracle maps rows to specific index partitions based on the index’s partitioning key. The partitioning key of an index must include one or more of the columns that define the index. This allows administrators to create an index that contains multiple columns but partitions the index on a subset of those columns. An index partition is defined exactly like its partitioned table counterpart; an upper boundary of partitioning key values is hard-coded into each tablespace specification.
Equi-Partitioned ObjectsAn index and table that has the same number of partitions are said to be equi-partitioned. Multiple tables and multiple indexes can be equi-partitioned if they meet Oracle’s equi-partition specifications. Please refer to the Oracle Server Concepts manual for a more complete listing of equi-partitioning specifications.
Equi-partitioned objects improve query performance by reducing the number of rows being sorted and joined. The Oracle optimizer is also partition aware. If the optimizer determines that a single index/table partition combination will satisfy a query, it will create an execution plan that accesses the single index and table partition.
Local IndexesYou can ensure that a table and its associated index are equi-partitioned by specifying the local parameter during index creation. All keys in a local index partition point to rows stored in a single table partition. When creating an index using the local parameter, range specifications and a maximum value do not need to be specified. Oracle automatically partitions the local index on the same partitioning key columns as the table it references, creates the same number of partitions and gives each index partition the same partitioning key boundaries.
Global IndexesUnlike their local index counterparts, index keys in a global index may point to rows in more than one table partition (see Figure 4). To create a global index, you specify the GLOBAL parameter (default) during index creation. Global indexes can be equi-partitioned with their tables that they reference, but Oracle will not take advantage of equi-partitioning when generating query plans or executing maintenance operations. The entire index will be affected. To take advantage of Oracle’s equi-partitioned performance improvements, the index must be created as local.
Oracle8i – Hash and Range/Hash Composite PartitioningOracle8i enhanced the Oracle database’s partitioning feature by providing two new partitioning techniques, hash and range/hash composite.
Hash PartitioningHash partitioning allows data to be evenly striped across devices. Hash partitioning uses a hashing algorithm on the partitioning columns to determine row placement in the tablespaces. The more unique the key values are, the more efficient the hashing algorithm will be. In general, the hash-partitioning key should be unique or near unique.
Hash partitioning attempts to evenly divide data among all available partitions. There is no way for the administrator to logically group data together in a partition. As a result, hash partitioning prohibits "partition pruning" from occurring. Hash partitioning also prevents "rolling window" operations from occurring. Rolling windows allow administrators to roll off data that is no longer needed.
Combining Range and Hash Partitioning – Range/Hash Composite Partitioning
Range/hash composite partitioning combines the best of both approaches. A range of values first partitions data then each partition is sub-partitioned into several hash partitions. This provides administrators with the ability to provide customized partitioning per application. The user specifies ranges of values for the primary partitions of the table or index then specifies a number of hash subpartitions.
Oracle9i – List and Range/List Composite PartitioningOracle9i continues to add partitioning functionality to the Oracle database by providing two new partitioning algorithms, list and range/list composite.
List PartitioningList partitioning allows the administrator to map a row to a specific tablespace based on the partitioning key value. The partition is defined by specifying a hard-coded list of individual partition key values. In Oracle9i Release 1, there was no overflow area to hold rows that had keys that were not identified in the list specifications. If an application program attempted to insert a row that had a partitioning key value that did not match any of the specifications, the row was not inserted and an Oracle error code was returned.
Oracle9i Release 2 solves this problem by allowing administrators to specify a default partition. Key values that do not match the list partition specifications are placed in the overflow tablespace. A new DEFAULT attribute has been added to the list partition specification. The example below shows the DEFAULT attribute being specified during partitioned table creation:
CREATE TABLE sales
(salesid NUMBER(9999), transdate DATE, state VARCHAR2(30)…..)
PARTITION BY LIST (state)
(PARTITION region_north VALUES (‘New York’, ‘Maine’)
PARTITION region_south VALUES (‘Florida’, ‘Georgia’)
……….
PARTITION region_ovflw VALUES (DEFAULT));
Range/List Composite PartitioningOracle’s latest release offers a hybrid solution for list partitioning that is a combination of the range and list partitioning techniques. The table is first partitioned by range and then subpartitioned using the list partitioning technique. Unlike composite range-hash partitioning, each subpartition contains a logical division of the data that is specified by the DBA (as opposed to the range-hash technique where the subpartitions are selected by the hashing algorithm itself).
For example, the primary partition could be based on a date range to allow rolling window operations to occur and the second level could be based on a logical grouping (a list of states (i.e. Pennsylvania, New York, Ohio, etc.) is an good example of a logical grouping). The data would be divided according to the date range and divided again according to the state’s name. The example below shows a table using the range-list composite partitioning technique:
CREATE TABLE sales
(salesid NUMBER(9999), transdate DATE, state VARCHAR2(30)…..)
PARTITION BY RANGE (transdate)
SUBPARTITION BY LIST (state)
SUBPARTITION TEMPLATE
(PARTITION region_north VALUES (‘New York’, ‘Maine’)
PARTITION region_south VALUES (‘Florida’, ‘Georgia’))
(PARTITION 2002_quarter1 values less than
(TO_DATE (’01-APR-2002’, ‘DD-MON-YYYY’)),
PARTITION 2002_quarter2 values less than……..
The CREATE TABLE partitioned tablespace above uses the SUBPARTITION TEMPLATE clause to define the subpartitions. If all subpartitions have the same definition, administrators are able to code the subpartition specification once and Oracle will apply the template specification to each main partition that does not override the template with its own subpartition specification. If the template were not used, the subpartition clause would have to be specified after each main partition specification.
Which Partitioning Technique Do I Choose?Choose range partitioning when the partitioning keys have distinct ranges that can be easily defined and do not vary dramatically. The problem with range partitioning is trying to determine what the range specifications are. The DBA should select a range of values that evenly divides the data among the individual tablespace partitions. Dates are excellent candidates for range partitioning keys because they allow the previously discussed rolling window operations to occur. If range partitioning will result in partitions that vary dramatically in size because of unequal key distribution, the DBA should consider other partitioning techniques.
If the DBA wants to use partitioning for performance and manageability but there are no columns that have distinct key ranges, the hash partitioning technique provides an excellent alternative. Since the rows are mapped based on a hashing algorithm, the higher the cardinality (the number of different values) the partitioning key contains, the more evenly the data will be divided among the different partitions. Many DBAs create an artificial series of numbers that are used as input to the hashing algorithm. These unique values ensure that the hashing algorithm evenly divides the rows among the tablespace partitions.
If you need specific control over the mapping of rows to tablespace partitions, use the list partitioning technique. List partitioning allows the DBA to logically group the data among the different partitions. Sales region would be an excellent example of a column that would lend itself to the list partitioning technique. The DBA would be able to divide the data among the partitions based on the company’s different sales regions.
Range/hash composite partitioning provides the manageability and availability benefits of range partitioning with the data distribution advantages of hash partitioning. Data skew is unlikely, because the user can always add or drop subpartitions within a partition to maintain even distribution of each container. Rolling windows of historical data are easily maintained by adding or dropping primary partitions with no effect on subpartitions in other primary partitions.
The range-list composite partitioning method provides for partitioning based on a two-level hierarchy. For example, the primary partition could be based on a date range to allow rolling window operation to occur and the second level could be based on a logical grouping (a list of state codes (i.e. PA, NY, OH, etc.) is an good example of a logical grouping). The data would be divided according to the date range and divided again according to the state’s abbreviation.
The Oracle Database Performance Tuning (1Z0-033) certification test will contain a few questions on tablespace partitioning. Test candidates should understand:
The basic partitioning algorithms (range, list, hash, composite)
How to specify partitioning during table creation
When to use a specific partitioning algorithm
Oracle9i Tablespace ChangesOracle9i provides the database administrator with a variety (read that bewildering array) of new tablespace parameters and block sizes. Administrators are now able to create Oracle managed tablespaces, user managed tablespaces, locally managed tablespaces, dictionary managed tablespaces, specify AUTOALLOCATE, UNIFORM, PERMANENT, UNDO as well as select block sizes of 2K, 4K, 8K, 16K, or 32K.
The tablespace definition below combines a few of the aforementioned options:
CREATE TABLESPACE oracle_local_auto DATAFILE SIZE 5M BLOCKSIZE 2K;