docs.intersystems.com
Home / InterSystems SQL Reference / SQL Commands / ALTER TABLE

InterSystems SQL Reference
ALTER TABLE
Next section
InterSystems: The power behind what matters   
Search:  


Modifies a table.
Synopsis
ALTER TABLE table alter-action

where alter-action is one of the following:
     ADD  [(] add-action {,add-action} [)] |
     DROP [COLUMN ] drop-column-action {,drop-column-action} |
     DROP drop-action |
     DELETE drop-action |
     ALTER [COLUMN] identifier alter-column-action |
     MODIFY modification-spec 

add-action ::= 
     [CONSTRAINT table]
     [(] FOREIGN KEY (identifier-commalist) 
          REFERENCES table (identifier-commalist)
          [referential-action] [)]
     |
     [(] UNIQUE (identifier-commalist)  [)] 
     |
     [(] PRIMARY KEY (identifier-commalist) [)] 
     | 
     DEFAULT [(] default-spec [)] FOR identifier
     |
     [COLUMN] [(] identifier datatype  [sqlcollation] 
           [%DESCRIPTION literal]
           [DEFAULT [(] default-spec [)] ]
           [ON UPDATE update-spec ]
           [UNIQUE] [NOT NULL]
           [REFERENCES table (identifier-commalist) ]
           [)]

drop-column-action ::= 
       [COLUMN] identifier [RESTRICT | CASCADE] [%DELDATA | %NODELDATA] 

drop-action ::= 
     FOREIGN KEY identifier |
     PRIMARY KEY |
     CONSTRAINT identifier |

alter-column-action ::= 
     datatype | 
     [SET] DEFAULT [(]default-spec[)]  |  DROP DEFAULT | 
     NULL |  NOT NULL | 
     COLLATE sqlcollation

modification-spec ::=
     identifier [datatype] 
          [DEFAULT [(]default-spec[)]]
          [CONSTRAINT identifier] [NULL] [NOT NULL]

sqlcollation ::=
     { %EXACT | %MINUS | %MVR | %PLUS | %SPACE |   
        %SQLSTRING [(maxlen)] | %SQLUPPER [(maxlen)] |
        %TRUNCATE[(maxlen)]  }
Arguments
table The name of the table to be altered. The table name can be qualified (schema.table), or unqualified (table). An unqualified table name takes the system-wide default schema name. Schema search path values are not used.
identifier The name of the column to be modified. For further details on valid identifiers, see the “Identifiers” chapter of Using InterSystems SQL.
identifier-commalist The name of a column or a comma-separated list of columns. An identifier-commalist must be enclosed in parentheses, even when only a single column is specified. For further details on valid identifiers, see the “Identifiers” chapter of Using InterSystems SQL.
datatype A valid InterSystems SQL data type. For a list of valid data types, see the SQL reference material at the end of this manual.
default-spec A default data value automatically supplied for this field, if not overridden by a user-supplied data value. Allowed values are: a literal value; one of the following keyword options (NULL, USER, CURRENT_USER, SESSION_USER, SYSTEM_USER, CURRENT_DATE, CURRENT_TIME, and CURRENT_TIMESTAMP); or an OBJECTSCRIPT expression. Do not use the SQL zero-length string as a default value. For further details, see CREATE TABLE.
COLLATE sqlcollation Optional — Specify one of the following SQL collation types: %EXACT, %MINUS, %PLUS, %SPACE, %SQLSTRING, %SQLUPPER, %TRUNCATE, or %MVR. 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. The percent sign (%) prefix to these collation parameter keywords is optional. The COLLATE keyword is optional. For further details refer to Table Field/Property Definition Collation in the “Collation” chapter of Using InterSystems SQL.
Description
An ALTER TABLE statement modifies a table definition; it can add elements, remove elements, or modify existing elements. You can only perform one type of operation in each ALTER TABLE statement.
The ALTER TABLE DROP statement and the ALTER TABLE DELETE statement are synonyms.
To determine if a specified table exists in the current namespace, use the $SYSTEM.SQL.TableExists() method.
Privileges and Locking
The ALTER TABLE command is a privileged operation. Prior to using ALTER TABLE it is necessary for your process to have either %ALTER_TABLE administrative privilege or an %ALTER object privilege for the specified table. Failing to do so results in an SQLCODE -99 error (Privilege Violation). You can determine if the current user has %ALTER privilege by invoking the %CHECKPRIV command. You can determine if a specified user has %ALTER privilege by invoking the $SYSTEM.SQL.CheckPriv() method. You can use the GRANT command to assign %ALTER_TABLE or %ALTER privileges, if you hold appropriate granting privileges. In embedded SQL, you can use the $SYSTEM.Security.Login() method to log in as a user with appropriate privileges:
   DO $SYSTEM.Security.Login("_SYSTEM","SYS")
   &sql(      )
