Archive for the ‘Table SQL’ Category

Constraints

Several types of Oracle constraints can be applied to Oracle tables to enforce data integrity, including:

  • Oracle "Check" Constraint: This constraint validates incoming columns at row insert time. For example, rather than having an application verify that all occurrences of region are North, South, East, or West, an Oracle check constraint can be added to the table definition to ensure the validity of the region column.
  • Not Null Constraint: This Oracle constraint is used to specify that a column may never contain a NULL value. This is enforced at SQL insert and update time.
  • Primary Key Constraint: This Oracle constraint is used to identify the primary key for a table. This operation requires that the primary columns are unique, and this Oracle constraint will create a unique index on the target primary key.
  • References Constraint: This is the foreign key constraint as implemented by Oracle. A references constraint is only applied at SQL insert and delete times.  At SQL delete time, the references Oracle constraint can be used to ensure that an employee is not deleted, if rows still exist in the DEPENDENT table.
  • Unique Constraint: This Oracle constraint is used to ensure that all column values within a table never contain a duplicate entry.

Important Constraint Views

dba_cons_columns
dba_constraints

 

CREATE TABLE Dept_tab (
    Deptno  NUMBER(3) CONSTRAINT Dept_pkey PRIMARY KEY, 
    Dname   VARCHAR2(15), 
    Loc     VARCHAR2(15))
CREATE TABLE Emp_tab ( 
    Empno    NUMBER(5) CONSTRAINT Emp_pkey PRIMARY KEY, 
    Ename    VARCHAR2(15) NOT NULL, 
    Job      VARCHAR2(10), 
    Mgr      NUMBER(5) CONSTRAINT Mgr_fkey REFERENCES Emp_tab,
    Hiredate DATE, 
    Sal      NUMBER(7,2), 
    Comm     NUMBER(5,2), 
    Deptno   NUMBER(3) NOT NULL 
             CONSTRAINT dept_fkey REFERENCES Dept_tab ON DELETE CASCADE);

alter table  table_name add constraint constraint_name;

Primary and Foreign Key Constraints
ALTER TABLE Dept_tab 
    ADD CONSTRAINT PK_Dept PRIMARY KEY (deptno); 
ALTER TABLE Emp_tab 
    ADD CONSTRAINT FKEY_Dept FOREIGN KEY (Deptno) REFERENCES Dept_tab;
Unique Check and Not Null Constraints
ALTER TABLE Dept_tab CONSTRAINT UQ_Dname UNIQUE (Dname, Loc);
ALTER TABLE Dept_tab CONSTRAINT Loc_check1
CHECK (loc IN ('NEW YORK', 'BOSTON', 'CHICAGO'));
ALTER TABLE Emp_tab MODIFY (Ename VARCHAR2(15) NOT NULL);
Enabling Disabling Dropping Constraints

ALTER TABLE Dept  ENABLE CONSTRAINT UQ_Dname;

ALTER TABLE Dept_tab  DISABLE CONSTRAINT UQ_Dname;

ALTER TABLE Dept_tab  DROP CONSTRAINT  UQ_Dname;

 

Constraint State

DEFERRABLE Clause

The DEFERRABLE and NOT DEFERRABLE parameters indicate whether or not, in subsequent transactions, constraint checking can be deferred until the end of the transaction using the SET CONSTRAINT(S) statement. If you omit this clause, then the default is NOT DEFERRABLE.

  • Specify NOT DEFERRABLE to indicate that in subsequent transactions you cannot use the SET CONSTRAINT[S] clause to defer checking of this constraint until the transaction is committed. The checking of a NOT DEFERRABLE constraint can never be deferred to the end of the transaction.

    If you declare a new constraint NOT DEFERRABLE, then it must be valid at the time the CREATE TABLE or ALTER TABLE statement is committed or the statement will fail.

  • Specify DEFERRABLE to indicate that in subsequent transactions you can use the SET CONSTRAINT[S] clause to defer checking of this constraint until after the transaction is committed. This setting in effect lets you disable the constraint temporarily while making changes to the database that might violate the constraint until all the changes are complete.

