When you create a table and specify a column using the ON UPDATE clause, that column is computed every time a row is updated in the table. The most common use of this feature is to define a column in a table that contains a timestamp value for the last time the row was updated.
CURRENT_DATE | CURRENT_TIME[(precision)] | CURRENT_TIMESTAMP[(precision)] | GETDATE([prec]) | GETUTCDATE([prec]) | SYSDATE | USER | CURRENT_USER | SESSION_USER | SYSTEM_USER | NULL | <literal> | -<number>
The following example sets the RowTS column to the current timestamp value when a row is inserted and each time that row is updated:
CREATE TABLE mytest (
Name VARCHAR(48),
RowTS TIMESTAMP DEFAULT Current_Timestamp(6) ON UPDATE Current_Timestamp(6) )
In this example, the DEFAULT keyword sets RowTS to the current timestamp on INSERT if no explicit value is specified for the RowTS column. If an UPDATE specifies an explicit value for the RowTS column, the ON UPDATE keyword validates, but ignores, the specified value, and updates RowTS with the current timestamp. If the specified value fails validation, a SQLCODE -105 error is generated.
The following example sets the HasBeenUpdated column to a boolean value:
CREATE TABLE mytest (
Name VARCHAR(48),
HasBeenUpdated TINYINT DEFAULT 0 ON UPDATE 1 )
The following example sets the WhoLastUpdated column to the current user name:
CREATE TABLE mytest (
Name VARCHAR(48),
WhoLastUpdated VARCHAR(48) DEFAULT CURRENT_USER ON UPDATE CURRENT_USER )
You cannot specify an ON UPDATE clause if the column also has a COMPUTECODE data constraint. Attempting to do so results in an SQLCODE -1 error at compile or prepare time.
description
InterSystems SQL provides a %DESCRIPTION keyword, which you can use to provide a description for documenting a table or a column. %DESCRIPTION is followed by text string, description, enclosed in single quotes. This text can be of any length, and can contain any characters, including blank spaces. (A single-quote character within a description is represented by two single quotes. For example: 'Joe''s Table'.) A table can have a %DESCRIPTION. Each column of a table can have its own %DESCRIPTION, specified after the data type. If you specify more than one table-wide %DESCRIPTION for a table, InterSystems IRIS issues an SQLCODE -82 error. If you specify more than one %DESCRIPTION for a column, the system retains only the last %DESCRIPTION specified. You cannot use ALTER TABLE to alter existing descriptions.
In the corresponding persistent class definition, a description appears prefaced by three slashes on the line immediately before the corresponding class (table) or property (column) syntax. For example: /// Joe's Table. In the Class Reference for the corresponding persistent class, the table description appears at the top just after the class name and SQL table name; a column description appears just after the corresponding property syntax.
You can display %DESCRIPTION text using the DESCRIPTION property of INFORMATION.SCHEMA.TABLESOpens in a new tab or INFORMATION.SCHEMA.COLUMNSOpens in a new tab. For example:
SELECT COLUMN_NAME,DESCRIPTION FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='MyTable'
sqlCollation
The type of collation used to sort values of a column, specified as one of the following SQL collation types: %EXACT, %MINUS, %PLUS, %SPACE, %SQLSTRING, %SQLUPPER, %TRUNCATE, or %MVR. Collation keywords are not case-sensitive. It is recommended that you specify the optional keyword COLLATE before the collation parameter for programming clarity, but this keyword is not required. The percent sign (%) prefix to the various collation parameter keywords is also optional.
The default is the namespace default collation (%SQLUPPER, unless changed). %SQLSTRING, %SQLUPPER, and %TRUNCATE may be specified with an optional maximum length truncation argument, an integer enclosed in parentheses. For more information on collation, see Table Field/Property Definition Collation.
%EXACT collation follows the ANSI (or Unicode) character collation sequence. This provides case-sensitive string collation and recognizes leading and trailing blanks and tab characters.
The %SQLUPPER collation converts all letters to uppercase for the purpose of collation. For further details on not case-sensitive collation, refer to the %SQLUPPER function.
The %SPACE and %SQLUPPER collations append a blank space to the data. This forces string collation of NULL and numeric values.
The %SQLSTRING, %SQLUPPER, and %TRUNCATE collations provide an optional maxlen parameter, which must be enclosed in parentheses. maxlen is a truncation integer that specifies the maximum number of characters to consider when performing collation. This parameter is useful when creating indices with columns containing large data values.
The %PLUS and %MINUS collations handle NULL as a zero (0) value.
InterSystems SQL provides functions for most of these collation types. Refer to the %EXACT, %SQLSTRING, %SQLUPPER, %TRUNCATE functions for further details.
ObjectScript provides the Collation()Opens in a new tab method of the %SYSTEM.UtilOpens in a new tab class for data collation conversion.
Note:
To change the namespace default collation from %SQLUPPER (which is not case-sensitive) to another collation type, such as %SQLSTRING (which is case-sensitive), use the following command:
WRITE $$SetEnvironment^%apiOBJ("collation","%Library.String","SQLSTRING")
After issuing this command, you must purge indexes, recompile all classes, and then rebuild indexes. Do not rebuild indices while the table’s data is being accessed by other users. Doing so may result in inaccurate query results.
shardKeyColumn
The column, or comma-separated list of columns, used as the shard key. Specify shardKeyColumn in the SHARD KEY clause, immediately after the closing parenthesis of the table column list but before the WITH clause (if specified). Specifying the shard key definition as an element within the table column list is supported for backwards compatibility, but defining a shard key in both locations generates an SQLCODE -327 error.
You cannot define the RowID column as the shard key. However, if the created table includes an IDENTITY column or IDKEY, you can define either of those columns as the shard key.
For information on choosing a shard key, see Choose a Shard Key.
coshardKeyColumn
The name of the shard key column that is used in cosharded joins with the shard key of the table defined in coshardTable. Specify coshardKeyColumn in the COSHARD WITH syntax: SHARD KEY (coshardKeyColumn) COSHARD WITH coshardTable.
coshardTable
The name of an existing table that the table being created coshards with. The table specified in the COSHARD WITH clause must be a sharded table with a system-assigned shard key.
When you specify this table, InterSystems IRIS sets the CoshardWith index keyword in the ShardKey index for the sharded table. This CoshardWith index keyword is equal to the class that projects the table.
To determine which sharded tables specified in a query are cosharded, view the Cosharding comment option.
pName = pValue
A %CLASSPARAMETER name-value pair that sets the class parameter named pName to the value pValue. You can specify multiple %CLASSPARAMETER clauses using comma-separated name-value pairs. For example: WITH %CLASSPARAMETER DEFAULTGLOBAL = '^GL.EMPLOYEE', %CLASSPARAMETER MANAGEDEXTENT 0. Separate the name and value using an equal sign or at least one space. Class parameter values are literal strings and numbers and must be defined as constant values.
Some of the class parameters currently in use are: ALLOWIDENTITYINSERT, DATALOCATIONGLOBALOpens in a new tab, DEFAULTGLOBALOpens in a new tab, DSINTERVALOpens in a new tab, DSTIMEOpens in a new tab, EXTENTQUERYSPECOpens in a new tab, EXTENTSIZEOpens in a new tab, GUIDENABLEDOpens in a new tab, MANAGEDEXTENTOpens in a new tab, READONLYOpens in a new tab, ROWLEVELSECURITYOpens in a new tab, SQLPREVENTFULLSCANOpens in a new tab, USEEXTENTSETOpens in a new tab, VERSIONCLIENTNAMEOpens in a new tab, VERSIONPROPERTYOpens in a new tab. Refer to the %Library.PersistentOpens in a new tab class for descriptions of these class parameters.
You can use the USEEXTENTSETOpens in a new tab and DEFAULTGLOBALOpens in a new tab class parameters to define the global naming strategy for table data storage and index data storage.
The IDENTIFIEDBYOpens in a new tab class parameter is deprecated. You must convert IDENTIFIEDBY relationships to proper Parent/Child relationships to be supported in InterSystems IRIS.
A CREATE TABLE that defines a sharded table cannot define the DEFAULTGLOBALOpens in a new tab, DSINTERVALOpens in a new tab, DSTIMEOpens in a new tab, or VERSIONPROPERTYOpens in a new tab class parameter.
You can specify additional class parameters as needed. For more details, see Class Parameters.
Examples
Create and Populate Table
Use CREATE TABLE to create a table, Employee, with several columns:
-
The EmpNum column (containing the employee's company ID number) is an integer value that cannot be NULL; additionally, it is declared as a primary key for the table and automatically increments each time a row is inserted into the table.
-
The employee's last and first names are stored in character string columns that have a maximum length of 30 and cannot be NULL.
-
The remaining columns are for the employee's start date, accrued vacation time, and accrued sick time, which use the TIMESTAMP and INT data types.
CREATE TABLE Employee (
EmpNum INT NOT NULL AUTO_INCREMENT,
NameLast CHAR(30) NOT NULL,
NameFirst CHAR(30) NOT NULL,
StartDate TIMESTAMP,
AccruedVacation INT,
AccruedSickLeave INT,
CONSTRAINT EMPLOYEEPK PRIMARY KEY (EmpNum))
To modify the table schema, use ALTER TABLE. For example, this statement changes the name of the table from Employee to Employees.
ALTER TABLE Employee RENAME Employees
To insert rows into a table, use INSERT. For example, this statement inserts a row with only the required columns in the table. The EmpNum column is also required, but you do not need to specify it because it auto-increments.
INSERT INTO Employees (NameLast, NameFirst) VALUES ('Zubik','Jules')
To update inserted rows, use UPDATE. For example, in the inserted row, this statement sets a value in one of the columns that was missing data.
UPDATE Employees SET AccruedVacation = 15 WHERE Employees.EmpNum = 1
To delete a row, use DELETE. For example, this statement deletes the inserted row.
DELETE FROM Employess WHERE EmpNum = 1
To delete an entire table, use DROP TABLE. Be careful using DROP TABLE. Unless you specify the %NODELDATA keyword, this command deletes both the table and all associated data.
DROP TABLE Employess
Security and Privileges
The CREATE TABLE command is a privileged operation that requires %CREATE_TABLE administrative privileges. Executing a CREATE TABLE command without these privileges results in an SQLCODE -99 error. To assign %CREATE_TABLE privileges to a user or role, use the GRANT command, assuming that you hold appropriate granting privileges. If you are using the CREATE TABLE AS SELECT syntax, then you must have SELECT privilege on the table specified in the query. Administrative privileges are namespace-specific. For more details, see Privileges.
By default, CREATE TABLE security privileges are enforced. To configure this privilege requirement system-wide, use the $SYSTEM.SQL.Util.SetOption()Opens in a new tab method. For example: SET status=$SYSTEM.SQL.Util.SetOption("SQLSecurity",0,.oldval). To determine the current setting, call the $SYSTEM.SQL.CurrentSettings()Opens in a new tab method, which displays an SQL security enabled setting. The default is 1 (enabled). When SQL security is enabled (recommended), a user can perform actions only on table or views for which they have privileges. Set this method to 0 to disable SQL security for any new process started after changing this setting. This means that privilege-based table/view security is suppressed. You can create a table without specifying a user. In this case, Dynamic SQL assigns “_SYSTEM” as user, and Embedded SQL assigns "" (the empty string) as user. Any user can perform actions on a table or view even if that user has no privileges to do so.
Embedded SQL does not use SQL privileges. In Embedded SQL, you can use the $SYSTEM.Security.Login()Opens in a new tab method to log in as a user with appropriate privileges. You must have the %Service_Login:Use privilege to invoke the $SYSTEM.Security.Login() method. For example:
DO $SYSTEM.Security.Login("_SYSTEM","SYS")
NEW SQLCODE,%msg
&sql(CREATE TABLE MyTable (col1 INT, col2 INT))
IF SQLCODE=0 {WRITE !,"Table created"}
ELSE {WRITE !,"SQLCODE=",SQLCODE,": ",%msg }
For more information, see %SYSTEM.SecurityOpens in a new tab.
If CREATE TABLE is used with computed columns that require executing code, the user will need %Development:USE privileges in addition to %CREATE_TABLE privileges unless the command is used in Embedded SQL.
Users can also avoid privilege checks by creating a command with the %SQL.StatementOpens in a new tab class and using either the %Prepare() method with the checkPriv argument set to 0 or the %ExecDirectNoPriv() method.
More About
Defining a Primary Key
Defining a primary key is optional. When you define a table, InterSystems IRIS automatically creates a generated column, the RowID Column (default name "ID") which functions as a unique row identifier. As each record is added to a table, InterSystems IRIS assigns a unique non-modifiable positive integer to that record’s RowID column. You can optionally define a primary key that also functions as a unique row identifier. A primary key allows the user to define a row identifier that is meaningful to the application. For example, a primary key might be an Employee ID column, a Social Security Number, a Patient Record ID column, or an inventory stock number. You can explicitly define a column or group of columns as the primary record identifier by using the PRIMARY KEY clause.
A primary key accepts only unique values and does not accept NULL. (The primary key index property is not automatically defined as Required; however, it effectively is required, since a NULL value cannot be filed or saved for a primary key column.) The collation type of a primary key is specified in the definition of the column itself.
Refer to the Constraints option of Catalog Details for ways to list the columns of a table that are defined as the primary key.
For more details, see Primary Key.
Primary Key As IDKEY
By default, the primary key is not the unique IDKEY index. In many cases this is preferable, because it enables you to update primary key values, set the collation type for the primary key, and so on. There are cases where it is preferable to define the primary key as the IDKEY index. Be aware that this imposes the IDKEY restrictions on the future use of the primary key.
If you add a primary key constraint to an existing column, the column may also be automatically defined as an IDKEY index. This depends on whether data is present and upon a configuration setting established in one of the following ways:
-
The SQL SET OPTION PKEY_IS_IDKEY statement.
-
The system-wide $SYSTEM.SQL.Util.SetOption()Opens in a new tab method configuration option DDLPKeyNotIDKey. To determine the current setting, call $SYSTEM.SQL.CurrentSettings()Opens in a new tab which displays Are primary keys created through DDL not ID keys; the default is 1.
-
Go to the Management Portal, select System Administration, Configuration, SQL and Object Settings, SQL. View the current setting of Define primary key as ID key for tables created via DDL.
-
If the check box is not selected (the default), the Primary Key does not become the IDKEY index in the class definition. Access to records using a primary key that is not the IDKEY is significantly less efficient; however, this type of primary key value can be modified.
-
If the check box is selected, when a Primary Key constraint is specified through DDL, it automatically becomes the IDKEY index in the class definition. With this option selected, data access is more efficient, but a primary key value, once set, can never be modified.
However, if an IDENTITY column is defined in the table, the primary key can never be defined as the IDKEY, even when you have used one of these configuration setting to define the primary key as the IDKEY.
InterSystems IRIS supports properties (columns) that are part of the IDKEY index to be SqlComputed. For example, a parent reference column. The property must be a triggered computed column. An IDKEY property defined as SqlComputed is only computed upon the initial save of a new Object or an INSERT operation. UPDATE computation is not supported, because columns that are part of the IDKEY index cannot be updated.
No Primary Key
In most cases, you should explicitly define a primary key. However, if a primary key is not designated, InterSystems IRIS attempts to use another column as the primary key for ODBC/JDBC projection, according to the following rules:
-
If there is an IDKEY index on a single column, report the IDKEY column as the SQLPrimaryKey column.
-
Else if the class is defined with SqlRowIdPrivate=0 (the default), report the RowID column as the SQLPrimaryKey column.
-
Else if there is an IDKEY index, report the IDKEY columns as the SQLPrimaryKey columns.
-
Else do not report an SQLPrimaryKey.
Multiple Primary Keys
You can only define one primary key. By default, InterSystems IRIS rejects an attempt to define a primary key when one already exists, or to define the same primary key twice, and issues an SQLCODE -307 error. The SQLCODE -307 error is issued even if the second definition of the primary key is identical to the first definition. To determine the current configuration, call $SYSTEM.SQL.CurrentSettings()Opens in a new tab, which displays an Allow create primary key through DDL when key exists setting. The default is 0 (No), which is the recommended configuration setting. If this option is set to 1 (Yes), InterSystems IRIS drops the existing primary key constraint and establishes the last-specified primary key as the table's primary key.
From the Management Portal, System Administration, Configuration, SQL and Object Settings, SQL you can set this option (and other similar create, alter, and drop options) system-wide by selecting the Ignore redundant DDL statements check box.
For example, the following CREATE TABLE statement:
CREATE TABLE MyTable (f1 VARCHAR(16),
CONSTRAINT MyTablePK PRIMARY KEY (f1))
creates the primary key (if none exists). A subsequent ALTER TABLE statement:
ALTER TABLE MyTable ADD CONSTRAINT MyTablePK PRIMARY KEY (f1)
generates an SQLCODE -307 error.
Defining a Foreign Key
A foreign key is a column that references another table; the value stored in the foreign key column is a value that uniquely identifies a record in the other table. The simplest form of this reference is shown in the following example, in which the foreign key explicitly references the primary key column CustID in the Customers table:
CREATE TABLE Orders (
OrderID INT UNIQUE NOT NULL,
OrderItem VARCHAR,
OrderQuantity INT,
CustomerNum INT,
CONSTRAINT OrdersPK PRIMARY KEY (OrderID),
CONSTRAINT CustomersFK FOREIGN KEY (CustomerNum) REFERENCES Customers (CustID))
Most commonly, a foreign key references the primary key column of the other table. However, a foreign key can reference a RowID (ID) or an IDENTITY column. In every case, the foreign key reference must exist in the referenced table and must be defined as unique; the referenced column cannot contain duplicate values or NULL.
In a foreign key definition, you can specify:
-
One column name: FOREIGN KEY (CustomerNum) REFERENCES Customers (CustID). The foreign key column (CustomerNum) and referenced column (CustID) may have different names (or the same name), but must have the same data type and column constraints.
-
A comma-separated list of column names: FOREIGN KEY (CustomerNum,SalespersonNum) REFERENCES Customers (CustID,SalespID). The foreign key columns and referenced columns must correspond in number of columns and in order listed.
-
An omitted column name: FOREIGN KEY (CustomerNum) REFERENCES Customers.
-
An explicit RowID column: FOREIGN KEY (CustomerNum) REFERENCES Customers (%ID). Synonymous with an omitted column name. If the class definition for the table contains SqlRowIdName you can specify this value as the explicit RowID.
If you define a foreign key and omit the referenced column name, the foreign key defaults as follows:
-
The primary key column defined for the specified table.
-
If the specified table does not have a defined primary key, the foreign key defaults to the IDENTITY column defined for the specified table.
-
If the specified table does not have either a defined primary key or a defined IDENTITY column, the foreign key defaults to the RowID. This occurs only if the specified table defines the RowID as public; the specified table definition can do this explicitly, either by specifying the %PUBLICROWID keyword, or through the corresponding class definition with SqlRowIdPrivate=0 (the default). If the specified table does not define the RowID as public, InterSystems IRIS issues an SQLCODE -315 error. You must omit the referenced column name when defining a foreign key on the RowID; attempting to explicitly specify ID as the referenced column name results in an SQLCODE -316 error.
If none of these defaults apply, InterSystems IRIS issues an SQLCODE -315 error.
Refer to the Constraints option of Catalog Details for ways to list the columns of a table that are defined as foreign key columns and the generated Constraint Name for a foreign key.
In a class definition, you can specify a Foreign Key that contains a column based on a parent table IDKEY property, as shown in the following example:
ForeignKey Claim(CheckWriterPost.Hmo,Id,Claim) References SQLUser.Claim.Claim(DBMSKeyIndex);
Because the parent column defined in a foreign key of a child has to be part of the IDKEY index of the parent class, the only referential action supported for foreign keys of this type is NO ACTION.
-
If a foreign key references a nonexistent table, InterSystems IRIS issues an SQLCODE -310 error, with additional information provided in %msg.
-
If a foreign key references a nonexistent column, InterSystems IRIS issues an SQLCODE -316 error, with additional information provided in %msg.
-
If a foreign key references a nonunique column, InterSystems IRIS issues an SQLCODE -314 error, with additional information provided in %msg.
If the foreign key column references a single column, the two columns must have the same data type and column data constraints.
In a parent/child relationship, there is no defined ordering of the children. Application code must not rely on any particular ordering.
You can define a foreign key constraint that references a class in a database that is mounted read-only. To define a FOREIGN KEY, the user must have REFERENCES privilege on the table being referenced or on the columns of the table being referenced. REFERENCES privilege is required if the CREATE TABLE is executed via Dynamic SQL or a database driver.
Sharded Tables and Foreign Keys
Foreign keys are supported for any combination of sharded and unsharded tables, including: key table sharded, fkey table unsharded; key table unsharded, fkey table sharded; and both key table and fkey table sharded. The key in the referenced table can be the shard key or another key. A foreign key can be a single column or multiple columns.
NO ACTION is the only referential action supported for sharded tables.
For more details, see Querying the Sharded Cluster.
Implicit Foreign Key
It is preferable to explicitly define all foreign keys. If there is an explicit foreign key defined, InterSystems IRIS reports this constraint and the implicit foreign key constraint is not defined.
However, it is possible to project implicit foreign keys to ODBC/JDBC and the Management Portal. These implicit foreign keys are reported as UPDATE and DELETE referential actions of NO ACTION. This implicit reference foreign key is not a true foreign key as there are no referential actions enforced. The name of this foreign key reported for the reference is "IMPLICIT_FKEY_REFERENCE__"_columnname. The reporting of this reference as a foreign key is provided for interoperability with third-party tools.
Bitmap Extent Index
When you create a table using CREATE TABLE, by default InterSystems IRIS automatically defines a bitmap extent index for the corresponding class. The SQL MapName of the bitmap extent index is %%DDLBEIndex:
Index DDLBEIndex [ Extent, SqlName = "%%DDLBEIndex", Type = bitmap ];
This bitmap extent index is not created in any of the following circumstances:
If, after creating a bitmap index, the CREATE BITMAPEXTENT INDEX command is run against a table where a bitmap extent index was automatically defined, the bitmap extent index previously defined is renamed to the name specified by the CREATE BITMAPEXTENT INDEX statement.
For DDL operations that automatically delete an existing bitmap extent index, refer to ALTER TABLE.
For more details, see Bitmap Extent Index.
Creating Named RowId Column Using IDENTITY Keyword
InterSystems SQL automatically creates a RowID column for each table, which contains a system-generated integer that serves as a unique record id. The optional IDENTITY keyword allows you to define a named column with the same properties as a RowID record id column. An IDENTITY column behaves as a single-column IDKEY index, whose value is a unique system-generated integer.
Defining an IDENTITY column prevents the defining of the Primary Key as the IDKEY.
Just as with any system-generated ID column, an IDENTITY column has the following characteristics:
-
You can only define one column per table as an IDENTITY column. Attempting to define more than one IDENTITY column for a table generates an SQLCODE -308 error.
-
The data type of an IDENTITY column must be an integer data type. If you do not specify a data type, its data type is automatically defined as BIGINT. You can specify any integer data type, such as INTEGER or SMALLINT; BIGINT is recommended to match the data type of RowID. Any specified column constraints, such as NOT NULL or UNIQUE are accepted but ignored.
-
Data values are system-generated. They consist of unique, nonzero, positive integers.
-
By default, IDENTITY column data values cannot be user-specified. By default, an INSERT statement does not, and cannot, specify an IDENTITY column value. Attempting to do so generates an SQLCODE -111 error. To determine whether an IDENTITY column value can be specified, call the $SYSTEM.SQL.Util.GetOption("IdentityInsert")Opens in a new tab method; the default is 0. To change this setting for the current process, call the $SYSTEM.SQL.Util.SetOption()Opens in a new tab method, as follows: SET status=$SYSTEM.SQL.Util.SetOption("IdentityInsert",1,.oldval). You can also specify %CLASSPARAMETER ALLOWIDENTITYINSERT=1 in the table definition. Specifying ALLOWIDENTITYINSERT=1 overrides any setting applied using SetOption("IdentityInsert"). For further details, refer to the INSERT statement.
-
IDENTITY column data values cannot be modified in an UPDATE statement. Attempting to do so generates an SQLCODE -107 error.
-
The system automatically projects a primary key on the IDENTITY column to ODBC and JDBC. If a CREATE TABLE or ALTER TABLE statement defines a primary key constraint or a unique constraint on an IDENTITY column, or on a set of columns including an IDENTITY column, the constraint definition is ignored and no corresponding primary key or unique index definition is created.
-
A SELECT * statement does return a table's IDENTITY column.
Following an INSERT, UPDATE, or DELETE operation, you can use the LAST_IDENTITY function to return the value of the IDENTITY column for the most-recently modified record. If no IDENTITY column is defined, LAST_IDENTITY returns the RowID value of the most recently modified record.
These SQL statements create a table with an IDENTITY column and insert a rows into that table, generating an IDENTITY column value for the created table:
CREATE TABLE Employee (
EmpNum INT NOT NULL,
MyID IDENTITY NOT NULL,
Name VARCHAR(30) NOT NULL,
CONSTRAINT EmployeePK PRIMARY KEY (EmpNum))
INSERT INTO Employee (EmpNum,Name)
SELECT ID,Name FROM SQLUser.Person WHERE Age >= '25'
In this case, the primary key, EmpNum, is taken from the ID column of another table. EmpNum values are unique integers, but because of the WHERE clause, this column might contain gaps in the sequence. The IDENTITY column, MyID, assigns a user-visible unique sequential integer to each record.
Sharded Table Restrictions
When defining a sharded table, keep these restrictions in mind:
-
A sharded table can only be used in a sharded environment; a non-sharded table can be used in a sharded or non-sharded environment. Not all tables are good candidates for sharding. Optimal performance in a sharded environment is generally achieved by using a combination of sharded tables (generally very large tables) and non-sharded tables. For more details, see Evaluating the Benefits of Sharding and Evaluate Existing Tables for Sharding.
-
You must define a table as a sharded table either using CREATE TABLE or a persistent class definition. You cannot use ALTER TABLE to add a shard key to an existing table.
-
A UNIQUE column constraint on a sharded table can have a significant negative impact on insert/update performance unless the shard key is a subset of the unique key. For more details, see Evaluate Unique Constraints in “Horizontally Scaling InterSystems IRIS for Data Volume with Sharding”.
-
Sharding a table that is involved in complex transactions requiring atomicity is not recommended.
-
A sharded table cannot contain a ROWVERSION data type or SERIAL (%Library.Counter) data type column.
-
A sharded table cannot specify the VERSIONPROPERTYOpens in a new tab class parameter.
-
To specify a shard key, the current namespace must be configured for sharding. If the current namespace is not configured for sharding, a CREATE TABLE that specifies a shard key fails with an SQLCODE -400 error. For details on configuring namespaces for sharding, see Configure the Shard Master Data Server.
-
The only referential action supported for sharded tables is NO ACTION. Any other referential action results in an SQLCODE -400 error.
-
A shard key column can only take %EXACT, %SQLSTRING, or %SQLUPPER collation, with no truncation. For more details, see Querying the Sharded Cluster.
For more details on sharding, see Create Target Sharded Tables.
Legacy Options
%EXTENTSIZE and %NUMROWS Keywords
The %EXTENTSIZE and %NUMROWS keywords provide an option to store the anticipated number of rows in the table being created. The InterSystems SQL query optimizer uses this value to estimate the cost of query plans. A table can define one or the other of these values but not both. For example:
CREATE TABLE Sample.DaysInAYear (
%EXTENTSIZE 366,
MonthName VARCHAR(24),
Day INTEGER)
Starting in 2021.2, the first time you query a table, InterSystems IRIS collects statistics such as the table size automatically. The SQL query optimizer uses these generated statistics to suggest appropriate query plan, making the %EXTENTSIZE and %NUMROWS keywords unnecessary. For more details on optimizing tables with table statisticss, see Table Statistics for Query Optimizer.
%FILE Keyword
The %FILE keyword provides an option to specify a file name that documents the table. For example:
CREATE TABLE Employee (
%FILE 'C:\SQL\employee_table_desc.txt',
EmpNum INT PRIMARY KEY,
NameLast VARCHAR(30) NOT NULL,
NameFirst VARCHAR(30) NOT NULL,
StartDate TIMESTAMP %Description 'MM/DD/YY')
This keyword is not recommended. Instead, document the table by using the %DESCRIPTION keyword.
Shard Key and %CLASSPARAMETER in Column List Parentheses
Old CREATE TABLE code might include the Shard Key definition and %CLASSPARAMETER clauses as comma-separated elements within the table element parentheses. For example: CREATE TABLE myTable(Name VARCHAR(50), DOB DATE, %CLASSPARAMETER USEEXTENTSET = 1). The preferred syntax is to specify these clauses after the closing parenthesis. For example: CREATE TABLE myTable(Name VARCHAR(50), DOB TIMESTAMP) WITH %CLASSPARAMETER USEEXTENTSET = 1. Specifying duplicates of these clauses generates an SQLCODE -327 error.
Options Supported for Compatibility Only
InterSystems SQL accepts the following CREATE TABLE options for parsing purposes only, to aid in the conversion of existing SQL code to InterSystems SQL. These options do not provide any actual functionality.
{ON | IN} dbspace-name LOCK MODE [ROW | PAGE] [CLUSTERED | NONCLUSTERED] WITH FILLFACTOR = literal MATCH [FULL | PARTIAL] CHARACTER SET identifier COLLATE identifier /* But COLLATE keyword is still used*/ NOT FOR REPLICATION
See Also
FeedbackOpens in a new tab