Oracle Tables DDL
CREATE Table
Table placement in relation to other database objects is important for optimal database performance.
Attempt to minimize contention by placing tables away from their associated indexes and away from
other I/O-intensive database objects such as redo logs and rollback segments. For very large
tables consider manually splitting tables up amongst several disks. This process would also require
sizing the table extents such that they just fill a single tablespace datafile. User objects including
tables should not be placed in the SYSTEM tablespace. The SYSTEM tablespace contains data dictionary
objects. Serious datafile contention could result by placing user objects into the SYSTEM tablespace
and can seriously affect performance.
Relational and Object Tables
- GLOBAL TEMPORARY - temporary table visible to a session only, ie. session or transaction specific. Thus only the data inserting data in the temporary table can see that session specific data. On COMMIT the rows can either be DELETEd or PRESERVEd. These temporary tables can also have temporary indexes.
Relational Table
Object Table
- OF object type - each row will represent an object data type.
Relational and Object Properties
- table_column - unique within a table. Column names can contain reserved words or spaces if enclosed in quotes.
- column_format -
- CHAR[(size)] - defaults to 1 byte if not specified, maximum 255 characters and right-side padded.
- VARCHAR2(size) - variable length upto 2000 characters.
- DATE - standard Oracle format is dd-MMM-99.
- LONG - upto 65,535 bytes of characters, one LONG per table.
- RAW(size) - raw binary data upto 2000 bytes.
- LONG RAW - raw binary data in hexadecimal format upto two gigabytes maximum.
- ROWID - non-user definable internal data type. Uniquely identifies table rows.
- NUMBER(p,s) - numeric data with p = precision and s = scale. Defaults to p = 38 and s = null.
- DECIMAL(p,s) - as NUMBER.
- INTEGER - defaults to NUMBER(38).
- SMALLINT - as INTEGER.
- FLOAT - as NUMBER(38).
- FLOAT(b) - NUMBER with precision of 1 to 126.
- REAL - as NUMBER(63).
- DOUBLE PRECISION - as NUMBER(38) with default as a floating point when no scale specified.
- column_constraint - limits placed on either a table or a column. The constraint_name is optional. There can be unlimited CHECK-type constraints per column and a NOT NULL is converted internally into a CHECK constraint by Oracle. A CHECK constraint requires that a condition be true or unknown for each value in the column affected. Constraints can be added, enabled, disabled or dropped.
- CONSTRAINT - name constraint type OR ...
- NULL CONSTRAINT constraint_name
- NOT NULL CONSTRAINT constraint_name
- PRIMARY KEY CONSTRAINT constraint_name
- UNIQUE CONSTRAINT constraint_name
- CHECK condition CONSTRAINT constraint_name
- REFERENCES table_name (column_name)CONSTRAINT constraint_name
- DEFAULT default_value_clause
- ENABLE or DISABLE - enables or disables constraints or triggers for a table.
Physical Properties
- ORGANIZATION HEAP - no order of data row storage.
- ORGANIZATION INDEX - index-organized table. The data rows are maintained in an index defined by the primary key.
- CLUSTER - an index-organised table is an alternative to a cluster.
- PCTTHRESHOLD - percentage of space reserved for an index-organised table row where row sections exceeding the threshold are stored in the overflow segment. PCTTHRESHOLD must be between 1 and 50%.
- COMPRESS - eliminates repeated occurences of primary key column values.
- OVERFLOW - overflow segment for index-organised tables.
- INCLUDING - column where index-organised table is divided into index and overflow.
LOB Parameters
Table Properties
- PARALLEL parallel_clause or NOPARALLEL - default parallelism of the table in a parallel query situation and thus sets how many processors will be used.
- CACHE or NOCACHE - do or do not cache the table in the SGA (shared global area).
- MONITORING - collect modification statistics. This will affect performance.
- Partitioning clauses - please refer to the separate section on Partitioning.
Segments Clause
- PCTFREE & PCTUSED - PCTFREE designates maximum block usage and PCTUSED designates minimum block usage.
- PCTFREE - how much space to leave in each block for future updates and the addition of new rows. The default is 10%. PCTFREE is table-usage specific. If set too low can result in chaining or wastage of disk space if set too high since the table will require more blocks than normal. Both result in degradation of performance. If a block's free space drops below PCTFREE it is removed from the freelist.
- Tables with large numbers of updates should have a high PCTFREE value.
- Static table should have a low PCTFREE value.
- PCTUSED - the minimum level of space to maintain in a block. Defaults to 40%. A block becomes a candidate for updates if its storage falls below PCTUSED. This parameter only applies for DELETE DML activity because a block is not placed on the updatable list until PCTUSED is reached from deletion activity. For tables with frequent inserts and updates PCTUSED should be set low. If PCTFREE is left at 10% and PCTUSED is set high there may be an increase in processing costs due to freelist maintenance.
- INITTRANS & MAXTRANS - these paremeters determine the number of active transactions that can access a single block concurrently.
- INITTRANS - initial number of active transactions that are allocated within each block. A large value will reduce the amount of space available for data in a block. A change to this parameter only affects blocks added after the change.
- MAXTRANS - maximum number of active transactions that can update a block concurrently.
- STORAGE - storage clause values determine how extents will be allocated for tables, clusters and indexes.
- TABLESPACE - tablespace if other than the user default.
More Simple Forms of the CREATE TABLE Statement.
CREATE TABLE <table_name>
(
<column_name 1> <datatype> [NOT NULL],
<column_name 1> <datatype> [NOT NULL],
...
<column_name n> <datatype> [NOT NULL];
)
... OR ...
CREATE TABLE <table_name> AS [query];
... OR ...
CREATE TABLE <table_name>
[(
<column_name 1> <datatype> [NOT NULL],
<column_name 1> <datatype> [NOT NULL],
...
<column_name n> <datatype> [NOT NULL];
)]
AS [query];
Primary and Secondary Keys
FOREIGN KEY (column, column)
REFERENCES table_name (column, column)
CONSTRAINT constraint_name
PRIMARY KEY (column, column)
USING INDEX TABLESPACE tablespace_name
STORAGE (storage_clause)
CONSTRAINT constraint_name
In the example above the foreign key constraint is enforced such that its values must match its
corresponding primary or unique key values. No index is automatically generated.
Indexes should be maintained on foreign keys or excessive full table scans may result. A primary key
will automatically have an index generated named for the constraint. A primary key automatically
forces its column or columns to be not null and if a single column, unique. For a composite set of
columns, the resulting set must be unique. Foreign and primary key constraints are known as referential
constraints. Referential integrity violations occur when a parent record is deleted and child records
still exist. Additionally, user-defined constraints are used to enforce business rules.
Comments on Table Columns
Comments can be created on or attached to columns in tables as shown in the example below.
COMMENT ON COLUMN SALARY.LOWLIMIT IS 'Low limit of this salary grade';
ALTER Table
Add columns, change column types and lengths plus add, change or drop column constraints. Table
columns can not be dropped or renamed. Table storage characteristics can be altered for subsequent
extents or data blocks only. The CASCADE option with DISABLE or DROP clauses allows cascading to all dependant integrity constraints.
DISABLE switches a constraint off; for PRIMARY and UNIQUE keys the indexes are dropped aswell.
ENABLE or ADD turns a constraint on or creates it. With UNIQUE and PRIMARY KEY constraints an index
is created. If the index clause is not specified the index is created in the default tablespace of the
creator with the tablespace default storage characteristics.
ALTER TABLE <table_name> ADD (<column_name> <datatype> [NOT NULL]);
ALTER TABLE <table_name> MODIFY (<column_name> <datatype> [NOT NULL]);
RENAME <old_table_name> TO <new_table_name;>
ALTER TABLE allows for allocation of new extents with specification of size and placement in different tablespaces
and deallocation of unused extents. When deallocating unused extents the bytes reserved for future inserts
above the highest value are set using the KEEP clause of the DEALLOCATE clause. Space unused above the
high-water mark can be deallocated. Space above the high_water mark cannot be deallocated even if that
space is unused.
If a table increases in size at a rate making calculation of exact sizing difficult
then increase PCTINCREASE. Do space calculations as accurately as possible and then apply a 50% unknown
factor in order to allocate enough space and setting of PCTINCREASE to zero. Sometimes the only method
of extreme table growth management is by setting PCTINCREASE to a high value.
- ADD - add nullable or non-nullable columns.
- MODIFY.
- Increase column sizes or alter numeric columns to different precisions.
- Decrease column length and change datatype for all columns containing all null values in its rows.
- PCTFREE, PCTUSED, INITRANS or MAXTRANS.
- STORAGE - as with the STORAGE clause.
- PARALLEL.
- CACHE/NOCACHE.
- DROP.
- DEFAULT - column default value setting.
- ENABLE/DISABLE - constraint enablement or disablement. CASCADE option causes dropping of all dependant integrity constraints.
- DEALLOCATE UNUSED - deallocates unused space. Specify a safety margin using the KEEP option.
- PRIMARY, NOT NULL, CHECK or FOREIGN KEY - add these constraints using the ADD CONSTRAINT clause.
- Can not do with ALTER TABLE
- Modify columns with shorter values or of a different datatype.
- Add a NOT NULL column to a table containing rows.
- Alter a column to NOT NULL if the column has null values.
- Drop a column.
- Rename a column.
- Change column datatype to an incompatible datatype.
- MOVE - relocate data of non-partitioned tables into new segments, ie. another tablespace. This would include moving of LOB segments.
- ALLOCATE EXTENT / DEALLOCATE UNUSED - allows allocation of new extents and/or deallocation of used extents for individual tables within a tablespace.
- Dropping Columns - Oracle8i allows dropping of columns from tables. THis can take a long time, especially with large tables and can impact availability in production environments. Thus columns can be set to unused. Unused columns have their names removed from meta-data such that those names can be reused, however, their data is not removed and disk space is not reclaimed. Ultimately, unused columns can be dropped thus removed unused column data.
DROP Table
LOCK TABLE Command
The LOCK TABLE command overrides automated locking and denies access to users for a table or view as long as the lock is in place.
The table or view will remain ina locked state until transaction COMMIT or ROLLBACK. Thus the locking a table is transactional at the
session level. Note that the locking a table blocks only WRITE access and not READ.
- lockmode
- ROW SHARE - locked table concurrent access, allows locking of rowset subsets of a table.
- ROW EXCLUSIVE - automatically obtained when inserting, updating or deleting, prohibits SHARE mode locking.
- SHARE UPDATE - as ROW SHARE.
- SHARE - allows conncurrent querying disallowing updates.
- SHARE ROW EXCLUSIVE - view table whilst disallowing other users the ability to lock that table.
- EXCLUSIVE - allows queries but disallows all other activity to other users.
- NOWAIT - returns a message and does not wait if table or view id already locked by another user.
Index Organised Tables
Index organised tables have rows grouped in relation to a primary index. Clustering uses a BTree which stores the primary index and non-index columns. Primary index columns are stored at the beginning of the segment in the order the the columns within the primary index.
Advantages of Index Organised Tables
- Fast query access for both range searches and exact matches.
- Row changes (insert, update and delete) update index structure only since the index and table data areas are not separate storage areas (objects). Thus row changes should also be faster.
- Therefore DO NOT use index organised tables for tables which are not accessed using the primary ALONE or a subset, properly ordered prefix, of the primary index of a table.
- Storage requirements are reduced since index key columns are not duplicated for each row. This is important to note.
The OVERFLOW and INCLUDING Clauses
The optional OVERFLOW clause allows for the the placing of index columns exceeding a specified threshold into separate overflow
segments thus preserving dense clustering of BTree index columns. The INCLUDING clause forces the storage of non-index columns into
the overflow data segment. PCTTHRESHOLD reserves space in each index block for the index. Thus space is reserved in the index block for the
indexes. Always choose a threshold value which accomodates index columns into the index segment and non-index columns into the overflow
segment. Note that index organised tables are particulary efficient for storage management of binary objects, however, note that indexes
cannot be anything but simple data types.
The COMPRESS Clause
The COMPRESS clause eliminates repeated occurences of index column prefix values. Prefix entries are shared amongst all suffix entries in an index block.
CREATE TABLE accounts
(
account_type CHAR(1) NOT NULL,
account_sub_type CHAR(1) NOT NULL,
chart_of_account NUMBER(4) NOT NULL,
name VARCHAR2(32),
debit_amount NUMBER(13,2),
credit_amount NUMBER(13,2
CONSTRAINT pk_accounts_index PRIMARY KEY (account_type, account_sub_type, chart_of_account)
)
ORGANIZATION INDEX COMPRESS TABLESPACE indx PCTTHRESHOLD 20 OVERFLOW TABLESPACE indxovfl;
Specifying Prefix Length
Prefix length is the number of index columns, ie. the number of columns stored within the index.
CREATE TABLE test (a INTEGER, b INTEGER, c INTEGER, d INTEGER, PRIMARY KEY (a, b, c)) ORGANIZATION COMPRESS 2;
[1,2,3],
[1,2,4],
[1,2,7],
[1,3,5],
[1,3,4],
[1,4,4]
... becomes ...
[1,2,
[3,4,7]
],
[1,3,
[5,4]
],
[1,4,
[4]
]
... and ...
CREATE TABLE test (a INTEGER, b INTEGER, c INTEGER, d INTEGER, PRIMARY KEY (a, b, c)) ORGANIZATION COMPRESS 1;
[1,2,3],
[1,2,4],
[1,2,7],
[1,3,5],
[1,3,4],
[1,4,4]
... becomes ...
[1,
[2,3],
[2,4],
[2,7],
[3,5],
[3,4],
[4,4]
]
Index Organised Table Fragmentation
Changes to data can cause fragmentation. The ALTER TABLE MOVE statement can be used to rebuild index organised tables and thus reduce
fragmentation. The example below will rebuild both the index and the overflow segments.
ALTER TABLE accounts MOVE TABLESPACE indx OVERFLOW TABLESPACE indxovfl