The following statement creates table games with a NOT DEFERRABLE INITIALLY IMMEDIATE constraint check (by default) on the scores column:

CREATE TABLE games (scores NUMBER CHECK (scores >= 0));

CREATE TABLE games (scores NUMBER, CONSTRAINT unq_num UNIQUE (scores) INITIALLY DEFERRED DEFERRABLE);

VALIDATE | NOVALIDATE

The behavior of VALIDATE and NOVALIDATE always depends on whether the constraint is enabled or disabled, either explicitly or by default.

ALTER TABLE sales ADD CONSTRAINT sales_time_fk
FOREIGN KEY (time_id) REFERENCES times (time_id)
ENABLE VALIDATE;

 

RELY Constraints

The ETL process commonly verifies that certain constraints are true. For example, it can validate all of the foreign keys in the data coming into the fact table. This means that you can trust it to provide clean data, instead of implementing constraints in the data warehouse. You create a RELY constraint as follows:

ALTER TABLE sales ADD CONSTRAINT sales_time_fk
FOREIGN KEY (time_id) REFERENCES times (time_id) 
RELY DISABLE NOVALIDATE;

This statement assumes that the primary key is in the RELY state. RELY constraints, even though they are not used for data validation, can:

  • Enable more sophisticated query rewrites for materialized views. See Chapter 18, " Query Rewrite" for further details.

  • Enable other data warehousing tools to retrieve information regarding constraints directly from the Oracle data dictionary.

Creating a RELY constraint is inexpensive and does not impose any overhead during DML or load. Because the constraint is not being validated, no data processing is necessary to create it.

DYNAMIC SQL FOR CONSTRAINTS

To disable constraints in a schema for all tables

SELECT ‘alter table ‘||owner||’.’||table_name||’ disable constraint ‘||constraint_name||’ ;’

FROM dba_constraints where owner = ‘HR’

To enable constraints, make sure that referential integrity constraints are enabled after primary key constraints.

SELECT ‘alter table ‘||owner||’.’||table_name||’ enable constraint ‘||constraint_name||’ ;’

FROM dba_constraints  where owner = ‘HR’

order by constraint_type

QUERIES FOR CHECKING CONSTRAINTS

  SELECT Constraint_name, Search_condition  
    FROM User_constraints  
    WHERE (Table_name = 'DEPT_TAB' OR Table_name = 'EMP_TAB') AND  
        Constraint_type = 'C';

SELECT CONSTRAINT_NAME, CONSTRAINT_TYPE, STATUS, LAST_CHANGE

FROM DBA_CONSTRAINTS

WHERE TABLE_NAME = ‘EMPLOYEES’

SELECT Owner,Constraint_name, Table_name, Column_name 
FROM dba_cons_columns

where  table_name = ‘EMPLOYEES’

and owner = ‘HR_DUP’

Advertisements

Managing Tables

Creating a Table

The CREATE TABLE command is used to create relational tables or object tables.

Relational table: This is the basic structure to hold user data.

Object table: Is a table that uses an object type for a column definition. An object table is a table that is explicitly defined to hold the object instance of a particular type.

 

The example below creates a DEPARTMENTS table in a data dictionary managed tablespace.

SQL> CREATE TABLE hr.departments( department_id NUMBER(4),

department_name VARCHAR2(30), manager_id NUMBER(6), location_id NUMBER(4))

STORAGE(INITIAL 200K NEXT 200K PCTINCREASE 0 MINEXTENTS 1 MAXEXTENTS 5)

TABLESPACE data;

STORAGE clause:

The STORAGE clause specifies storage characteristics for the table. The storage allocated for the first extent is 200 KB. When a second extent is required it will be created at 200 KB also defined by the NEXT value. When a third extent is required, it will be created at 200 KB because the PCTINCREASE has been set to zero. The maximum amount of extents that can be used is set at five, with the minimum set to one.

