CREATE TABLE statement

Description

Creates a new table in the database or on a remote server.

Syntax

CREATE [ { GLOBAL | LOCAL } TEMPORARY ] TABLE
owner. ]table-name
… ( column-definitioncolumn-constraint ] … 
[ , column-definitioncolumn-constraint ] …]
[ , table-constraint ] … )
…[ IN dbspace-name ]
…[ ON COMMITDELETE | PRESERVE } ROWS 
| NOT TRANSACTIONAL ]
[ AT location-string ]
[PARTITION BY range-partitioning-scheme ]

Parameters

column-definition:

column-name data-type [ [ NOT ] NULL ] [ IN dbspace-name ] [ DEFAULT default-value | IDENTITY ] [ PARTITIONpartition-name IN  dbspace-name [ , ... ] ) ]

default-value:

special-value | string | global variable | [ - ] number | ( constant-expression ) | built-in-functionconstant-expression ) | AUTOINCREMENT | CURRENT DATABASE | CURRENT REMOTE USER | NULL | TIMESTAMP | LAST USER

special-value:

CURRENTDATE | TIME | TIMESTAMP | USER | PUBLISHER } | USER

column-constraint:

[ CONSTRAINT constraint-name ] { { UNIQUE  |  PRIMARY KEY  |  REFERENCES table-name [ ( column-name ) ] [ action ]  } [ IN dbspace-name ]  |  CHECKcondition )  |  IQ UNIQUEinteger ) }

table-constraint:

CONSTRAINT constraint-name ] { { UNIQUEcolumn-name [ , column-name ] … ) | PRIMARY KEYcolumn-name [ , column-name ] … ) } [ IN dbspace-name ] | foreign-key-constraint| CHECKcondition ) | IQ UNIQUEinteger ) }

foreign-key-constraint:

FOREIGN KEYrole-name ] [ ( column-name [ , column-name ] … ) ] …REFERENCES table-name [ ( column-name [ , column-name ] … ) ] …[ action ] [ IN dbspace-name ]

action:

ONUPDATE | DELETERESTRICT }

location-string:

remote-server-name.[db-name].[owner].object-name | remote-server-name;[db-name ];[ owner ];object-name }

range-partitioning-scheme:

RANGEpartition-key ) ( range-partition-decl [,range-partition-decl ...] )

partition-key:

column-name

range-partition-decl:

partition-name VALUES <= ( {constant-expr |  MAX } ) [ IN dbspace-name ]

Examples

Example 1

Creates a table named SalesOrders2 with five columns. Data pages for columns FinancialCode, OrderDate, and ID are in dbspace Dsp3.

Data pages for integer column CustomerID are in dbspace Dsp1. Data pages for CLOB column History are in dbspace Dsp2. Data pages for the primary key, HG for ID, are in dbspace Dsp4.

CREATE TABLE SalesOrders2 (
FinancialCode CHAR(2),
CustomerID int IN Dsp1,
History CLOB IN Dsp2,
OrderDate TIMESTAMP,
ID BIGINT,
PRIMARY KEY(ID) IN Dsp4 
) IN Dsp3

Example 2

Creates a table fin_code2 with four columns. Data pages for columns code, type, and id are in the default dbspace, which is determined by the value of the database option DEFAULT_DBSPACE.

Data pages for CLOB column description are in dbspace Dsp2. Data pages from foreign key fk1, HG for c1 are in dbspace Dsp4:

CREATE TABLE fin_code2 (
code INT,
type CHAR(10),
description CLOB IN Dsp2,
id BIGINT,
FOREIGN KEY fk1(id) REFERENCES SalesOrders(ID) IN Dsp4
)

Example 3

Creates a table t1 where partition p1 is adjacent to p2 and partition p2 is adjacent to p3.

CREATE TABLE t1 (c1 INT, c1 INT)
PARTITION BY RANGE(c1),
(p1 VALUES <= (0), p2 VALUES <= (10), p3 VALUES <= (100))

Example 4

Creates a partitioned table bar with six columns and three partitions, mapping data to partitions based on dates.