You must have the %Service_Login:Use privilege to invoke the $SYSTEM.Security.Login method. For further information, refer to %SYSTEM.Security in the InterSystems Class Reference.
The ALTER TABLE statement acquires a table-level lock on table. This prevents other processes from modifying the table’s data. This lock is automatically released at the conclusion of the ALTER TABLE operation. When ALTER TABLE locks the corresponding class definition, it uses the SQL Lock Timeout setting for the current process.
ADD COLUMN Restrictions
ALTER TABLE can add a single column, or can add a comma-separated list of columns.
If you attempt to add a field to a table through an ALTER TABLE tablename ADD COLUMN statement:
To change this default NOT NULL constraint behaviors, refer to the COMPILEMODE=NOCHECK option of the SET OPTION command.
If you specify an ordinary data field named “ID” and the RowID field is already named “ID” (the default), the ADD COLUMN operation succeeds. ALTER TABLE adds the ID data column, and renames the RowId column as “ID1” to avoid duplicate names.
Adding an Integer Counter
If you attempt to add an integer counter field to a table through an ALTER TABLE tablename ADD COLUMN statement:
ALTER COLUMN Restriction
You cannot change the data type of a column that contains data if this change would result in stream data being typed as non-stream data or non-stream data being typed as stream data. Attempting to do so results in an SQLCODE -374 error. If there is no existing data, this type of datatype change is permitted.
If you change the collation type for a column that contains data, you must rebuild all indices for that column.
DROP COLUMN Restrictions
DROP COLUMN can delete multiple column definitions, specified as a comma-separated list. Each listed column name must be followed by its RESTRICT or CASCADE (if unspecified, the default is RESTRICT) and %DELDATA or %NODELDATE (if unspecified, the default is %NODELDATA) options.
By default, deleting a column definition does not delete any data that has been stored in that column from the data map. To delete both the column definition and the data, specify the %DELDATA option.
Deleting a column definition does not delete the corresponding column-level privileges. For example, the privilege granted to a user to insert, update, or delete data on that column. This has the following consequences:
For these reasons, it is generally recommended that you use the REVOKE command to revoke column-level privileges from a column before deleting the column definition.
RESTRICT keyword (or no keyword): You cannot drop a column if that column appears in an index, or is defined in a foreign key constraint or other unique constraint. Attempting a DROP COLUMN for that column fails with an SQLCODE -322 error. RESTRICT is the default. See DROP INDEX.
CASCADE keyword: If the column appears in an index, the index will be deleted. There may be multiple indices. If the column appears in a foreign key, the foreign key will be deleted. There may be multiple foreign keys.
You cannot drop a column if that column is used in COMPUTECODE or in a COMPUTEONCHANGE clause. Attempting to do so results in an SQLCODE -400 error.
ADD PRIMARY KEY Restrictions
You cannot add a primary key constraint to an existing field if that field contains non-unique data or permits NULL values.
If you add a primary key constraint to an existing field, the field 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:
If CREATE TABLE defined a bitmap extent index and later you use ALTER TABLE to add a primary key that is also the IDKey, the system automatically drops the bitmap extent index.
ADD PRIMARY KEY When Already Exists
What happens when you try to add a primary key to a table that already has a defined primary key is configuration-dependent. By default, InterSystems IRIS rejects an attempt to define a primary key when one already exists and issues an SQLCODE -307 error. You can set this behavior system-wide using the $SYSTEM.SQL.SetDDLNo307() method call. To determine the current setting, call $SYSTEM.SQL.CurrentSettings(), which displays a Suppress SQLCODE=-307 Errors setting.
The default is “No” (0). This is the recommended setting for this option.
If this option is set to “Yes” (1), an ALTER TABLE ADD PRIMARY KEY causes InterSystems IRIS to remove the primary key index from the class definition, and then recreates this index using the specified primary key field(s).
However, even if this option is set to allow the creation of a primary key when one already exists, you cannot recreate a primary key index if it is also the IDKEY index and the table contains data. Attempting to do so generates an SQLCODE -307 error.
ADD FOREIGN KEY Restrictions
By default, you cannot have two foreign keys with the same name. Attempting to do so generates an SQLCODE -311 error. This option is configurable system-wide using the $SYSTEM.SQL.SetDDLNo311() method call. To determine the current setting, call $SYSTEM.SQL.CurrentSettings(), which displays a Suppress SQLCODE=-311 Errors setting.
The default is “No” (0). This is the recommended setting for this option. When “Yes” (1), you can add a foreign key through DDL even if one with the same name already exists. When “No” (0), this action generates an SQLCODE -311 error.
Your table definition should not have two foreign keys with different names that reference the same identifier-commalist field(s) and perform contradictory referential actions. In accordance with the ANSI standard, InterSystems SQL does not issue an error if you define two foreign keys that perform contradictory referential actions on the same field (for example, ON DELETE CASCADE and ON DELETE SET NULL). Instead, InterSystems SQL issues an error when a DELETE or UPDATE operation encounters these contradictory foreign key definitions.
An ADD FOREIGN KEY that specifies a non-existent foreign key field generates an SQLCODE -31 error.
An ADD FOREIGN KEY that references a non-existent parent key table generates an SQLCODE -310 error. An ADD FOREIGN KEY that references a non-existent field in an existing parent key table generates an SQLCODE -316 error. If you do not specify a parent key field, it defaults to the ID field.
Before issuing an ADD 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 ALTER TABLE is executed via Dynamic SQL or xDBC.
An ADD FOREIGN KEY that references a field (or combination of fields) that can take non-unique values generates an SQLCODE -314 error, with additional details available through %msg.
NO ACTION is the only referential action supported for sharded tables.
An ADD FOREIGN KEY is constrained when data already exists in the table. To change this default constraint behavior, refer to the COMPILEMODE=NOCHECK option of the SET OPTION command.
When you define an ADD FOREIGN KEY constraint for a single field and the foreign key references the idkey of the referenced table, InterSystems IRIS converts the property in the foreign key into a reference property. This conversion is subject to the following restrictions:
For further information on foreign keys, refer to the CREATE TABLE command, and to the Using Foreign Keys chapter in Using InterSystems SQL.
DROP CONSTRAINT Restrictions
By default, you cannot drop a unique or primary key constraint if it is referenced by a foreign key constraint. Attempting to do so results in an SQLCODE -317 error. To change this default foreign key constraint behavior, refer to the COMPILEMODE=NOCHECK option of the SET OPTION command.
The effects of dropping a primary key constraint depend on the setting of the Are Primary Keys also ID Keys setting (as described above):
DROP CONSTRAINT When Non-Existent
What happens when you try to drop a field constraint on a field that does not have that constraint depends on a configuration setting. You can configure this behaviior system-wide using the $SYSTEM.SQL.SetDDLNo315() method call. To determine the current setting, call $SYSTEM.SQL.CurrentSettings(), which displays a Suppress SQLCODE=-315 Errors setting.
The default is “No” (0). By default, InterSystems IRIS rejects an attempt to drop a constraint that does not exist and issues an SQLCODE -315 error. However, if this option is set to “Yes” (1), an ALTER TABLE DROP CONSTRAINT causes InterSystems IRIS to perform no operation and not issue an error message.
Examples
The following examples uses Embedded SQL programs to create a table, populate two rows, and then alter the table definition.
To demonstrate this, please run the first two Embedded SQL programs in the order shown. (It is necessary to use two embedded SQL programs here because embedded SQL cannot compile an INSERT statement unless the referenced table already exists.)
  DO $SYSTEM.Security.Login("_SYSTEM","SYS")
  &sql(DROP TABLE SQLUser.MyStudents)
      IF SQLCODE=0 { WRITE !,"Deleted table" }
      ELSE { WRITE "DROP TABLE error SQLCODE=",SQLCODE }
  &sql(CREATE TABLE SQLUser.MyStudents (
     FirstName VARCHAR(35) NOT NULL,
     LastName VARCHAR(35) NOT NULL)
     )
     IF SQLCODE=0 { WRITE !,"Created table" }
     ELSE { WRITE "CREATE TABLE error SQLCODE=",SQLCODE }
  DO $SYSTEM.Security.Login("_SYSTEM","SYS")
  NEW SQLCODE,%msg
  &sql(INSERT INTO SQLUser.MyStudents (FirstName, LastName) 
    VALUES ('David','Vanderbilt'))
  IF SQLCODE=0 { WRITE !,"Inserted data in table"}
      ELSE { WRITE !,"SQLCODE=",SQLCODE,": ",%msg }
  &sql(INSERT INTO SQLUser.MyStudents (FirstName, LastName)
    VALUES ('Mary','Smith'))
  IF SQLCODE=0 { WRITE !,"Inserted data in table"}
     ELSE { WRITE !,"SQLCODE=",SQLCODE,": ",%msg }
