INFORMIX
Informix Guide to SQL: Syntax
Chapter 1: SQL Statements
Home Contents Index Master Index New Book

SQL Statements

CREATE TABLE

Use the CREATE TABLE statement to create a new table in the current database, place data-integrity constraints on its columns or on a combination of its columns, designate the size of its initial and subsequent extents, and specify how to lock each table. You can also use this statement to fragment tables into separate dbspaces.

You can use CREATE TABLE to create untyped tables (traditional relational- database tables), typed tables (object-relational tables), typed tables with inheritance, or temporary tables.

Syntax

Element Purpose Restrictions Syntax

table name

The name assigned to the table. Every table must have a name.

Name must be unique within a database. It must not be used for any other tables or for any views or synonyms within the current database.

Identifier, p. 1-966

Some of the syntax diagrams in this chapter include branches that are valid only for certain types of tables. The diagrams use the following icons to indicate which types of tables can use the limited branches:

Actions in this branch can appear in (permanent) untyped tables.

Actions in this branch can appear in typed tables.

Actions in this branch can appear in temporary (untyped) tables.

Syntax Clauses for Typed and Untyped Tables

The following syntax diagrams show the syntax for both typed and untyped tables. Typed tables and inheritance are new features introduced by INFORMIX-Universal Server. Earlier releases of Informix products support only untyped tables, both permanent and temporary.

Element Purpose Restrictions Syntax

row type name

The name of row type used as this table's type

This type must already exist and must be a named row type.

Data type, p.1-859

Identifier, p. 1-966

Informix Guide to SQL: Syntax: Chapter 3, "Environment Variables"

supertable name

The name of the parent table of which this table is a child.

This parent table must already exist as a typed table.

A type hierarchy must already exist in which the named row type of this table is a subtype of the named row type of the supertable.

Usage

When you create a table, the table and columns within that table must have unique names and every table column must have a data type associated with it. However, although temporary table names must be different from existing table, view, or synonym names in the current database, they need not be different from temporary table names used by other users.

ANSI
In an ANSI-compliant database, the combination owner.tablename must be unique within the database.

DB
In DB-Access, using the CREATE TABLE statement outside the CREATE SCHEMA statement generates warnings if you set DBANSIWARN.

ESQL
The CREATE TABLE statement generates warnings if you use the -ansi flag or set DBANSIWARN environment variable.

For information about DBANSIWARN environment variable, refer to the Informix Guide to SQL: Syntax.

Typed and Untyped Tables

Untyped tables are the only kinds of tables that are available in Informix products prior to INFORMIX-Universal Server. Typed tables use named row types. For a detailed discussion of row types and typed and untyped tables, refer to Chapter 10 of the Informix Guide to SQL: Tutorial.

Important: Informix recommends that you use the BLOB or CLOB data types instead of the TEXT or BYTE data types when you create a typed table that contains columns for large objects. For backward compatibility, you can create a named row type that contains TEXT or BYTE fields and use that type to recreate an existing (untyped) table as a typed table. However, although you can use a row type that contains BYTE or TEXT fields to create a typed table, you cannot use such a row type as a column. You can use a row type that contains CLOB or BLOB fields in both typed tables and columns.

Typed Tables
A typed table is a table that has a named row type assigned to it. The columns of a typed table correspond to the fields of the named row type.

For example, suppose you create a named row type, student_t as follows:

If a table is assigned the type student_t, the table is a typed table whose columns are of the same name and data type (and in the same order) as the fields of the type student_t.

The following CREATE TABLE statement creates a typed table named students whose type is student_t:

The students table has the following columns:

When you create a typed table, the columns of the table are not named in the CREATE TABLE statement. Instead, the columns are specified when you create the row type. You cannot add additional columns to a typed table.

Important: Typed tables do not take the default values or null/not null specification of the row type whose type they adopt.
For more information about row types, refer to the CREATE ROW TYPE statement on page 1-197.

Typed Tables with Inheritance
A typed table can inherit properties from a typed supertable and add new columns and properties. The table that inherits is a subtable. The subtable must use a row type that is derived from the row type of the supertable.

Continuing the example shown in "Typed Tables", the following statements created a typed table, grad_students, that inherits all of the columns of the students table and in addition has columns for adviser and field_of_study:

When you create a typed table as a subtable, the subtable inherits the following properties:

  • All columns in the immediate supertable
  • All constraint definitions defined on its supertable
  • Fragmentation. If a subtable does not define fragments, and if its supertable has fragments defined, then the subtable inherits the fragments of the supertable.
  • All indexes defined by its supertable
  • Referential integrity
  • The access method
  • The WITH options
  • The storage option
  • All triggers defined on the supertable
Tip: Any heritable attributes that are added to a supertable after subtables have been created will automatically be inherited by existing subtables. It is not necessary to add all heritable attributes to a supertable before creating its subtables.
Inheritance occurs in one direction only-from supertable to subtable. Properties of subtables are not inherited by supertables.

Constraints, indices, and triggers are recorded in the system catalog for the supertable, but not for subtables that inherit them. Fragmentation information is recorded for both supertables and subtables.

No two tables in a table hierarchy can have the same type. For example, the final line of the following code sample is illegal because the tables tab2 and tab3 cannot have the same row type (rowtype2):

For more information about inheritance, refer to Chapter 10 of the Informix Guide to SQL: Tutorial.

Untyped Tables
Tables that have not been assigned a named row type are untyped tables. Untyped tables, both permanent and temporary, are traditional relational-database tables. For simplicity, this discussion refers to permanent untyped tables as untyped tables and temporary untyped tables as temporary tables.

The following CREATE TABLE statement creates an untyped table:

Temporary Tables
Temporary tables are always untyped tables. The following CREATE TABLE statement creates a temporary table:

After a temporary table is created, you can build indexes on the table. However, you are the only user who can see the temporary table.

Temporary tables that you create with the CREATE TEMP TABLE statement are explicit temporary tables. You can also create explicit temporary tables with the SELECT ... INTO TEMP statement. Temporary tables that the database server creates as a part of processing are called implicit temporary tables. Implicit temporary tables are discussed in the INFORMIX-Universal Server Administrator's Guide.

When an application creates an explicit temporary table, the table exists until one of the following situations occur:

  • The application terminates.
  • The application closes the database where the table was created. In this case, the table is dropped only if the database does transaction logging, and the temporary table was not created with the WITH NO LOG option.
  • The application closes the database where the table was created and opens a database in a different database server.
When any of these events occur, the temporary table is deleted.

DB
You cannot use the INFO statement and the Info Menu Option with temporary tables.

Temporary table names must be different from existing table, view, or synonym names in the current database. However, they need not be different from other temporary table names used by other users.

You can specify where temporary tables are created with the CREATE TEMP TABLE statement, environment variables, and ONCONFIG parameters. If you do not specify a storage location, the temporary tables are created in the same dbspace as the database. The database server stores temporary tables in the following order:

    1. The IN dbspace clause

    You can specify the dbspace where you want the temporary table stored with the IN dbspace clause of the CREATE TABLE statement.

    2. The dbspaces you specify when you fragment temporary tables

    Use the FRAGMENT BY clause of the CREATE TABLE statement to fragment regular and temporary tables.

    3. The DBSPACETEMP environment variable

    The DBSPACETEMP environment variable lists dbspaces where temporary tables can be stored. This list can include standard dbspaces, temporary dbspaces, or both. If the environment variable is set, the database server assigns each temporary table to a dbspace in round-robin sequence.

    4. The ONCONFIG parameter DBSPACETEMP

    You can specify a location for temporary tables with the ONCONFIG parameter DBSPACETEMP.

Tip: Use the PUT clause to specify a separate storage area for smart large objects.
For additional information about the DBSPACETEMP environment variable, see Chapter 3 in the Informix Guide to SQL: Syntax. For additional information about the ONCONFIG parameter DBSPACETEMP, see the INFORMIX-Universal Server Administrator's Guide.

Differences Among Tables
Tables created with the CREATE TABLE statement are similar in most ways, but have a few notable differences. The following table summarizes the major differences among tables.

Table Description Characteristics

Untyped table

A permanent database table

See "Untyped Tables".

Allows column-level constraints as well as table-level constraints.

Temporary Table

A table that exists only until the application either terminates or, under certain conditions, closes the database.

See "Temporary Tables".

Allows column-level constraints as well as table-level constraints.

Can use the DBSPACETEMP environment variable or the DBSPACETEMP configuration parameter to specify storage location.

Typed table

A permanent database table

See "Typed Tables".

Allows only table-level constraints.

Does not allow SERIAL and SERIAL8 data types. Does not allow the WITH ROWIDS clause.

Table with Inheritance

A permanent database table that is a subtable in an inheritance hierarchy.

See "Typed Tables with Inheritance".

Both subtable and supertable must be typed, and their types must be named row types. The type of the subtable must be a subtype directly under the type of the supertable.

Allows only table-level constraints.

Does not allow SERIAL and SERIAL8 data types. Does not allow the WITH ROWIDS clause.

Privileges on Tables

The privileges on a table describe both who can access the information in the table and who can create new tables. For information about the privileges required for creating a table, refer to the GRANT statement on page 1-461. For additional information about privileges, refer to Chapter 11, "Granting and Limiting Access to Your Database," in the Informix Guide to SQL: Tutorial.

ANSI
In an ANSI-compliant database, no default table-level privileges exist. You must grant these privileges explicitly.

When set to yes, the environment variable NODEFDAC prevents default privileges on a new table in a database that is not ANSI compliant from being granted to PUBLIC. For information about preventing privileges from being granted to PUBLIC, see the NODEFDAC environment variable in the Informix Guide to SQL: Syntax.

System Catalog Information

When you create a table, the database server adds basic information about the table to the systables system catalog table and column information to syscolumns table. The sysblobs table contains information about the location of dbspaces and simple large objects. The syschunks table in the sysmaster database contains information about the location of smart large objects.

The systabauth, syscolauth, sysfragauth, sysprocauth, sysusers, and sysxtdtypeauth tables contain information about the privileges required for various CREATE TABLE options. The systables, sysxtdtypes, and sysinherits system catalog tables provide information about table types.

For information about the system catalog tables, refer to the Informix Guide to SQL: Syntax. For information about sysmaster database, refer to the INFORMIX-Universal Server Administrator's Guide.

Column Definition Clause

Element Purpose Restrictions Syntax

column name

The name of a column in the permanent table

Name must be unique within a table, but you can use the same names in different tables in the same database.

Identifier, p. 1-966

Use the column definition portion of the CREATE TABLE statement to list the name, data type, default values, and constraints of a single column of an untyped table (permanent or temporary) as well as to specify constraints on the column.

The Untyped Table clause on page 1-213 refers to the Column Definition Clause.

DEFAULT Clause

Element Purpose Restrictions Syntax

literal

A literal term that defines alphabetic or numeric constant characters to be used as the default value for the column

Term must be appropriate type for the column. See "Literal Terms as Default Values".

Expression, p. 1-880

The default value is inserted in the column when an explicit value is not specified. If a default is not specified, and the column allows nulls, the default is NULL.

The column definition clause on page 1-222 refers to DEFAULT clause.