•MINEXTENTS: This is the minimum number of extents that is to be allocated.

•MAXEXTENTS: This is the maximum number of extents to be allocated. If MINEXTENTS is specified with a value greater than one and the tablespace contains more than one datafile, the extents will be spread across the different datafiles.

•PCTINCREASE: This is the percent of increase in extent size after NEXT extent and thereafter.

 

PCTFREE must be a value from zero to ninety-nine. A value of zero means that the entire block can be filled by inserts of new rows. The default value is 10. This value reserves 10% of each block for updates to existing rows and allows inserts of new rows to fill a maximum of 90% of each block.

•PCTUSED: Specifies the minimum percentage of used space that is maintained for each data block of the table. A block becomes a candidate for row insertion when its used space falls below PCTUSED. PCTUSED is specified as integer from zero to ninety-nine and defaults to 40.

The combination of PCTFREE and PCTUSED determines whether new rows will be inserted into existing data blocks or into new bocks. The sum of these two must be equal to or less than 100. These parameters are used to utilize space within a table more efficiently.

Note: PCTUSED, FREELISTS, and FREELIST GROUPS are deprecated with the Oracle9i feature Automatic Segment-Space Management. Refer to the “Storage Structures and Relationship” lesson for details regarding this feature.

•INITRANS: Specifies the initial number of transaction entries allocated within each data block allocated to the table. This value can range from 1-255 and default to one INITRANS: Ensures that a minimum number of concurrent transactions can update the block. In general, this value should not be changed from its default.

•MAXTRANS: Specifies the maximum number of concurrent transaction that can update a data block allocated to the table. This limit does not apply to queries. The value can range from 1-255 and the default is a function of the data block size.

 

Creating Temporary Tables

Temporary tables can be created to hold session-private data that exists only for the duration of a transaction or session.

The CREATE GLOBAL TEMPORARY TABLE command creates a temporary table that can be transaction-specific or session-specific. For transaction-specific temporary tables, data exists for the duration of the transaction, while for session-specific temporary tables, data exists for the duration of the session. Data in a session is private to the session. Each session can only see and modify its own data. DML locks are not acquired on the data of the temporary tables. The clauses that control the duration of the rows are:

  • ON COMMIT DELETE ROWS: To specify that rows are only visible within the transaction
  • ON COMMIT PRESERVE ROWS: To specify that rows are visible for the entire session

You can create indexes, views, and triggers on temporary tables and you can also use the Export and Import utilities to export and import the definition of a temporary table. However, no data is exported, even if you use the ROWS option. The definition of a temporary table is visible to all sessions.

Setting PCTFREE

A higher PCTFREE affords more room for updates within a database block. Set a higher value if the table contains:

  • Columns that are initially NULL and later updated with a value
  • Columns that are likely to increase in size as a result of an update

A higher PCTFREE will result in lower block density—each block can accommodate fewer rows. The formula specified above ensures that there is enough free space in the block for row growth.

Setting PCTUSED

Set PCTUSED to ensure that the block is returned to the free list only when there is sufficient space to accommodate an average row. If a block on the free list does not contain sufficient space for inserting a row, the Oracle server looks up the next block on the free list. This linear scan continues until either a block with sufficient space is found or the end of the list is reached. Using the formula given reduces the time taken to scan the free list by increasing the probability of finding a block with the required free space.

Changing Storage and Block Utilization Parameters

Some of the storage parameters and any of the block utilization parameters can be modified by using the ALTER TABLE command.

Syntax:

ALTER TABLE hr.employees

PCTFREE 20

PCTUSED 60

STORAGE NEXT (500k MINEXTENTS 2 MAXEXTENTS 100);

ALLOCATING EXTENTS MANUALLY

Extents may need to be allocated manually:

  • To control the distribution of extents of a table across files
  • Before loading data in bulk to avoid dynamic extension of tables