The following example uses ALTER TABLE to add the ColorPreference column. Because the column definition specifies a default, the system populates ColorPreference with the value 'Blue' for the two existing rows of the table:
   NEW SQLCODE,%msg
  &sql(ALTER TABLE SQLUser.MyStudents 
    ADD COLUMN ColorPreference VARCHAR(16) NOT NULL DEFAULT 'Blue')
  IF SQLCODE=0 {
    WRITE !,"Added a column",! }
  ELSEIF SQLCODE=-306 {
    WRITE !,"SQLCODE=",SQLCODE,": ",%msg }
  ELSE { WRITE "SQLCODE error=",SQLCODE }
The following example uses ALTER TABLE to add two computed columns: FLName and LFName. For existing rows these columns have no value. For any subsequently inserted row a value is computed for each of these columns:
  NEW SQLCODE,%msg
  &sql(ALTER TABLE SQLUser.MyStudents 
    ADD COLUMN FLName VARCHAR(71) COMPUTECODE { SET {FLName}={FirstName}_" "_{LastName}} 
               COMPUTEONCHANGE (FirstName,LastName),
        COLUMN LFName VARCHAR(71) COMPUTECODE { SET {LFName}={LastName}_ "," _{FirstName}} 
               COMPUTEONCHANGE (FirstName,LastName) )
  IF SQLCODE=0 {
    WRITE !,"Added two computed columns",! }
  ELSE { WRITE "SQLCODE error=",SQLCODE }
See Also


Next section
Send us comments on this page
View this book as PDF   |  Download all PDFs
Copyright © 1997-2019 InterSystems Corporation, Cambridge, MA
Content Date/Time: 2019-07-17 06:47:30