Important: If you use a named row type as one of the columns in an untyped table, the table does not adopt any constraints of the named row.

Literal Terms as Default Values
You can designate literal terms as default values. A literal term is a string of character or numeric constant characters that you define. To use a literal term as a default value, you must adhere to the following rules.

Use a Literal With Columns of Data Type

INTEGER

INTEGER, SMALLINT, DECIMAL, MONEY, FLOAT,
SMALLFLOAT, INT8

DECIMAL

DECIMAL, MONEY, FLOAT, SMALLFLOAT

CHARACTER

CHAR, VARCHAR, NCHAR, NVARCHAR,
CHARACTER VARYING, DATE

INTERVAL

INTERVAL

DATETIME

DATETIME

CHARACTER

Opaque data types

Characters must be enclosed in quotation marks. Date literals must be of the format specified with the DBDATE environment variable. If DBDATE is not set, the format mm/dd/yyyy is assumed.

Opaque data types support only string literals for default values. The default value must be specified at the column level and not at the table level.

For information on using a literal INTERVAL, refer to the Literal INTERVAL segment on page 1-998. For more information on using a literal DATETIME, refer to the Literal DATETIME segment on page 1-995.

NULL as the Default Value
If you do not indicate a default value for a column, the default is NULL unless you place a not null constraint on the column. In this case, no default value exists for the column.

If you designate NULL as the default value for a column, you cannot specify a not null constraint as part of the column definition.

If the column is TEXT or BYTE data type, you can designate only NULL as the default value.

Data Type Requirements for Certain Columns
The following table indicates the data type requirements for columns that specify the CURRENT, DBSERVERNAME, SITENAME, TODAY, or USER functions as the default value.

Function Name Data Type Requirement

CURRENT

DATETIME column with matching qualifier

DBSERVERNAME

CHAR, VARCHAR, NCHAR, NVARCHAR, or CHARACTER VARYING column at least 18 characters long

SITENAME

CHAR, VARCHAR, NCHAR, NVARCHAR, or CHARACTER VARYING column at least 18 characters long

TODAY

DATE column

USER

CHAR, VARCHAR, NCHAR, NVARCHAR, or CHARACTER VARYING column at least 8 characters long

Limitations on Default Values
You cannot designate default values for serial columns.

You cannot designate a server-defined function (that is, CURRENT, USER, TODAY, SITENAME or DBSERVERNAME) as the default value for opaque or distinct data types.

You cannot designate NULL as a default value for a column that is part of a primary key.

Examples of Default Values in Column Definitions
The following example creates a table called accounts. In accounts, the acc_num, acc_type, and acc_descr columns have literal default values. The acc_id column defaults to the user's login name.

The following example creates the newitems table. In newitems, the column manucode does not have a default value nor does it allow nulls.

If you place a not null constraint on a column (and no default value is specified), you must enter a value into this column when you insert a row or update that column in a row. If you do not enter a value, the database server returns an error.

Constraints

Putting a constraint on a column is similar to putting an index on a column (using the CREATE INDEX statement). However, if you use constraints instead of indexes, you can also implement data-integrity constraints and turn effective checking off and on. For information on data-integrity constraints, refer to the Informix Guide to SQL: Tutorial. For information on effective checking, see the SET statement on page 1-647.

Important: In a database without logging, detached checking is the only kind of constraint checking available. Detached checking means that constraint checking is performed on a row-by-row basis.

Limits on Constraint Definitions
You can include 16 columns in a list of columns for a table-level constraint. The total length of all columns in the constraint list cannot exceed 390 bytes.

You cannot place a constraint on a violations or diagnostics table. For further information on violations and diagnostics tables, see the START VIOLATIONS TABLE statement on page 1-748.

Restrictions for Unique Constraints
Use the UNIQUE keyword to require that a single column or set of columns accepts only unique data. You cannot insert duplicate values in a column that has a unique constraint.

When you define a unique constraint (UNIQUE or DISTINCT keywords), a column cannot appear in the constraint list more than once. You cannot place a unique constraint on a column on which you have already placed a primary-key constraint. You cannot place a unique constraint on a BYTE or TEXT column.

Opaque types support a unique constraint only where there is a secondary access method that supports the uniqueness for that type. The built-in (default) secondary access method is a generic B-tree, which supports the equal() function. Therefore, if the definition of the opaque type includes the equal() function, a column of that opaque type can have a unique constraint.

Restrictions for Primary-Key Constraints
You can define a primary-key constraint (PRIMARY KEY keywords) on only one column or one set of columns in a table.You cannot define a column or set of columns as a primary key if you have already defined another column or set of columns as the primary key.

You cannot define a primary-key constraint on a BYTE or TEXT column.

Opaque types support a primary key constraint only where there is a secondary access method that supports the uniqueness for that type. The built-in secondary access method is a generic B-tree, which supports the equal() function. Therefore, if the definition of the opaque type includes the equal() function, a column of that opaque type can have a primary key constraint

Restrictions for Referential Constraints
When you specify a referential constraint, the data type of the referencing column (the column you specify after the FOREIGN KEY keywords) must match the data type of the referenced column (the column you specify in the REFERENCES clause). The only exception is that the referencing column must be INTEGER if the referenced column is SERIAL, or INT8 if the column is SERIAL8.

You must have the REFERENCES privilege to create a referential constraint.

Adding or Dropping Constraints
After you have used the CREATE TABLE statement to place constraints on a column or set of columns in an untyped or temporary table, you can use the ALTER TABLE statement to modify the constraints. You cannot use ALTER TABLE with a typed table.