CREATE TABLE bar (
		c1 INT IQ UNIQUE(65500),
		c2 VARCHAR(20),
		c3 CLOB PARTITION (P1 IN Dsp11, P2 IN Dsp12,
		   P3 IN Dsp13),
		c4 DATE,
		c5 BIGINT,
		c6 VARCHAR(500) PARTITION (P1 IN Dsp21,
		   P2 IN Dsp22),
		PRIMARY KEY (c5) IN Dsp2) IN Dsp1
		PARTITION BY RANGE (c4)
		(P1 VALUES <= ('2006/03/31') IN Dsp31, 
		 P2 VALUES <= ('2006/06/30') IN Dsp32,
		 P3 VALUES <= ('2006/09/30') IN Dsp33
		) ;

Data page allocation for each partition follows:

Partition

Dbspaces

Columns

P1

Dsp31

c1, c2, c4, c5

P1

Dsp11

c3

P1

Dsp21

c6

P2

Dsp32

c1, c2, c4, c5

P2

Dsp12

c3

P2

Dsp22

c6

P3

Dsp33

c1, c2, c4, c5, c6

P3

Dsp13

c3

P1, P2, P3

Dsp1

lookup store of c1 and other shared data

P1, P2, P3

Dsp2

primary key (HG for c5)

Example 5

Creates a table for a library database to hold book information:

CREATE TABLE library_books (
isbn CHAR(20)      PRIMARY KEY IQ UNIQUE (150000),
copyright_date     DATE,
title              CHAR(100),
author             CHAR(50)
)

Example 6

Creates a table for a library database to hold information on borrowed books:

CREATE TABLE borrowed_book (
date_borrowed DATE NOT NULL,
date_returned DATE,
book       CHAR(20)
           REFERENCES library_books (isbn),
CHECK( date_returned >= date_borrowed )
)

Example 7

Creates a table named t1at the remote server SERVER_A and create a proxy table named t1 that is mapped to the remote table:

CREATE TABLE t1
( a  INT,
  b  CHAR(10))
AT 'SERVER_A.db1.joe.t1'

Example 8

Creates a table named tab1 that contains a column c1 with a default value of the special constant LAST USER:

CREATE TABLE tab1(c1 CHAR(20) DEFAULT LAST USER)

Usage

You can create a table for another user by specifying an owner name. If GLOBAL TEMPORARY or LOCAL TEMPORARY is not specified, the table is referred to as a base table. Otherwise, the table is a temporary table.

A created global temporary table exists in the database like a base table and remains in the database until it is explicitly removed by a DROP TABLE statement. The rows in a temporary table are visible only to the connection that inserted the rows. Multiple connections from the same or different applications can use the same temporary table at the same time and each connection sees only its own rows. A given connection inherits the schema of a global temporary table as it exists when the connection first refers to the table. The rows of a temporary table are deleted when the connection ends.

When you create a local temporary table, omit the owner specification. If you specify an owner when creating a temporary table, as, for example, with CREATE TABLE dbo.#temp(col1 int), a base table is incorrectly created.

An attempt to create a base table or a global temporary table will fail, if a local temporary table of the same name exists on that connection, as the new table cannot be uniquely identified by owner.table.

You can, however, create a local temporary table with the same name as an existing base table or global temporary table. References to the table name access the local temporary table, as local temporary tables are resolved first.

For example, consider this sequence:

CREATE TABLE t1 (c1 int);
INSERT t1 VALUES (9);

CREATE LOCAL TEMPORARY TABLE t1 (c1 int);
INSERT t1 VALUES (8);

SELECT * FROM t1;

The result returned is 8. Any reference to t1 refers to the local temporary table t1 until the local temporary table is dropped by the connection.

In a procedure, use the CREATE LOCAL TEMPORARY TABLE statement, instead of the DECLARE LOCAL TEMPORARY TABLE statement, when you want to create a table that persists after the procedure completes. Local temporary tables created using the CREATE LOCAL TEMPORARY TABLE statement remain until they are either explicitly dropped, or until the connection closes.

Local temporary tables created in IF statements using CREATE LOCAL TEMPORARY TABLE also persist after the IF statement completes.

You cannot use a temporary table to create a join index.

Do not update a base table that is part of any join index. This is disallowed, and returns this error:

-1000102 Cannot update table %2 because it is defined in one or more join indexes

Sybase IQ does not support the CREATE TABLE ENCRYPTED clause for table-level encryption of Sybase IQ tables. However, the CREATE TABLE ENCRYPTED clause is supported for SQL Anywhere tables in a Sybase IQ database.

IN Specifies in which database file (dbspace) the table is to be created. You can specify SYSTEM with this clause to put either a permanent or temporary table in the catalog store. All other use of the IN clause is ignored. You cannot use this clause to place an IQ table in a particular dbspace. By default, all permanent tables are placed in the main IQ store, and all temporary tables are placed in the temporary IQ store. Global temporary and local temporary tables can never be in the IQ store.

The IN clauses in column-definition, column-constraint, table-constraint, and foreign-key clauses specify the dbspace where the object is to be created. If the IN clause is omitted, Sybase IQ creates the object in the dbspace where the table is assigned.

For more information about dbspaces, see CREATE DBSPACE statement.

ON COMMIT Allowed for temporary tables only. By default, the rows of a temporary table are deleted on COMMIT.

For clause behavior on multiplex global temporary tables, see “Preserving rows” in Chapter 3, “Running Multiplex Transactions” of Using Sybase IQ Multiplex.

NOT TRANSACTIONAL Allowed only for temporary tables. A table created using NOT TRANSACTIONAL is not affected by either COMMIT or ROLLBACK.

The NOT TRANSACTIONAL clause provides performance improvements in some circumstances because operations on nontransactional temporary tables do not cause entries to be made in the rollback log. For example, NOT TRANSACTIONAL might be useful if procedures that use the temporary table are called repeatedly with no intervening COMMITs or ROLLBACKs.

The parenthesized list following the CREATE TABLE statement can contain these clauses in any order:

AT Used to create a table at the remote location specified by location-string. The local table that is created is a proxy table that maps to the remote location. Tables used as proxy tables must have names of 30 characters or less. The AT clause supports the semicolon (;) as a delimiter. If a semicolon is present anywhere in the location-string, the semicolon is the field delimiter. If no semicolon is present, a period is the field delimiter. This allows file names and extensions to be used in the database and owner fields.

Semicolon field delimiters are used primarily with server classes not currently supported; however, you can also use them in situations where a period would also work as a field delimiter. For example, this statement maps the table proxy_a to the SQL Anywhere database mydb on the remote server myasa:

CREATE TABLE proxy_a1
AT 'myasa;mydb;;a1'

Foreign-key definitions are ignored on remote tables. Foreign-key definitions on local tables that refer to remote tables are also ignored. Primary key definitions are sent to the remote server if the server supports primary keys.

In a simplex environment, you cannot create a proxy table that refers to a remote table on the same node. In a multiplex environment, you cannot create a proxy table that refers to the remote table defined within the multiplex.

For example, in a simplex environment, if you try to create proxy table proxy_e which refers to base table Employees defined on the same node, the CREATE TABLE ... AT statement is rejected with an error message. In a multiplex environment, the CREATE TABLE .... AT statement is rejected if you create proxy table proxy_e from any node (coordinator or secondary) that refers to remote table Employees defined within a multiplex.

column-definition Defines a column in the table. Allowable data types are described in Chapter 3, “SQL Data Types” in Reference: Building Blocks, Tables, and Procedures. Two columns in the same table cannot have the same name. If NOT NULL is specified, or if the column is in a UNIQUE or PRIMARY KEY constraint, the column cannot contain any NULL values. You can create up to 45,000 columns; however, there might be performance penalties with more than 10,000 columns in a table. The limit on the number of columns per table that allow NULLs is approximately 8*(database-page-size - 30).

table-constraint Helps ensure the integrity of data in the database. There are four types of integrity constraints:

If a statement would cause changes to the database that would violate an integrity constraint, the statement is effectively not executed and an error is reported. (Effectively means that any changes made by the statement before the error was detected are undone.)

Sybase IQ enforces single-column UNIQUE constraints by creating an HG index for that column.

NoteYou cannot define a column with a BIT data type as a UNIQUE or PRIMARY KEY constraint. Also, the default for columns of BIT data type is to not allow NULL values; you can change this by explicitly defining the column as allowing NULL values.