ALTER TABLE hr.employess

ALLOCATE EXTENT (SIZE 500K  DATAFILE ‘C:\ORACLE\DATA01.DBF’);

Moving Table To Different Tablespace

A nonpartitioned table can be moved without having to run the Export or Import utility. In addition, it allows the storage parameters to be changed. This is useful when:

  • Moving a table from one tablespace to another
  • Reorganizing the table to eliminate row migration

ALTER TABLE hr.employees move tablespace data1;

 

Adding a Table Column and Check Constraint: Example

The following statement adds a column named duty_pct of datatype NUMBER and a column named visa_needed of datatype VARCHAR2 with a size of 3 and a CHECK integrity constraint:

 ALTER TABLE countries 
   ADD (duty_pct     NUMBER(2,2)  CHECK (duty_pct < 10.5),
        visa_needed  VARCHAR2(3)); 

 

Renaming a Column: Example

ALTER TABLE customers

   RENAME COLUMN credit_limit TO credit_amount;

TRUNCATE TABLE

TRUNCATE TABLE hr.employees;

  • The effects of using this command are as follows:
  • All rows in the table are deleted.
  • No undo data is generated and the command commits implicitly because TRUNCATE TABLE is a DDL command.
  • Corresponding indexes are also truncated.
  • A table that is being referenced by a foreign key cannot be truncated.
  • The delete triggers do not fire when this command is used.

DROP TABLE

DROP TABLE hr.employees CASCADE CONSTRAINT;

When a table is dropped, the extents used by the table are released. If they are contiguous, they may be coalesced either automatically or manually at a later stage. The CASCADE CONSTRAINTS option is necessary if the table is the parent table in a foreign key relationship.

 

Dropping a Column

Dropping a column can take a significant amount of time because all the data for the column is deleted from the table.

Dropping a column can be time consuming and requires a large amount of undo space. While dropping columns from large tables, checkpoints can be specified to minimize the use of undo space. In the example in the slide, a checkpoint occurs every 1,000 rows. The table is marked INVALID until the operation completes.

ALTER TABLE hr.employees DROP COLUMN comments CASCADE constraints CHECKPOINT 1000;

If the instance fails during the operation, the table remains INVALID on start up, and the operation will have to be completed.

SQL> ALTER TABLE hr.employees DROP COLUMNS CONTINUE;

Using the UNUSED Option

Instead of removing a column from a table, the column can be marked as unused and then removed later. This has the advantage of being relatively quick, as it does not reclaim the disk space because the data is not removed. Columns that are marked as unused can be removed at a later time from the table when there is less activity on the system.

Unused columns act as if they are not part of the table. Queries cannot see data from unused columns. In addition, the names and data types of those columns are not displayed when a DESCRIBE command is executed. A user can add a new column with the same name as an unused column. Marking column COMMENTS as unused:

ALTER TABLE hr.employees SET UNUSED COLUMN comments CASCADE CONSTRAINTS;

Dropping UNUSED column

ALTER TABLE hr.employees DROP UNUSED COLUMNS CHECKPOINT 1000;

The following query shows that the table EMPLOYEES owned by HR has one unused column:

SQL > SELECT * FROM dba_unused_col_tabs;

OWNER TABLE_NAME COUNT

—– ————– ——

HR EMPLOYEES 1

To identify tables that have partially completed DROP COLUMN operations the DBA_PARTIAL_DROP_TABS view can be queried.

SQL > SELECT * FROM dba_partial_drop_tabs;

OWNER TABLE_NAME COUNT

—– ————– ——

no rows selected

Obtaining Table Information

Information about tables can be obtained from the data dictionary.

  • DBA_OBJECTS
  • DBA_TABLES

To obtain the data object number and the location of the table header for all tables owned by HR, use the following query:

SQL > SELECT table_name FROM dba_tables WHERE owner = ‘HR’;

 

 
 
For details see Alter table link.