Enforcing Primary-Key, Unique, and Referential Constraints
When a primary-key, unique, and referential constraint is placed on a column, the database server performs the following functions:

  • Creates a unique, ascending index for a unique or primary-key constraint
  • Creates a nonunique, ascending index for the columns specified in the referential constraint
However, if a constraint already was created on the same column or set of columns, another index is not built for the constraint. Instead, the existing index is shared by the constraints. If the existing index is non-unique, it is upgraded to a unique index if a unique or primary-key constraint is placed on that column.

Because these constraints are enforced through indexes, you cannot create an index (using the CREATE INDEX statement) for a column that is of the same type as the constraint placed on that column. For example, if a unique constraint exists on a column, you can create neither an ascending unique index for that column nor a duplicate ascending index.

Constraint Names
Whenever you place a data restriction on a column or specify a table-level constraint, the database server creates a constraint. If you wish, you can specify a name for the constraint. The name of the constraint must be unique within the database.

The database server adds a row to the sysconstraints system catalog table for each constraint. If you do not specify a constraint name, the database server generates a constraint name using the following template:

In this template, constraint_type is the letter u for unique or primary-key constraints, r for referential constraints, c for check constraints, and n for not null constraints. For example, the constraint name for a unique constraint might look like this: u111_14. If the name conflicts with an existing identifier, the database server returns an error, and you must then supply a constraint name.

ANSI
When you create a constraint of any type, the owner.constraint_name (the combination of the owner name and constraint name) must be unique within the database.

In addition, the database server adds a row to the sysindices system catalog table for each new primary-key, unique, or referential constraint that does not share an index with an existing constraint. The index name in sysindices is created with the following format:

In this format, tabid and constraintid are values from the tabid and constrid columns of the systables and sysconstraints system catalog tables, respectively. For example, the index name might be something like this: " 121_13" (quotes used to show the space).

Using Simple Large Object Types in Constraints
You cannot place a unique, primary-key, or referential constraint on BYTE or TEXT columns. However, you can check for null or non-null values if you place a check constraint on a BYTE or TEXT column.

Restrictions on Temporary Table Constraints
The only difference between columns in permanent tables and columns in temporary tables is in the constraint options, as follows:

  • You cannot place referential constraints on columns in a temporary table. Temporary columns cannot be referenced or referencing columns.
  • You cannot assign a name to a constraint on a temporary-table column.
  • You cannot set the constraint mode on a temporary-table column. (See "Constraint Mode Definition" for information on this option.)

Column-Level Constraint Definition

In untyped and temporary tables, you can define constraints at either the column level or table level. At the column level, you can indicate that the column has a specific default value or that data entered into the column must be checked to meet a specific data requirement. Constraints at the column level cannot refer to multiple columns. In other words, the constraint created at the column level can apply only to a single column.

The following example creates a simple table with two constraints, a primary-key constraint named num on the acc_num column and a unique constraint named code on the acc_code column:

The column definition clause on page 1-222 refers to the column-level constraint definition.

Table-Level Constraint Definition

You can define table-level constraints for both typed and untyped tables. When you define a constraint at the table level, the constraint can refer to a single column or to multiple columns. Constraints that refer to a single column are treated the same way whether they are defined at the column level or the table level.

Element Purpose Restrictions Syntax

column name

The name of the column or columns on which the constraint is placed

You must observe general restrictions that apply regardless of the type of constraint you are defining. You must also observe specific restrictions that depend on the type of constraint you are defining. See "Constraints".

Identifier, p. 1-966

Using the UNIQUE and DISTINCT Keywords

Use the UNIQUE keyword to require that a single column or set of columns accepts only unique data. You cannot insert duplicate values in a column that has a unique constraint.

When you define a unique constraint (UNIQUE or DISTINCT keywords), a column cannot appear in the constraint list more than once. You cannot place a unique constraint on a column on which you have already placed a primary-key constraint. You cannot place a unique constraint on a BYTE or TEXT column.

Each column named in a unique constraint must be a column in the table and cannot appear in the constraint list more than once.

The following example creates a simple table that has a unique constraint on one of its columns:

The following example creates a simple table, but includes the constraint as a table-level constraint instead of a column-level constraint:

Using the PRIMARY KEY Keywords

A primary key is a column or set of columns that contains a non-null unique value for each row in a table. A table can have only one primary key, and a column that is defined as a primary key cannot also be defined as unique.

In the previous two examples, a unique constraint was placed on the column acc_name. The following example creates this column as the primary key for the accounts table:

Using the FOREIGN KEY Keywords

A foreign key joins and establishes dependencies between tables. A foreign key references a unique or primary key in a table. For every entry in the foreign-key columns, a matching entry must exist in the unique or primary-key columns if all foreign-key columns contain non-null values. You cannot make BYTE or TEXT columns foreign keys.

When you use FOREIGN KEY keywords, you must use the REFERENCES clause, page 1-235, to complete the foreign key dependencies.

CHECK Clause

Check constraints allow you to designate conditions that must be met before data can be assigned to a column during an INSERT or UPDATE statement. If a row evaluates to false for any check constraint defined on a table during an insert or update, the database server returns an error.

Check constraints are defined using search conditions. The search condition cannot contain subqueries; aggregates; host variables; rowids; the CURRENT, USER, SITENAME, DBSERVERNAME, or TODAY functions; or stored procedure calls.

Warning: When you specify a date value in a search condition, make sure to specify 4 digits instead of 2 digits for the year. When you specify a 4-digit year, the DBCENTURY environment variable has no effect on how the database server interprets the search condition. When you specify a 2-digit year, the DBCENTURY environment variable can affect how the database server interprets the search condition, so the check constraint might not work as you intended. See the "Informix Guide to SQL: Syntax" for more information on the DBCENTURY environment variable.
The Column-Level Constraint definition on page 1-230 and the Table-Level Constraint definition on page 1-231 refer to the CHECK clause.