column-constraint Restricts the values the column can hold. Column and table constraints help ensure the integrity of data in the database. If a statement would cause a violation of a constraint, execution of the statement does not complete, any changes made by the statement before error detection are undone, and an error is reported. Column constraints are abbreviations for the corresponding table constraints. For example, these are equivalent:

CREATE TABLE Products (
	product_num integer UNIQUE
)
CREATE TABLE Products (
	product_num integer,
	UNIQUE ( product_num )
)

Column constraints are normally used unless the constraint references more than one column in the table. In these cases, a table constraint must be used.

IQ UNIQUE constraint This constraint can be specified for columns only. IQ UNIQUE defines the cardinality of the column, and it is used to optimize the indexes internally. The default value is 0, which gives IQ no information for optimizing the default index. The IQ UNIQUE constraint should be applied if the expected distinct count (the number of unique values) for the column is less than or equal to 65536. This allows Sybase IQ to optimize storage of this column's data.

When the MINIMIZE_STORAGE option is ON (the default for new databases is OFF), it is equivalent to specifying IQ UNIQUE 255 for every newly created column, and there is no need to specify IQ UNIQUE except for columns with more than 65536 unique values. For related information, see “Optimizing storage and query performance,”Chapter 5, “Working with Database Objects,” in the System Administration Guide: Volume 1.


Integrity constraints

UNIQUE or UNIQUE ( column-name, … ) No two rows in the table can have the same values in all the named columns. A table may have more than one unique constraint.

There is a difference between a unique constraint and a unique index. Columns of a unique index are allowed to be NULL, while columns in a unique constraint are not. A foreign key can reference either a primary key or a column with a unique constraint, but not a unique index, because it can include multiple instances of NULL.

PRIMARY KEY or PRIMARY KEY ( column-name, … ) The primary key for the table consists of the listed columns, and none of the named columns can contain any NULL values. Sybase IQ ensures that each row in the table has a unique primary key value. A table can have only one PRIMARY KEY.

When the second form is used (PRIMARY KEY followed by a list of columns), the primary key is created including the columns in the order in which they are defined, not the order in which they are listed.

When a column is designated as PRIMARY KEY, FOREIGN KEY, or UNIQUE, Sybase IQ creates a High_Group index for it automatically. For multicolumn primary keys, this index is on the primary key, not the individual columns. For best performance, you should also index each column with a HG or LF index separately.

REFERENCES primary-table-name [(primary-column-name)] This clause defines the column as a foreign key for a primary key or a unique constraint of a primary table. Normally, a foreign key would be for a primary key rather than an unique constraint. If a primary column name is specified, it must match a column in the primary table which is subject to a unique constraint or primary key constraint, and that constraint must consist of only that one column. Otherwise the foreign key references the primary key of the second table. Primary key and foreign key must have the same data type and the same precision, scale, and sign. Only a nonunique single-column HG index is created for a single-column foreign key. For a multicolumn foreign key, Sybase IQ creates a nonunique composite HG index. The maximum width of a multicolumn composite key for a unique or nonunique HG index is 1KB.

A temporary table cannot have a foreign key that references a base table and a base table cannot have a foreign key that references a temporary table. Local temporary tables cannot have or be referenced by a foreign key.

FOREIGN KEY [role-name] [(...)] REFERENCES primary-table-name [(...)] This clause defines foreign-key references to a primary key or a unique constraint in another table. Normally, a foreign key would be for a primary key rather than an unique constraint. (In this description, this other table is called the primary table.)

If the primary table column names are not specified, the primary table columns are the columns in the table’s primary key. If foreign key column names are not specified, the foreign-key columns have the same names as the columns in the primary table. If foreign-key column names are specified, then the primary key column names must be specified, and the column names are paired according to position in the lists.

If the primary table is not the same as the foreign-key table, either the unique or primary key constraint must have been defined on the referenced key. Both referenced key and foreign key must have the same number of columns, of identical data type with the same sign, precision, and scale.

The value of the row’s foreign key must appear as a candidate key value in one of the primary table’s rows unless one or more of the columns in the foreign key contains nulls in a null allows foreign key column.