Defining Check Constraints at the Column Level
If you define a check constraint at the column level, the only column that the check constraint can check against is the column itself. In other words, the check constraint cannot depend upon values in other columns of the table. For example, as the following statement shows, the table my_accounts has two columns with check constraints:

Both acct1 and acct2 are columns of MONEY data type whose values must be between 0 and 99999. If, however, you wanted to test that acct1 had a larger balance than acct2, you would not be able to create the check constraint at the column level. To create a constraint that checks values in more than one column, you must define the constraint at the table level.

Defining Check Constraints at the Table Level
When you defined a check constraint at the table level, each column in the search condition must be a column in that table. You cannot create a check constraint for columns across tables. The next example builds the same table and columns as the previous example. However, the check constraint now spans two columns in the table.

In this example, the acct1 column must be greater than the acct2 column, or the insert or update fails.

REFERENCES Clause

Element Purpose Restrictions Syntax

column name

A referenced column or columns in the referenced table

You must observe restrictions on the column type and the number and length of columns. See "Restrictions on the Column Name Variable".

Identifier, p. 1-966

table name

The name of the referenced table

The referenced table must reside in the same database as the referencing table.

Table Name, p. 1-1048

The REFERENCES clause appears in the Column-Level Constraint definition on page 1-230.

Restrictions on the Column Name Variable
You must observe the following restrictions on the column name variable in the REFERENCES clause:

  • The referenced column must be a unique or primary-key column.
    That is, the referenced column must already include a unique or primary-key constraint.

  • The data types of the referencing and referenced columns must be identical. The only exception is that a referencing column must be INTEGER if the referenced column is SERIAL or INT8 if the referenced column is SERIAL8.
  • You cannot place a referential constraint on a BYTE or TEXT column.
  • A column-level REFERENCES clause can include only a single column name.
  • The maximum number of columns in a table-level REFERENCES clause is 16, and the total length of the columns cannot exceed 390 bytes.
Using the REFERENCES Clause
In a referential relationship, the referenced column is a column or set of columns within a table that uniquely identifies each row in the table. The referenced column or set of columns must have a unique or primary-key constraint.

The referencing column is the column or set of columns that refers to the referenced columns. Unlike a referenced column, the referencing column or set of columns can contain null and duplicate values. However, every non-null value in the referencing columns must match a value in the referenced columns. When a referencing column meets this criteria, it is called a foreign key.

The relationship between referenced and referencing columns is called a parent-child relationship, where the parent is the referenced column (primary key) and the child is the referencing column (foreign key). The referential constraint establishes this parent-child relationship.

You can use the REFERENCES clause to establish a referential relationship between two tables or within the same table. The referenced and referencing tables must be in the same database.

For example, you can have an employee table where the emp_no column uniquely identifies every employee through an employee number. The mgr_no column in that table contains the employee number of the manager who manages that employee. In this case, mgr_no is the foreign key (the child) that references emp_no, the primary key (the parent).

Using Column-Level REFERENCES Constraints
You can reference only one column when you use the REFERENCES clause at the column level (that is, when you use the REFERENCES clause with the "Column-Level Constraint Definition").

The following example creates two tables, accounts and sub_accounts. A referential constraint is created between the foreign key, ref_num, in the sub_accounts table and the primary key, acc_num, in the accounts table.

The ref_num is not explicitly called a foreign key in the column- definition syntax. At the column level, the foreign-key designation is applied automatically.

If the referenced table is different from the referencing table, you do not need to specify the referenced column; the default is the primary-key column or columns. If the referenced table is the same as the referencing table, you must specify the referenced column.

In the preceding example, you can simply reference the accounts table without specifying a column. Because acc_num is the primary key of the accounts table, it becomes the referenced column by default.

Using Table-Level REFERENCES Constraints
You can specify multiple columns when you are using the REFERENCES clause at the table level.

A referential constraint must have a one-to-one relationship between referencing and referenced columns. In other words, if the primary key is a set of columns, then the foreign key also must be a set of columns that corresponds to the primary key. The following example creates two tables. The first table has a multiple-column primary key, and the second table has a referential constraint that references this key.

In this example, the foreign key of the sub_accounts table, ref_num and ref_type, references the primary key, acc_num and acc_type, in the accounts table. If, during an insert, you tried to insert a row into the sub_accounts table whose value for ref_num and ref_type did not exactly correspond to the values for acc_num and acc_type in an existing row in the accounts table, the database server would return an error. Likewise, if you attempt to update sub_accounts with values for ref_num and ref_type that do not correspond to an equivalent set of values in acc_num and acc_type (from the accounts table), the database server returns an error.

If you are referencing a primary key in another table, you do not have to state the primary-key columns in that table explicitly. Referenced tables that do not specify the referenced columns default to the primary-key columns. You can rewrite the references section of the previous example as follows:

Because acc_num and acc_type is the primary key of the accounts table, and no other columns are specified, the foreign key, ref_num and ref_type, references those columns.

Locking Implications
When you create a referential constraint, an exclusive lock is placed on the referenced table. The lock is released when the CREATE TABLE statement is done. If you are creating a table in a database with transactions, and you are using transactions, the lock is released at the end of the transaction.

Using ON DELETE CASCADE

Cascading deletes allow you to specify whether you want rows deleted in the child table when rows are deleted in the parent table. Unless you specify cascading deletes, the default prevents you from deleting data in the parent table if child tables are associated with the parent table. With the ON DELETE CASCADE clause, when you delete a row in the parent table, any rows associated with that row (foreign keys) in a child table are also deleted. The principal advantage to the cascading deletes feature is that it allows you to reduce the quantity of SQL statements you need to perform delete actions.

For example, the all_candy table contains the candy_num column as a primary key. The hard_candy table refers to the candy_num column as a foreign key. The following CREATE TABLE statement creates the hard_candy table with the cascading-delete clause on the foreign key:

With cascading deletes specified on the child table, in addition to deleting a candy item from the all_candy table, the delete cascades to the hard_candy table associated with the candy_num foreign key. If you indicate cascading deletes, when you delete a row from a parent table, the database server deletes the associated matching rows from the child table.

You specify cascading deletes with the REFERENCES clause on a column-level or table-level constraint. You need only the References privilege to indicate cascading deletes. You do not need the Delete privilege to perform cascading deletes; however, you do need the Delete privilege on tables referenced in the DELETE statement.

Locking and Logging
During deletes, the database server places locks on all qualifying rows of the referenced and referencing tables. You must turn logging on when you perform the deletes. If logging is turned off in a database, even temporarily, deletes do not cascade. This restriction applies because if logging is turned off, you cannot roll back any actions. For example, if a parent row is deleted, and the system crashes before the child rows are deleted, the database will have dangling child records, which violates referential integrity. However, when logging is turned back on, subsequent deletes cascade.

What Happens to Multiple Children Tables
If you have a parent table with two child constraints, one child with cascading deletes specified and one child without cascading deletes, and you attempt to delete a row from the parent table that applies to both child tables, the delete statement fails, and no rows are deleted from either the parent or child tables.

Restriction on Cascading Deletes
Cascading deletes can be used for most deletes. The only exception is correlated subqueries. In correlated subqueries, the subquery (or inner SELECT) is correlated when the value it produces depends on a value produced by the outer SELECT statement that contains it. If you have implemented cascading deletes, you cannot write deletes that use a child table in the correlated subquery. You receive an error when you attempt to delete from a query that contains such a correlated subquery.

See the Informix Guide to SQL: Tutorial for a detailed discussion about cascading deletes.

Constraint Mode Definition

You can set the object mode of the constraint to the enabled, disabled, or filtering mode. For a discussion of object modes, see "Terminology for Object Modes".

You can use the Constraint Mode Definition option for the following purposes:

  • To assign a name to a column-level or table-level constraint
  • To set any type of column-level constraint or table-level constraint to the disabled, enabled, or filtering object modes
The Column-Level Constraint Definition on page 1-230 and the Table-Level Constraint Definition on page 1-231 refer to the Constraint Mode Definition.

Description of Constraint Modes
You can set constraints in the following modes: disabled, enabled, and filtering. The following list explains these modes and options.

Constraint Mode Effect

disabled

A constraint created in disabled mode is not enforced during insert, delete, and update operations.

enabled

A constraint created in enabled mode is enforced during insert, delete, and update operations. If a target row causes a violation of the constraint, the statement fails.

filtering

A constraint created in filtering mode is enforced during insert, delete, and update operations. If a target row causes a violation of the constraint, the statement continues processing, but the bad row is written to the violations table associated with the target table. Diagnostic information about the constraint violation is written to the diagnostics table associated with the target table.

If you choose filtering mode, you can specify the WITHOUT ERROR or WITH ERROR options. The following list explains these options.

Error Option Effect

WITHOUT ERROR

When a filtering-mode constraint is violated during an insert, delete, or update operation, no integrity-violation error is returned to the user.

WITH ERROR

When a filtering-mode constraint is violated during an insert, delete, or update operation, an integrity-violation error is returned to the user.

Using Constraint Mode Definitions
You must observe the following rules concerning the use of constraint mode definitions:

  • If you do not specify the object mode of a column-level constraint or table-level constraint explicitly, the default mode is enabled.
  • If you do not specify the WITH ERROR or WITHOUT ERROR option for a filtering-mode constraint, the default error option is WITHOUT ERROR.
  • Constraints defined on temporary tables are always in the enabled mode. You cannot create a constraint on a temporary table in the disabled or filtering mode, nor can you use the SET statement to switch the object mode on a temporary table to the disabled or filtering mode.
  • You cannot assign a name to a not null constraint on a temporary table.
  • You cannot create a constraint on a table that is serving as a violations or diagnostics table for another table.

Options

The CREATE TABLE options let you specify logging and rowid options, optional storage locations, and user-defined access methods.

WITH Clause

Using WITH ROWIDS
Nonfragmented tables contain a hidden column called the rowid column. However, fragmented tables do not contain this column. If a table is fragmented, you can use the WITH ROWIDS clause to add the rowid column to the table. The database server assigns each row in the rowid column a unique number that remains stable for the life of the row. The database server uses an index to find the physical location of the row. After you add the rowid column, each row contains an additional 4 bytes to store the rowid.

You cannot use the WITH ROWIDS clause with typed tables.

Important: Use the WITH ROWIDS clause only on fragmented tables. In non- fragmented tables, the rowid column remains unchanged. Informix recommends, however, that you utilize primary keys as an access method rather than exploiting the rowid column.

Using WITH NO LOG
You must use the WITH NO LOG keywords on temporary tables created in temporary dbspaces. Using the WITH NO LOG keywords prevents logging of temporary tables in databases started with logging.

If you use the WITH NO LOG keywords in a CREATE TABLE statement, and the database does not use logging, the WITH NO LOG option is ignored.

Once you turn off logging on a temporary table, you cannot turn it back on; a temporary table is, therefore, always logged or never logged.

The following example shows how to prevent logging temporary tables in a database that uses logging:

Storage Option

Element Purpose Restrictions Syntax

dbspace