Any foreign-key column not explicitly defined is automatically created with the same data type as the corresponding column in the primary table. These automatically created columns cannot be part of the primary key of the foreign table. Thus, a column used in both a primary key and foreign key must be explicitly created.

role-name is the name of the foreign key. The main function of role-name is to distinguish two foreign keys to the same table. If no role-name is specified, the role name is assigned as follows:

  1. If there is no foreign key with a role-name the same as the table name, the table name is assigned as the role-name.

  2. If the table name is already taken, the role-name is the table name concatenated with a zero-padded 3-digit number unique to the table.

The referential integrity action defines the action to be taken to maintain foreign-key relationships in the database. Whenever a primary key value is changed or deleted from a database table, there may be corresponding foreign key values in other tables that should be modified in some way. You can specify an ON DELETE clause, followed by the RESTRICT clause:

RESTRICT Generates an error if you try to update or delete a primary key value while there are corresponding foreign keys elsewhere in the database. Generates an error if you try to update a foreign key so that you create new values unmatched by a candidate key. This is the default action, unless you specify that LOAD optionally reject rows that violate referential integrity.This enforces referential integrity at the statement level.

If you use CHECK ON COMMIT without specifying any actions, then RESTRICT is implied as an action for DELETE. Sybase IQ does not support CHECK ON COMMIT.

A global temporary table cannot have a foreign key that references a base table and a base table cannot have a foreign key that references a global temporary table. Local temporary tables cannot have or be referenced by a foreign key.

CHECK ( condition ) No row is allowed to fail the condition. If an INSERT statement would cause a row to fail the condition, the operation is not permitted and the effects of the statement are undone.

The change is rejected only if the condition is FALSE; in particular, the change is allowed if the condition is UNKNOWN. CHECK condition is not enforced by Sybase IQ. For more information about TRUE, FALSE, and UNKNOWN conditions, see “NULL value” and “Search conditions” in Chapter 2, “SQL Language Elements” in Reference: Building Blocks, Tables, and Procedures.

NoteSybase recommends that you not define referential integrity foreign key-primary key relationships in Sybase IQ unless you are certain there are no orphan foreign keys.


Remote tables

Foreign-key definitions are ignored on remote tables. Foreign-key definitions on local tables that refer to remote tables are also ignored. Primary-key definitions are sent to the remote server if the server supports it.

PARTITION BY RANGE Specifies that rows are to be partitioned according to the specified ranges of values in the partitioning column.

The column-name in the partition-key clause specifies the partition key column. Sybase IQ 15.2 supports a single partition key column.

The partition-name in the range-partition-decl clause specifies the name of a new partition on which table rows are stored. Partition names must be unique within the set of partitions on a table. The partition_name clause is required.

VALUE clause Specifies the inclusive upper bound for each partition for range partitioning criteria. The user must specify the partitioning criteria for each range partition to guarantee that each row is distributed to only one partition. NULLs are allowed for the partition column and rows with NULL as partition key value belong to the first table partition. However, NULL cannot be the bound value. There is no lower bound (MIN value) for the first partition. Rows of NULL cells in the first column of the partition key will go to the first partition. For the last partition, you can either specify an inclusive upper bound or MAX. If the upper bound value for the last partition is not MAX, loading or inserting any row with partition key value larger than the upper bound value of the last partition generates an error.

MAX Denotes the infinite upper bound and can only be specified for the last partition.

IN In the partition-decl, specifies the dbspace on which rows of the partition should reside.

These restrictions affect partitions keys and bound values for range partitioned tables:


Side effects

Automatic commit.

Standards

Permissions

Must have RESOURCE authority. To create a table for another user, you must have DBA authority. To create a base table in an IQ main store dbspace, you must have DBA authority or RESOURCE authority and CREATE privilege in the specified dbspace.

See also

ALTER TABLE statement

Chapter 5, “Working with Database Objects” in System Administration Guide: Volume 1

CREATE DBSPACE statement

CREATE INDEX statement

“Creating tables” in Chapter 5, “Working with Database Objects,” in the System Administration Guide: Volume 1

DECLARE LOCAL TEMPORARY TABLE statement

DROP statement

“MINIMIZE_STORAGE option”