The name of the dbspace in which to store the table. The default for database tables is the dbspace in which the current database resides.

Specified dbspace must already exist.

Identifier, p. 1-966

extspace

The name of an external space in which to store a virtual table

Specified extspace must already exist.

The storage option allows you to specify where the table is stored and the locking granularity for the table. If you use the Access Method Option on page 1-255 to specify an access method, the spaces named must be supported by that access method.

You can specify a dbspace for the table that is different from the storage location specified for the database, or fragment the table into several dbspaces. You can also specify an sbspace for each smart large object (CLOB or BLOB) using the PUT clause.

Tip: If your table has columns that contain simple large objects (TEXT or BYTE), you can specify a separate blobspace for each object. For information on storing simple large objects, refer to "Large-Object Data Types".
The following statement creates the foo table. The data for the table is fragmented into the dbs1 and dbs2 dbspaces. However, the PUT clause assigns the smart large object data in the gamma and delta columns to the sb1 and sb2 sbspaces, respectively. The TEXT data in the eps column is assigned to the blb1 blobspace.

The Storage Option appears in the Options diagram on page 1-243.

IN dbspace Clause
The IN dbspace clause allows you to isolate a table. The dbspace that you specify must already exist. If you do not specify the IN dbspace clause, the default is the dbspace where the current database resides. Temporary tables do not have a default dbspace. For further information about storing temporary tables, see the "Temporary Tables".

For example, if the stores7 database is in the stockdata dbspace, but you want the customer data placed in a separate dbspace called custdata, use the following statements:

For more information about storing your tables in separate dbspaces, see the INFORMIX-Universal Server Administrator's Guide.

FRAGMENT BY Clause
The FRAGMENT BY clause allows you to create fragmented tables. Fragmentation means that groups of rows within a table are stored together in the same dbspace.

(1 of 2)

Element Purpose Restrictions Syntax

dbspace

The dbspace that contains a table fragment

You must specify at least two dbspaces. You can specify a maximum of 2,048 dbspaces. The dbspaces must exist when you execute the statement.

Identifier, p. 1-966

frag-expression

An expression that defines a fragment where a row is to be stored using a range, hash, or arbitrary rule

If you specify a value for remainder dbspace, you must specify at least one fragment expression. If you do not specify a value for remainder dbspace, you must specify at least two fragment expressions. You can specify a maximum of 2,048 fragment expressions. Each fragment expression can contain only columns from the current table and only data values from a single row. No subqueries, stored procedures, current date/time functions, or aggregates are allowed in a fragment expression.

Expression, p. 1-880, and Condition, p. 1-835

remainder dbspace

The dbspace that contains table rows that do not meet the conditions defined in any fragment expression

If you specify two or more fragment expressions, remainder dbspace is optional. If you specify only one fragment expression, remainder dbspace is required. The dbspace specified in remainder dbspace must exist at the time you execute the statement.

Identifier, p. 1-966

Use the FRAGMENT BY clause to define the distribution scheme, either round-robin or expression-based.

In a round-robin distribution scheme, specify at least two dbspaces where you want the fragments to be placed. As records are inserted into the table, they are placed in the first available dbspace. The database server balances the load between the specified dbspaces as you insert records and distributes the rows in such a way that the fragments always maintain approximately the same number of rows. In this distribution scheme, the database server must scan all fragments when it searches for a row.

In an expression-based distribution scheme, each fragment expression in a rule specifies a dbspace. Each fragment expression within the rule isolates data and aids the database server in searching for rows. Specify one of the following rules:

  • Range rule
    A range rule specifies fragment expressions that use a range to specify which rows are placed in a fragment, as the following example shows:

  • Hash rule
    A hash rule specifies fragment expressions that are created when you use a hash algorithm, which is often implemented with the MOD function, as the following example shows:

  • Arbitrary rule
    An arbitrary rule specifies fragment expressions based on a predefined SQL expression that typically includes the use of OR clauses to group data, as the following example shows:

Warning: When you specify a date value in a fragment expression, make sure to specify 4 digits instead of 2 digits for the year. When you specify a 4-digit year, the DBCENTURY environment variable has no effect on the distribution scheme. When you specify a 2-digit year, the DBCENTURY environment variable can affect the distribution scheme and can produce unpredictable results. See the "Informix Guide to SQL: Syntax" for more information on the DBCENTURY environment variable.

PUT Clause

The PUT clause specifies storage information for smart large objects (CLOB and BLOB columns).

Element Purpose Restrictions Syntax

column name

The name of the smart-large-object column to store in the specified sbspace

Column must be BLOB or CLOB data type.

Identifier, p. 1-966

kbytes

The number of kilobytes to allocate for the extent size

Number must be an integer value.

sbspace

An area of storage used for smart large objects

The sbspace must exist.

A smart large object is contained in a single sbspace. The SB_SPACE_NAME configuration parameter specifies the system default in which smart large objects are created unless you specify another area.

Important: The PUT clause does not affect the storage of simple large-object data types (BYTE and TEXT).
The PUT clause appears in the Storage Option on page 1-245.

EXTENT SIZE Option of the PUT Clause
The EXTENT SIZE option of the PUT clause specifies the number of kilobytes in an smart large-object extent. The EXTENT SIZE should be a multiple of the sbspace page size. If it is not, Universal Server rounds up the number to the nearest multiple of the sbspace page size.

If the extent size is not specified, or if no extent of the specified size exists, Universal Server uses the larger of:

  • the size of the write request.
  • the smallest extent size for the sbspace.
After eight extension operations for a single smart large object, Universal Server automatically doubles the extent size for that smart large object, to avoid having a large number of extents.

LOG and NO LOG Options of the PUT Clause
Use the LOG option of the PUT clause when you want the database server to follow the logging procedure used with the current database log for the corresponding smart large object.

Warning: Use of the LOG option can generate large amounts of log traffic and increase the risk that the logical log fills up.
Instead of full logging, you might turn off logging when you load the smart large object initially, and then turn logging back on once the smart large object has been loaded.

Use the NO LOG option to turn off logging. If you use NO LOG, you can restore the smart-large-object metadata later to a state in which no structural inconsistencies exist. In most cases, no transaction inconsistencies will exist either, but that result is not guaranteed.

The NO LOG option is the default logging behavior for smart large objects.

HIGH INTEG and MODERATE INTEG Option
The HIGH INTEG option of the PUT clause provides user data pages that contain a page header and a page trailer. The database server uses the header and trailer to detect incomplete writes and data corruption. The HIGH INTEG option is the default.

Important: After you have specified the HIGH INTEG option, you cannot use the ALTER TABLE statement to change to MODERATE INTEG.
The MODERATE INTEG option provides a lower level of data integrity but is faster. It does not produce page headers or trailers on user data pages, so it preserves the user data alignment on pages. The MODERATE INTEG option is useful for moving large volumes of data through the server when very high data integrity is not required. Audio and video applications may benefit from a MODERATE INTEG option.

KEEP ACCESS TIME and NO KEEP ACCESS TIME Options
The KEEP ACCESS TIME option of the PUT clause tells the database server to record, in the smart large-object meta data, the system time at which the corresponding smart large object was last read or written. This capability is provided for compatibility with the Illustra interface.

When you specify the NO KEEP ACCESS TIME option, the database server does not track the system time at which the corresponding smart large object was last read or written. This option provides better performance than the KEEP ACCESS TIME option.

The NO KEEP ACCESS TIME option is the default.

EXTENT Option

Element Purpose Restrictions Syntax

first kbytes

The length in kilobytes of the first extent for the table. The default length is eight times the disk page size on your system. For example, if you have a 2-kilobyte page system, the default length is 16 kilobytes.

The minimum length is four times the disk page size on your system. For example, if you have a 2-kilobyte page system, the minimum length is eight kilobytes. The maximum length is equal to the chunk size.

Expression, p. 1-880

next kbytes

The length in kilobytes for the subsequent extents. The default length is eight times the disk page size on your system. For example, if you have a 2-kilobyte page system, the default length is 16 kilobytes.

The minimum length is four times the disk page size on your system. For example, if you have a 2-kilobyte page system, the minimum length is 8 kilobytes.The maximum length is equal to the chunk size.

Expression, p. 1-880

See the INFORMIX-Universal Server Performance Guide for a discussion about calculating extent sizes.

The following example specifies a first extent of 20 kilobytes and allows the rest of the extents to use the default size:

Revising Extent Sizes for Unloaded Tables
You can revise the CREATE TABLE statements in generated schema files to revise the extent and next-extent sizes of unloaded tables. See the INFORMIX-Universal Server Administrator's Guide for information about revising extent sizes.

The EXTENT option appears in the Storage Option on page 1-245.

LOCK MODE Clause

The default locking granularity is a page.

Row-level locking provides the highest level of concurrency. However, if you are using many rows at one time, the lock-management overhead can become significant. Also, you might exceed the maximum number of locks available, depending on the configuration of your database-server system.

Page locking allows you to obtain and release one lock on a whole page of rows. Page locking is especially useful when you know that the rows are grouped into pages in the same order that you are using to process all the rows. For example, if you are processing the contents of a table in the same order as its cluster index, page locking is especially appropriate.

You can change the lock mode of an existing table with the ALTER TABLE statement.

The Lock Mode clause appears in the Storage Option on page 1-245.

Access Method Option

A primary access method is a set of routines that perform all of the operations needed to make a table available to a server, such as create, drop, insert, delete, update, and scan. Universal Server provides a built-in primary access method.

An virtual table is managed outside of the database server but can be accessed by Universal Server users with SQL statements. Access to an virtual table requires a user-defined primary access method.

DataBlade Modules can provide other primary access methods to access virtual tables. When you access a virtual table, the database server calls the routines associated with that access method rather than the built-in table routines. For more information on these other primary access methods, refer to the DataBlade user guides.

Element Purpose Restrictions Syntax

access method name

Name of the access method to be used with this table

Access method must already exist.

See "Access Method Name Clause"

configuration keyword

One of the configuration keywords associated with the specified access method name.

Keyword must already exist.

Keywords can be up to 18 bytes in length.

configuration value

Value of the specified configuration keyword. Configuration values are not required with all keywords.

You can retrieve a list of configuration values for an access method from a table descriptor (mi_am_table_desc) using the MI_TAB_AMPARAM macro.

Value must be defined by the access method.

Value must be in quotation marks.

Values can be up to 236 bytes in length.

The Access Method Option appears in the Options clause on page 1-243.

Access Method Name Clause

For example, if there was an access method called textfile, you could specify that access method in the following Access Method clause:

The Access Method Name clause appears in the Access Method Option on page 1-255.

References

See the ALTER TABLE, CREATE INDEX, CREATE DATABASE, DROP TABLE, and SET statements in this manual. Also see the Condition, Data Type, Identifier, and Table Name segments.

In the Informix Guide to SQL: Tutorial, see the discussion of data-integrity constraints and the discussion of the ON DELETE CASCADE clause. Also see the discussion of creating a database and tables in the same book.

In the INFORMIX-Universal Server Performance Guide, see the discussion of extent sizing.




Informix Guide to SQL: Syntax, version 9.1
Copyright © 1998, Informix Software, Inc. All rights reserved.