SQL References

ALTER AUDIT POLICY

Function

It adds an auditing target to an audit policy object, or drops an auditing target from an audit policy object.

Syntax

<alter audit policy statement> ::= 
    ALTER AUDIT POLICY policy_name
    { <add_audit_option> | <drop_audit_option> }
    ;

<add_audit_option> ::=
    ADD { <privilege_audit_clause> |  <action_audit_clause> | <privilege_audit_clause> <action_audit_clause> }

<drop_audit_option> ::=
    DROP { <privilege_audit_clause> |  <action_audit_clause> | <privilege_audit_clause> <action_audit_clause> }


<privilege_audit_clause> ::=
    PRIVILEGES <database_privilege> [, ...]

<action_audit_clause> ::=
    ACTIONS { <object_action_audit> | <system_action_audit> } [, ...]

<object_action_audit> ::=
      ALL ON [schema_name.]object_name
    | <object_action> ON [schema_name.]object_name

<system_action_audit> ::=
      ALL
    | <system_action>

Invocation and Access Rules

AUDIT SYSTEM ON DATABASE privilege is required to perform <alter audit policy statement>.

Syntax Rules and Parameters

policy_name

It is the name of an audit policy object to be altered.

<add_audit_option>

It adds an auditing target to an audit policy.

<drop_audit_option>

It drops an auditing target from an audit policy.

<privilege_audit_clause>

For more information, refer to CREATE AUDIT POLICY.

<action_audit_clause>

For more information, refer to CREATE AUDIT POLICY.

Description

It can alter an audit policy which is already activated, and it does not effect the existing session but it effects only the newly created session.

When dropping ALL option as follows, not all actions are dropped, but only the corresponding ALL option is dropped.

CREATE AUDIT POLICY p1
       ACTIONS ALL ON u1.t1,
               SELECT ON u1.t1;

ALTER AUDIT POLICY p1 DROP
      ACTIONS ALL ON u1.t1;

Examples

The following is an example of adding a new audit option to an audit policy.

ALTER AUDIT POLICY policy_dml
      ADD ACTIONS SELECT ON u1.t1;

The following is an example of dropping an audit option from an audit policy.

ALTER AUDIT POLICY policy_dml
      DROP ACTIONS SELECT ON u1.t1;

Compatibility

The SQL standard does not have the audit policy.

For More Information

Refer to the followings.

ALTER CLUSTER GROUP name ADD MEMBER

Function

It adds a cluster member to a cluster group.

Syntax

<alter cluster group add member statement> ::=
    ALTER CLUSTER GROUP group_name ADD
        <cluster member definition> [, ...]
    ;

<cluster member definition> ::=
    CLUSTER MEMBER member_name <connection attribute> [<member position>]

<connection attribute> ::=
    HOST 'address' PORT port_no

<member position> ::=
    POSITION DEFAULT
  | POSITION MAX
  | POSITION number

Invocation and Access Rules

It can be performed in a cluster system.
ADMINISTRATION ON DATABASE privilege is required to perform <alter cluster group add member statement>.

Syntax Rules and Parameters

group_name

It is the cluster group name.

<cluster member definition>

It defines a cluster member to be included in a cluster group.
A cluster group may include maximum 32 cluster members.

member_name

It is the name of a cluster member.
The cluster member name should be as same as the member name which was defined when the database of that cluster member was created.
There should not be the same cluster group, nor the same cluster member.
The length of the name should be shorter than 128 bytes.

The start-up phase for the cluster member should be GLOBAL OPEN.

<connection attribute>

It defines the connection information for the communication between the cluster members.
<connection attribute> should be as same as the HOST and PORT which were defined when the database of that cluster member was created.
The combination of HOST and PORT should be unique in the cluster system.

<member position>

It assigns the position number of the cluster member.

The member_position information of the cluster member can be retrieved through DBA_CLUSTER view.

SELECT member_name, member_id, member_position FROM dba_cluster;

If the following position numbers are being used,

The following values are assigned according to each option.

Description

<alter cluster group add member statement> statement does not rebalance shards in the tables.
The following statement should be performed to rebalance shards on the added cluster member.

Examples

The following is an example of adding two cluster members to a cluster group.

gSQL>
ALTER CLUSTER GROUP g1 ADD
    CLUSTER MEMBER g1n3 HOST '192.168.0.13' PORT 10130,
    CLUSTER MEMBER g1n4 HOST '192.168.0.14' PORT 10140
;

Cluster Group altered.

The following is an example of designating the empty member position as a cluster member position.

ALTER CLUSTER GROUP g2 ADD
    CLUSTER MEMBER g2n1 HOST '192.168.0.21' PORT 10210 POSITION 4
;

Compatibility

The SQL standard does not define the concepts of the cluster.

For More Information

Refer to the followings.

ALTER CLUSTER GROUP name OFFLINE MEMBER

Function

It sets a cluster member of the cluster group to offline.

Syntax

<alter cluster group offline member statement> ::=
    ALTER CLUSTER GROUP group_name OFFLINE
        <cluster member definition>
    ;

<cluster member definition> ::=
    CLUSTER MEMBER member_name
    ;

Invocation and Access Rules

It can be performed in a cluster system.
ADMINISTRATION ON DATABASE privilege is required to perform <alter cluster group offline member statement>.

Syntax Rules and Parameters

group_name

It is the cluster group name.

<cluster member definition>

It defines a cluster member to be included in a cluster group.
A cluster group may include maximum 32 cluster members.

member_name

It is the name of a cluster member.
The cluster member should be included in the cluster group of group_name.
The cluster member should be inactive.

Description

<alter cluster group offline member statement> statement does not rebalance shards in the tables.

Examples

The following is an example of setting a specific cluster member to offline.

gSQL>

ALTER CLUSTER GROUP g1 OFFLINE
    CLUSTER MEMBER g1n3
;
Cluster Group altered.

Compatibility

The SQL standard does not define the concepts of the cluster.

For More Information

Refer to the followings.

ALTER CLUSTER LOCATION

Function

It alters a cluster location information.

Syntax

<alter cluster location statement> ::=
    ALTER CLUSTER LOCATION member_name 
    <cluster connection attribute>
    ;

<cluster connection attribute> ::
       HOST 'address' PORT port_no

Invocation and Access Rules

It can be performed in a cluster system.
ADMINISTRATION ON DATABASE privilege is required to perform <alter cluster location statement>.

Syntax Rules and Parameters

member_name

It is the name of a cluster member.
The same cluster member name should exist in the registered cluster location information.
The length of the name should be shorter than 128 bytes.

<cluster connection attribute>

It defines the connection information for the communication between the cluster members.
The combination of HOST and PORT should be unique in the cluster system.

Description

If the connection information of the cluster location is altered, the cluster member does not need to be dropped or recreated, but the connection information can be altered by using ALTER CLUSTER LOCATION.

Examples

gSQL> 
ALTER CLUSTER LOCATION g1n2
    HOST '192.168.0.12' PORT 10120
;

altered.

Compatibility

The SQL standard does not define the concepts of the cluster.

For More Information

Refer to the followings.

ALTER DATABASE ADD LOGFILE

Function

It adds log file groups or log file members to the database.

Syntax

<alter database add logfile statement> ::=
      <add logfile member statement> 
    | <add logfile group statement>
    ;

<add logfile member statement> ::=
    ALTER DATABASE ADD LOGFILE MEMBER <add logfile clause> [, ...] TO 
        <group clause>

<add logfile group statement> ::=
    ALTER DATABASE ADD LOGFILE <group clause> ( 'logfile_name' [, ...] ) 
        <size clause> [ REUSE ]

<group clause> ::=
    GROUP integer

<add logfile clause> ::=
    'logfile_name' [ REUSE ]

<size clause> ::=
    integer [ M | G ]

Invocation and Access Rules

ALTER DATABASE ON DATABASE privilege is required to perform <alter database add logfile statement>.

Syntax Rules and Parameters

<alter database add logfile statement>

The database should be in MOUNT phase.

<add logfile member statement>

The log member is added to an existing log file group.

<add logfile group statement>

It adds a new log file group.

Description

It is recommended to back up the control file just in case for the file damage because the newly added log file groups and log members are stored in the control file.

Examples

The following is an example of adding two log file members to an existing log file group 3.

ALTER DATABASE ADD LOGFILE MEMBER 'logfile1.log', 'logfile2.log' TO GROUP 3;

The following is an example of adding a new log file group 4 to database. The size of log file group 4 is 100 M, and the log file name is 'logfile1.log'.

ALTER DATABASE ADD LOGFILE GROUP 4 ( 'logfile1.log' ) SIZE 100M;

When adding a log group, a single log file should be used, and multiple log files can be added to an existing group as a member.

Compatibility

The SQL standard does not define ALTER DATABASE statement.

For More Information

Refer to the followings.

ALTER DATABASE ARCHIVELOG

Function

It alters an archive setting of the online log file in the database.

Syntax

<alter database archivelog statement> ::=
    ALTER DATABASE { ARCHIVELOG | NOARCHIVELOG }
    ;

Invocation and Access Rules

ALTER DATABASE ON DATABASE privilege is required to perform <alter database archivelog statement>.

Syntax Rules and Parameters

<alter database archivelog statement>

Description

For the database backup and the media recovery using the backup, the system should be operated in ARCHIVELOG mode.

Example

The following is an example of how to set up a database to archive mode.

ALTER DATABASE ARCHIVELOG;

Compatibility

The SQL standard does not define ALTER DATABASE statement.

For More Information

Refer to the followings.

ALTER DATABASE BACKUP

Function

The backup state is set to ACTIVE or INACTIVE to perform a full backup of the database. Then, the incremental database backup and control file backup are performed.

Syntax

<alter database backup statement> ::=
      <database begin backup statement>
    | <database end backup statement>
    | <database incremental backup statement>
    | <database controlfile backup statement>
    ;

<database begin backup statement> ::=
    ALTER DATABASE BEGIN BACKUP [ AT <domain name> ]
    ;

<database end backup statement> ::=
    ALTER DATABASE END BACKUP [ AT <domain name> ]
    ;

<database incremental backup statement> ::=
    ALTER DATABASE BACKUP INCREMENTAL
        <incremental backup option> [ AT <domain name> ]    ;

<incremental backup option> ::=
      LEVEL integer [ CUMULATIVE | DIFFERENTIAL ]

<database controlfile backup statement> ::=
    ALTER DATABASE BACKUP CONTROLFILE TO 'target_name'
        [ AT <domain name> ]    ;

Invocation and Access Rules

ALTER DATABASE ON DATABASE privilege is required to perform <alter database backup statement>.

Syntax Rules and Parameters

<database begin backup clause>

The database is set to the state which the full backup is available.

<database end backup clause>

The database is set to the state which the full backup is not available.

<database incremental backup statement>

<incremental backup option>

<database controlfile backup statement>

The maximum length of the 'target_name' managed by GOLDILOCKS is 1024 bytes. However, the maximum lengths of the file name varies depending on the OS, so the actual length of 'target_name' which is available to be created can be shorter than 1024 bytes.

<domain name>

It is a name of a member or a group for which the statement is performed.
If it is omitted, it is performed for all groups.

Description

It backs up data files and control files in the database. A full backup of the database begins with BEGIN BACKUP, and copies the datafiles using OS file copy, then ends with END BACKUP. The incremental backup file is created in the path set by the BACKUP_DIR 1 property using a single statement.

Examples

The following is an example of setting the entire backup state to ACTIVE.

ALTER SYSTEM BEGIN BACkUP;

The following is an example of setting the entire backup state to INACTIVE.

ALTER SYSTEM END BACkUP;

The following is an example to create the incremental backup of LEVEL 1 by using DIFFERENTIAL.

ALTER DATABASE BACKUP INCREMENTAL LEVEL 1 DIFFERENTIAL;

The following is an example to create the 'controlfile.bak' backup file for the control file. If the absolute path is not included, a backup file is created in the path set by the LOG_DIR property.

ALTER DATABASE BACKUP CONTROLFILE TO 'controlfile.bak';

Compatibility

The SQL standard does not define ALTER DATABASE statement.

For More Information

Refer to the followings.

ALTER DATABASE CLEAR AUDIT TRAIL

Function

It purges audit records which are accumulated when applying an audit policy.

Syntax

<clear audit trail statement> ::= 
    ALTER DATABASE CLEAR AUDIT TRAIL
;

Invocation and Access Rules

AUDIT SYSTEM ON DATABASE privilege is required to perform <clear audit trail statement>.

Description

If an audit policy is activated, an audit trails is getting longer as time goes by.
Tables configuring an audit trail are stored in MEM_AUX_TBS tablespace, and a user should be cautious not to let the audit trail keep increasing.

Storing Audit Trail

A user should purge an audit trail after storing it according to the following procedure to store an audit trail when it is necessary.

CREATE TABLE backup_audit_trail AS SELECT * FROM AUDIT_TRAIL;
COMMIT;
INSERT INTO backup_audit_trail SELECT * FROM AUDIT_TRAIL;
COMMIT;
ALTER DATABASE CLEAR AUDIT TRAIL;

Examples

Purge an audit trail by using the following statement.

ALTER DATABASE CLEAR AUDIT TRAIL;

Compatibility

The SQL standard does not have the audit policy.

For More Information

Refer to the followings.

ALTER DATABASE CLEAR PASSWORD HISTORY

Function

It deletes the user's password change history which is accumulated due by applying the profile.

Syntax

<clear password history statement> ::= 
    ALTER DATABASE CLEAR PASSWORD HISTORY
    ;

Invocation and Access Rules

ALTER DATABASE ON DATABASE privilege is required to perform <clear password history statement>.

Description

When a profile is applied to a user, the user's password change history is accumulated according to the PASSWORD_REUSE_MAX and PASSWORD_REUSE_TIME policies.
Managing the change history

PASSWORD_REUSE_MAX

PASSWORD_REUSE_TIME

Managing the change history

value

value

It manages only the change history within the value range, and the change history out of the value range is automatically deleted.

value

UNLIMITED

It accumulates all change history and it does not delete any change history because all change history should be checked.

UNLIMITED

value

It accumulates all change history and it does not delete any change history because all change history should be checked.

UNLIMITED

UNLIMITED

It does not manage the change history because the change history is not checked.

<Clear password history statement> deletes the accumulated user's password change history.

Examples

The following is an example of executing <clear password history statement> statement.
gSQL> ALTER DATABASE CLEAR PASSWORD HISTORY;

Database altered.

gSQL> COMMIT;

Commit complete.

Compatibility

The SQL standard does not define ALTER DATABASE statement.

For More Information

Refer to the followings.

ALTER DATABASE DATAFILE AUTOEXTEND

Function

It alters the property to automatically extend disk tablespace data file. If the property is ON, then the size to be extended and the maximum size of the data file also can be altered.

Syntax

<alter database datafile autoextend statement> ::= 
    ALTER DATABASE DATAFILE datafile_name <autoextend clause>
        [ AT <domain name> ]
    ;

<autoextend clause>
    AUTOEXTEND { ON [ <next size clause> ] [ <max size clause> ] | OFF }

<next size clause>
    NEXT <size clause>

<max size clause>
    MAXSIZE { <size clause> | UNLIMITED }

Invocation and Access Rules

ALTER DATABASE ON DATABASE privilege is required to perform <alter database datafile autoextend statement>.

The datafile automatic expand property can alter the property of disk tablespace only.

datafile_name

It specifies the name of the data file to be altered.

<autoextend clause>

It sets the automatic expand property to ON or OFF. If it is set to ON, then it can specify the automatic expanded size and the maximum size of the data file.

<next size clause>

It specifies the size to be extended when the data file in use does not have available space.

<max size clause>

It specifies the maximum expanded size of the data file.

Description

Refer to the syntax rules of each statement.

Examples

The following is an example of altering the automatic expand property of the datafile, the automatic expanded size, and datafile size.

gSQL> ALTER DATABASE DATAFILE 'DISK_TBS.dbf' AUTOEXTEND OFF;

Database altered.

gSQL> ALTER DATABASE DATAFILE 'DISK_TBS.dbf' AUTOEXTEND ON;

Database altered.

gSQL> ALTER DATABASE DATAFILE 'DISK_TBS.dbf' AUTOEXTEND ON NEXT 20M;

Database altered.

gSQL> ALTER DATABASE DATAFILE 'DISK_TBS.dbf' AUTOEXTEND ON MAXSIZE 1G;

Database altered.

gSQL> ALTER DATABASE DATAFILE 'DISK_TBS.dbf' AUTOEXTEND ON 20M MAXSIZE 1G;

Database altered.

Compatibility

The SQL standard does not define the concepts of the datafile.

For More Information

Refer to CREATE DISK DATA TABLESPACE.

ALTER DATABASE DELETE BACKUP

Function

It deletes the backup file and the backup information of incremental backup. It can delete all incremental backup of the database or no longer usable obsolete backup.

Syntax

<alter database delete backup statement> ::=
    ALTER DATABASE DELETE <delete backup list option> 
        BACKUP LIST [ <including backup file option> ]
    ;

<delete backup list option> ::=
      OBSOLETE
    | ALL

<including backup file option> ::=
    INCLUDING BACKUP FILES

Invocation and Access Rules

ALTER DATABASE ON DATABASE privilege is required to perform <alter database delete backup statement>.

Syntax Rules and Parameters

<alter database delete backup statement>

The database should be in MOUNT or OPEN phase.

<delete backup list option>

It selects the backups to be deleted among the existing incremental backups.

<including backup file option>

Description

Deletion of the OBSOLETE incremental backup deletes the incremental backup of which is before the most recent LEVEL 0 database backup. When non-LEVEL 0 incremental backup is performed, it is not deleted even if it includes the previously performed incremental backup. It is because it can be used when performing the incomplete recovery by using the incremental backups.

Be cautious of deleting the backup file together when an incremental backup is deleted. It can not be recovered even by using the control file which has incremental backup information.

Example

The following is an example to delete the backup information and backup files of all existing incremental backups.

ALTER DATABASE DELETE ALL BACKUP LIST INCLUING BACKUP FILES;

Compatibility

The SQL standard does not define ALTER DATABASE statement.

For More Information

Refer to the followings.

ALTER DATABASE DROP INACTIVE CLUSTER MEMBERS

Function

It drops the entire inactive cluster member.

Syntax

<alter database drop inactive members statement> ::=
    ALTER DATABASE DROP INACTIVE CLUSTER MEMBERS
    ;

Invocation and Access Rules

It can be performed in a cluster system.
ADMINISTRATION ON DATABASE privilege is required to perform <alter database drop inactive cluster members statement>.

Description

It drops the entire inactive cluster member.
The inactive state of a cluster member means that it is not connected to the cluster system, and it occurs in the following cases.

However, if the table shard is lost while dropping the cluster member, then an inactive cluster member can not be dropped.

It is recommended to use <alter database drop inactive members statement> when an inactive cluster member can not be included in the cluster system any more.

Examples

The following is an example of executing <alter database drop inactive members statement>.

gSQL> ALTER DATABASE DROP INACTIVE CLUSTER MEMBERS;

Database altered.

Compatibility

The SQL standard does not define the concepts of the cluster.

For More Information

Refer to ALTER SYSTEM JOIN DATABASE.

ALTER DATABASE DROP LOGFILE

Function

It drops a log file group or a member which exists in the database.

Syntax

<alter database drop logfile statement> ::=
      <drop logfile group statement>
    | <drop logfile member statement>
    ;

<drop logfile group statement> ::=
    ALTER DATABASE DROP LOGFILE <group clause>

<group clause> ::=
    GROUP integer

<drop logfile member statement> ::=
    ALTER DATABASE DROP LOGFILE MEMBER <logfile_list>

<logfile_list> ::=
      'logfile_name'
    | <logfile_list> , 'logfile_name'

Invocation and Access Rules

ALTER DATABASE ON DATABASE privilege is required to perform <alter database drop logfile statement>.

Syntax Rules and Parameters

<alter database drop logfile statement>

The database should be in MOUNT phase.
An error occurs when the log file to be deleted is in CURRENT or ACTIVE stage.
At least four log file groups should be remained after dropping.

<drop logfile group statement>

It drops the existing log file group.

<drop logfile member statement>

It drops the existing log file members.

Description

For more information, refer to the rules for each syntax.

Examples

The following is an example of dropping the existing log file GROUP 3.

ALTER DATABASE DROP LOGFILE GROUP 3;

The following is an example of dropping logfile1.log and logfile2.log from the existing logfile GROUP 3.

ALTER DATABASE DROP LOGFILE MEMBER 'logfile1.log', 'logfile2.log';

Compatibility

The SQL standard does not define ALTER DATABASE statement.

For More Information

Refer to the respective syntax rules, and the followings.

ALTER DATABASE MOVE SHARD

Function

It rebalances shard of all tables in a specific cluster group to another cluster group.

Syntax

<alter database move shard statement> ::=
    ALTER DATABASE MOVE SHARD FROM CLUSTER GROUP src_cluster_group
        TO CLUSTER GROUP dest_cluster_group [ ONLINE | OFFLINE ];

Invocation and Access Rules

It can be performed in a cluster system.
ALTER DATABASE ON DATABASE privilege is required to perform <alter database move shard statement>.

Syntax Rules and Parameters

src_cluster_group

It is a cluster group to which the table shard is moved.

dest_cluster_group

It is a target cluster group to which the table shard is moved.

[ ONLINE | OFFLINE ]

It determines whether to allow DML when rebalancing table shard.

Description

When adding a cluster member and a cluster group using the following statements, the table shard is not rebalanced.

Perform <alter database rebalance statement> to rebalance the shard of the entire table which was not rebalanced when adding a cluster group and a cluster member.

<alter database move shard statement> is performed as the following concepts for tables which did not rebalance the shard.

ALTER TABLE t1 MOVE SHARD FROM CLUSTER GROUP src_group TO CLUSTER GROUP dest_group;
COMMIT;
ALTER TABLE t2 MOVE SHARD FROM CLUSTER GROUP src_group TO CLUSTER GROUP dest_group;
COMMIT;
ALTER TABLE t3 MOVE SHARD FROM CLUSTER GROUP src_group TO CLUSTER GROUP dest_group;
COMMIT;
...
...
ALTER TABLE t_n MOVE SHARD FROM CLUSTER GROUP src_group TO CLUSTER GROUP dest_group;
COMMIT;

The <alter database move shard statement> is proceeded even when the rebalancing the shard of a specific table fails. It does not rollback the table which succeeded in rebalancing the shard.

Therefore, when performing <alter database move shard statement> again after appropriately processed an error, then it rebalances only the shard for the table requiring the rebalancing. In this case, the table which succeeded in rebalancing the shard is not included in a target of the rebalancing.

Examples

The following is an example of performing <alter database move shard statement>.

gSQL> ALTER DATABASE MOVE SHARD FROM CLUSTER GROUP G1 TO CLUSTER GROUP G2;

Database altered.

Compatibility

The SQL standard does not define the concepts of the cluster.

For More Information

Refer to the followings.

ALTER DATABASE OFFLINE INACTIVE CLUSTER MEMBERS

Function

It sets the entire inactive cluster member to offline. In other words, it sets the shard map for the cluster member to offline.

Syntax

<alter database offline inactive cluster members statement> ::=
    ALTER DATABASE OFFLINE INACTIVE CLUSTER MEMBERS
    ;

Invocation and Access Rules

It can be performed in a cluster system.
ADMINISTRATION ON DATABASE privilege is required to perform <alter database offline inactive cluster members statement>.

Syntax Rules and Parameters

It sets the entire inactive cluster member to offline.
The inactive state of a cluster member means that it is not connected to the cluster system, and it occurs in the following cases.

Description

It is recommended to use <alter database offline inactive members statement> when an inactive cluster member can not be included in the cluster system any more.

If an inactive cluster member can participate in a cluster system, then perform ALTER SYSTEM JOIN DATABASE to include it in a cluster system.

The cluster member which is set to offline can be shifted to online again by using the following statements after the join.

Examples

gSQL> ALTER DATABASE OFFLINE INACTIVE CLUSTER MEMBERS;

Compatibility

The SQL standard does not define the concepts of the cluster.

For More Information

Refer to the followings.

ALTER DATABASE REBALANCE

Function

It rebalances shard of all tables.

Syntax

<alter database rebalance statement> ::=
    ALTER DATABASE REBALANCE [ ONLINE | OFFLINE ];

Invocation and Access Rules

It can be performed in a cluster system.
ALTER DATABASE ON DATABASE privilege is required to perform <alter database rebalance statement>.

Syntax Rules and Parameters

[ ONLINE | OFFLINE ]

It determines whether to allow DML when rebalancing table shard.

Description

When adding a cluster member and a cluster group using the following statements, the table shard is not rebalanced.

Perform <alter database rebalance statement> to rebalance the shard of the entire table which was not rebalanced when adding a cluster group and a cluster member.

<alter database rebalance statement> is performed as the following concepts for tables which did not rebalance the shard.

ALTER TABLE t1 REBALANCE;
COMMIT;
ALTER TABLE t2 REBALANCE;
COMMIT;
ALTER TABLE t3 REBALANCE;
COMMIT;
...
...
ALTER TABLE t_n REBALANCE;
COMMIT;
The <alter database rebalance statement> is proceeded even when the rebalancing the shard of a specific table fails. It does not rollback the table which succeeded in rebalancing the shard.
Therefore, when performing <alter database rebalance statement> again after appropriately processed an error, then it rebalances only the shard for the table requiring the rebalancing. In this case, the table which succeeded in rebalancing the shard is not included in a target of the rebalancing.

Examples

The following is an example of performing <alter database rebalance statement>.

gSQL> ALTER DATABASE REBALANCE;

Database altered.

Compatibility

The SQL standard does not define the concepts of the cluster.

For More Information

Refer to ALTER TABLE name REBALANCE.

ALTER DATABASE REBALANCE EXCLUDE CLUSTER GROUP

Function

It rebalances shard of all tables excluding shards of a specific cluster group.

Syntax

<alter database rebalance exclude cluster group statement> ::=
    ALTER DATABASE REBALANCE EXCLUDE CLUSTER GROUP cluster_group_name [ ONLINE | OFFLINE ];

Invocation and Access Rules

It can be performed in a cluster system.
ALTER DATABASE ON DATABASE privilege is required to perform <alter database rebalance exclude cluster group statement>.

Syntax Rules and Parameters

cluster_group_name

It is a name of the cluster group excluding a shard of the table.
If the specified cluster group is the only cluster group, then the statement can not be performed.

[ ONLINE | OFFLINE ]

It determines whether to allow DML when rebalancing table shard.

Description

To drop a cluster group by using DROP CLUSTER GROUP, there should not be a shard in the cluster group.

Perform <alter database rebalance exclude cluster group statement> to exclude a shard from the cluster group. <alter database rebalance exclude cluster group statement> is performed as the following concepts for tables which include a shard in the cluster group.

ALTER TABLE t1 REBALANCE EXCLUDE CLUSTER GROUP g3;
COMMIT;
ALTER TABLE t2 REBALANCE EXCLUDE CLUSTER GROUP g3;
COMMIT;
ALTER TABLE t3 REBALANCE EXCLUDE CLUSTER GROUP g3;
COMMIT;
...
...
ALTER TABLE t_n REBALANCE EXCLUDE CLUSTER GROUP g3;
COMMIT;
If  the <alter database rebalance exclude cluster group statement> fails due to the lack of storage space, it does not rollback the table which succeed in excluding a shard.
Therefore, when performing <alter database rebalance exclude cluster group statement> again after appropriately processed an error, then it excludes and rebalances only the shard for the table requiring the rebalancing. In this case, the table which succeeded in excluding the shard is not included in a target of the rebalancing.

Examples

The following is an example of performing <alter database rebalance exclude cluster group statement>.

gSQL> ALTER DATABASE REBALANCE EXCLUDE CLUSTER GROUP g3;

Database altered.

Compatibility

The SQL standard does not define the concepts of the cluster.

For More Information

Refer to the followings.

ALTER DATABASE RECOVER

Function

It recovers the entire data file or part of the data files in the database by using the online and archive log files.

Syntax

<alter database recover statement> ::=
      <complete database recover statement>
    | <datafile recover statement>
    | <complete tablespace recover statement>
    | <incomplete database recover statement>
    ;

<complete database recover statement> ::=
    ALTER DATABASE RECOVER

<datafile recover statement> ::=
    ALTER DATABASE RECOVER DATAFILE <datafile recovery clause>

<datafile recovery clause> ::=
    <datafile recovery object> [, ...]

<datafile recovery object> ::=
    'datafile_name' [<recovery using backup option>] [recovery corruption option>]

<recovery using backup option> ::=
    USING BACKUP 'backup_datafile_name'

<recovery corruption option> ::=
    CORRUPTION

<complete tablespace recover statement> ::=
    ALTER DATABASE RECOVER TABLESPACE tablespace_name

<incomplete database recover statement> ::=
      <batch incomplete recovery statement>
    | <interactive incomplete recovery statement>
    ;

<batch incomplete recovery statement> ::=
    ALTER DATABASE RECOVER <until clause> [<using backup controlfile option>]
    
<until clause> ::=
      UNTIL CHANGE integer

<using backup controlfile option> ::=
    USING BACKUP CONTROLFILE

<interactive incomplete recovery statement> ::=
    ALTER DATABASE <incomplete recovery option> [<using backup controlfile option>]

<incomplete recovery option> ::=
      BEGIN INCOMPLETE RECOVERY
    | END INCOMPLETE RECOVERY
    | RECOVER 'logfile name'
    | RECOVER AUTOMATICALLY
    | RECOVER SUGGESTION
    ;

Invocation and Access Rules

ALTER DATABASE ON DATABASE privilege is required to perform <alter database recover statement>.

Syntax Rules and Parameters

<complete database recover statement>

The data files of the database are recovered up to date by using the online and archive log files.

<datafile recover statement>

It recovers the backuped datafile, the datafile of the tablespace which requires the recovery by using the archive logfile due to an error during the backup, or the datafile of the tablespace which was set to offline by an immediate option, to the latest status.

<complete tablespace recover statement>

The data files of the tablespace is recovered up to date.

<incomplete database recover statement>

<batch incomplete database recover statement>

The datafiles in the database are recovered in a batch up to a specific point of time by using the online and archive logfile.

<interactive incomplete database recover statement>

The data files in the database are interactively recovered with a user up to a specific point of time by using online and archive log file.

Description

Incomplete recovery of the database is not easy to find a recovery completion point at a time. Therefore, the desired recovery point is found by performing it several times.
However, it becomes a new database if the database is started up with RESETLOGS option after an incomplete recovery. Therefore, the incomplete recovery should be performed several times after creating a copy of the archived log files and online redo log files.

Examples

The following is an example of a complete recovery for entire database.

ALTER DATABASE RECOVER;

The following is an example of a datafile recovery.

ALTER DATABASE RECOVER DATAFILE 'test.dbf';

The following is an example of a tablespace recovery.

ALTER DATABASE RECOVER TABLESPACE test_tbs;

The following is an example of incomplete recovery for the entire database until LSN is 11123.

ALTER DATABASE RECOVER UNTIL CHANGE 11123;

The following is an example of interactive incomplete recovery until the recoverable archive log files.

ALTER DATABASE BEGIN INCOMPLETE RECOVERY;
ALTER DATABASE RECOVER AUTOMATICALLY;
ALTER DATABASE END INCOMPLETE RECOVERY;

Compatibility

The SQL standard does not define ALTER DATABASE statement.

For More Information

Refer to the followings.

ALTER DATABASE REGISTER

Function

It registers unrecoverable segments in the database.

Syntax

<alter database register statement> ::=
    ALTER DATABASE REGISTER IRRECOVERALBE SEGMENT 
        <segment physical identifier list>
    ;

<segment physical identifier list> ::=
      integer
    | <segment physical identifier list> , integer

Invocation and Access Rules

ALTER DATABASE ON DATABASE privilege is required to perform <alter database register statement>.

Syntax Rules and Parameters

<alter database register statement>

It registers the unrecoverable segments in the database. The statement can be used on the assumption that the segment is not used any more, when the database is not recoverable and the backup does not exist.

<segment physical identifier list>

The list of unrecoverable segment identifier
• Integer: 8 bytes integer segment identifier

Description

When a server restarts after abnormal termination, the database performs the recovery process. During this process, it executes pages again by using the REDO log to recover pages which was not reflected in the disk in the previous service stage.

If an unexpected failure occurs during execution of the REDO operation, that statement can be used to ignore the failure and to execute the recovery.

Example

The following is an example of giving up the recovery of the segment whose identifier is 4028679323648.

ALTER DATABASE REGISTER IRRECOVERABLE SEGMENT 4028679323648;

Compatibility

The SQL standard does not define ALTER DATABASE statement.

For More Information

Refer to the followings.

ALTER DATABASE RENAME LOGFILE

Function

It renames the logfile in the database.

Syntax

<alter database rename logfile statement> ::=
    ALTER DATABASE RENAME LOGFILE <logfile_list> TO <logfile_list>
    ;

<logfile_list> ::=
      'logfile_name'
    | <logfile_list> , 'logfile_name'

Invocation and Access Rules

ALTER DATABASE ON DATABASE privilege is required for performing <alter database rename logfile statement>.

Syntax Rules and Parameters

<alter database rename logfile statement>

Description

For more information, refer to the rules for each syntax.

Example

The following is an example of modifying the existing 'logfile.log' logfile to 'newlogfile.log'.

ALTER DATABASE RENAME LOGFILE 'logfile.log' TO 'newlogfile.log';

Compatibility

The SQL standard does not define ALTER DATABASE statement.

For More Information

Refer to the followings.

ALTER DATABASE RESET LOCAL CLUSTER MEMBER

Function

It resets the local cluster member except for the tablespace object to the time of creating the database.

Syntax

<alter database reset local cluster member statement> ::=
    ALTER DATABASE RESET LOCAL CLUSTER MEMBER
    ;

Invocation and Access Rules

It can be performed in a cluster system.
The start-up phase should be LOCAL OPEN.
ADMINISTRATION ON DATABASE privilege is required to perform <alter database reset local cluster member statement>.

Description

It resets the local cluster member except for the tablespace object to the time of creating the database. It drops all objects created by a user except for the tablespace object.
<alter database reset local cluster member statement> statement resets an inactive cluster member, and makes the new cluster member to participate in a cluster system.
An inactive cluster member which is disconnected from the cluster system is processed as follows.

In this case, the device corresponding to the cluster member which is excluded from a cluster system can be used again by using the following two methods.

The method 2 reduces the cost of recreating the tablespace comparing to the method 1.

Examples

The following is an example of a reset by using <alter database reset local cluster member statement> after driving the local cluster member, which is excluded from the cluster system, up to LOCAL OPEN phase.

gSQL> \startup nomount

Startup success


gSQL> ALTER SYSTEM MOUNT DATABASE;

System altered.


gSQL> ALTER SYSTEM OPEN LOCAL DATABASE;

System altered.

gSQL> ALTER DATABASE RESET LOCAL CLUSTER MEMBER;

Database altered.

Compatibility

The SQL standard does not define the concepts of the cluster.

For More Information

Refer to the followings.

ALTER DATABASE RESTORE

Function

It restores the data files in the database or tablespace by using the incremental backup.

Syntax

<alter database restore statement> ::=
      <database restore statement>
    | <tablespace restore statement>
    | <controlfile restore statement>
    ;

<database restore statement> ::=
    ALTER DATABASE RESTORE [ <until clause> ]

<until clause> ::=
    UNTIL CHANGE integer

<tablespace restore statement> ::=
    ALTER DATABASE RESTORE TABLESPACE tablespace_name

<controlfile restore statement> ::=
    ALTER DATABASE RESTORE CONTROLFILE FROM 'file_name'

Invocation and Access Rules

ALTER DATABASE ON DATABASE privilege is required to perform <alter database restore statement>.

Syntax Rules and Parameters

<database restore statement>

It restores the data files in the database by using the incremental backup. 
The database should be in MOUNT phase.

<tablespace restore statement>

It restores the data files in the tablespace by using the incremental backup.

<controlfile restore statement>

The control file is recovered using 'file_name'.

Description

The data recovery using full backup uses OS copy command to directly copy the backup file to the data file path. The data recovery using incremental backup restores only the deleted data files or old data files.

Examples

The following is an example of recovering the database by using the incremental backup.

ALTER DATABASE RESTORE;

The following is an example of recovering the tablespace by using the incremental backup.

ALTER DATABASE RESTORE TABLESPACE test_tbs;

The following is an example of recovering the database by using only the incremental backup whose LSN is smaller than 11123.

ALTER DATABASE RESTORE UNTIL CHANGE 11123;

The following is an example of recovering the control file by using controlfile.bak.

ALTER DATABASE RESTORE CONTROLFILE FROM 'controlfile.bak'

Compatibility

The SQL standard does not define ALTER DATABASE statement.

For More Information

Refer to the followings.

ALTER INDEX

Function

It alters the index definition.

Syntax

<alter index statement> ::=
      <alter index physical attribute statement>
    | <rename index statement>
    | <aging index statement>
    | <rebuild statement>
    ;

Invocation and Access Rules

One of the following privileges is required to perform <alter index statement>.

Syntax Rules and Parameters

<alter index physical attribute statement>

It alters physical attributes of the index.
For more information, refer to ALTER INDEX name STORAGE.

<rename index statement>

It alters the index name.
For more information, refer to ALTER INDEX name RENAME TO.

<aging statement>

It deletes the empty page of the index.
For more information, refer to ALTER INDEX name AGING.

<rebuild statement>

It rebuilds the index.
For more information, refer to ALTER INDEX name REBUILD.

Description

Refer to the descriptions of each detailed statement.

Examples

Refer to the examples of each detailed statement.

Compatibility

The SQL standard does not define the concepts of the index.

ALTER INDEX name AGING

Function

It deletes an empty page of the index.

Syntax

<aging index statement> ::=
    ALTER INDEX index_name AGING
    ;

Invocation and Access Rules

One of the following privileges is required to perform <aging index statement>.

Syntax Rules and Parameters

index_name

It is the name of the target index.

Description

This syntax returns pages whose all keys are deleted among index pages to a segment. Aging is processed in two steps which are logical deletion and physical deletion. A logical deletion is disconnection of index page, and it is performed when SCN of when deleting the last key of a page is smaller than the agable SCN of the system. Then the physical deletion is performed when the SCN of the logical deletion is smaller then the agable SCN of the system.

If the agable SCN of the system does not increase, then the empty page may not be deleted even though the index AGING statement succeeded.

Examples

The following is an example of aging the index.

gSQL> select index_name, empty_blocks from user_indexes where index_name = 'T1X';

INDEX_NAME EMPTY_BLOCKS
---------- ------------
T1X                   2

1 row selected.

gSQL> alter index t1x aging;

Index altered.

gSQL> select index_name, empty_blocks from user_indexes where index_name = 'T1X';

INDEX_NAME EMPTY_BLOCKS
---------- ------------
T1X                   0

1 row selected.

Compatibility

The SQL standard does not define the concepts of the index.

For More Information

Refer to the followings.

ALTER INDEX name REBUILD

Function

It rebuilds an index.

Syntax

<rebuild index statement> ::=
    ALTER INDEX index_name REBUILD
        [ ONLINE | OFFLINE ]
        [ <index attributes> [...] ]
        [ TABLESPACE tablespace_name ]
    ;

<index attributes> ::=
      <physical attribute clause>
    | STORAGE ( <segment attr clause> [...] )
    | <parallel clause> 

<physical attribute clause> ::=
      PCTFREE integer
    | INITRANS integer
    | MAXTRANS integer

<segment attr clause> ::=
      INITIAL <size_clause>
    | NEXT <size_clause>
    | MINSIZE <size_clause>
    | MAXSIZE <size_clause>

<size clause> ::=
      integer [ K | M | G | T ]

<parallel clause> ::=
      NOPARALLEL
    | PARALLEL [ integer ]

Invocation and Access Rules

The user should satisfy the following conditions to perform <rebuild index statement>.

At least one of the following privileges for a tablespace in which the index is to be created is required.

Syntax Rules and Parameters

index_name

It is the name of the target index.
The schema name can be specified, and the user's default schema name is used when it is omitted.

[ ONLINE | OFFLINE ]

It determines whether to allow DML on the table when rebuilding the index.

<physical attribute clause>

It defines the physical attribute information of an index.

<segment attr clause>

It specifies the information for the index storage space.

<size clause>

It specifies the file size in bytes. (If the unit is omitted, the default value is bytes.)

NOPARALLEL | PARALLEL [ integer ]

It specifies the number of threads to be used when rebuilding an index.

TABLESPACE tablespace_name

It specifies the name of the tablespace in which the index is to be rebuilt.

Description

Examples

The following is an example of altering the index logging setting and the tablespace.

gsql> SELECT INDEX_NAME, TABLESPACE_NAME FROM INDEXES AS IDX, TABLESPACES AS TBS WHERE IDX.TABLESPACE_ID = TBS.TABLESPACE_ID AND IDX.INDEX_NAME = 'T1X';

INDEX_NAME TABLESPACE_NAME
---------- ---------------
T1X        MEM_TEMP_TBS   

1 row selected.

gsql> ALTER INDEX T1X REBUILD TABLESPACE MEM_DATA_TBS;

SELECT INDEX_NAME, TABLESPACE_NAME FROM INDEXES AS IDX, TABLESPACES AS TBS WHERE IDX.TABLESPACE_ID = TBS.TABLESPACE_ID AND IDX.INDEX_NAME = 'T1X';

INDEX_NAME TABLESPACE_NAME
---------- ---------------
T1X        MEM_DATA_TBS   

1 row selected.

Compatibility

The SQL standard does not cover the concepts of the index.

For More Information

Refer to the followings.

ALTER INDEX name RENAME TO

Function

It alters the index name.

Syntax

<rename index statement> ::=
    ALTER INDEX index_name
        RENAME TO new_index_name
    ;

Invocation and Access Rules

One of the following privileges is required to perform <rename index statement>.

Syntax Rules and Parameters

index_name

It is the name of the target index.
The schema name can not be described and it has the same schema name as same as that of the existing index.

new_index_name

It is the name of the new index, and it should be a unique index name within the schema.

Description

Refer to the syntax rules of each statement.

Examples

The following is an example of altering the index name.

gSQL> ALTER INDEX t1_idx1 RENAME TO idx_t1_id;

Index altered.

Compatibility

The SQL standard does not define the concepts of the index.

For More Information

Refer to the followings.

ALTER INDEX name STORAGE

Function

It alters the physical attributes of the index.

Syntax

<alter index physical attribute statement> ::=
    ALTER INDEX index_name
    | <physical attribute clause>
    | [ STORAGE ( <segment attr clause> [...] ) ]
    ;

<physical attribute clause> ::=
      PCTFREE integer
    | INITRANS integer
    | MAXTRANS integer

<segment attr clause> ::=
      INITIAL <size_clause>
    | NEXT <size_clause>
    | MINSIZE <size_clause>
    | MAXSIZE <size_clause>

<size clause> ::=
      integer [ K | M | G | T ]

Invocation and Access Rules

One of the following privileges is required to perform <alter index physical attribute statement>.

Syntax Rules and Parameters

index_name

It is the target index name.

<physical attribute clause>

It defines the physical attribute information of the index.

<segment attr clause>

It specifies the information for the index storage space.

<size clause>

It specifies the file size in byte. (If it is omitted, the default unit is bytes.)

Description

Refer to the syntax rules of each statement.

Examples

The following is an example of altering the physical attributes of the index.

gSQL> ALTER INDEX idx_t1_id PCTFREE 10 INITRANS 4 MAXTRANS 8;

Index altered.

Compatibility

The SQL standard does not define the concepts of the index.

For More Information

Refer to the followings.

ALTER PROFILE

Function

It alters the password management method.

Syntax

<alter profile statement> ::= 
    ALTER PROFILE profile_name LIMIT 
    { <password_parameters>, ...}
    ; 

<password parameters> ::= 
      FAILED_LOGIN_ATTEMPTS { integer | UNLIMITED | DEFAULT }
    | PASSWORD_LOCK_TIME  { password_parameter_number_interval | UNLIMITED | DEFAULT }
    | PASSWORD_LIFE_TIME  { password_parameter_number_interval | UNLIMITED | DEFAULT }
    | PASSWORD_GRACE_TIME { password_parameter_number_interval | UNLIMITED | DEFAULT }
    | PASSWORD_REUSE_MAX  { integer | UNLIMITED | DEFAULT }
    | PASSWORD_REUSE_TIME { password_parameter_number_interval | UNLIMITED | DEFAULT }
    | PASSWORD_VERIFY_FUNCTION { <verify_policy> | NULL | DEFAULT }

<verify_policy> ::= 
      KISA_VERIFY_FUNCTION
    | ORA12C_VERIFY_FUNCTION
    | ORA12C_STRONG_VERIFY_FUNCTION
    | VERIFY_FUNCTION_11G 
    | VERIFY_FUNCTION

<password_parameter_number_interval> ::=
   integer 
 | integer / integer

Invocation and Access Rules

ALTER PROFILE ON DATABASE privilege is required to perform <alter profile statement>.

Syntax Rules and Parameters

profile_name

It is a profile name to be altered.

FAILED_LOGIN_ATTEMPTS

It sets the number of consecutive login attempts allowed to fail.
For more information, refer to CREATE PROFILE.

PASSWORD_LOCK_TIME

It sets an account lockout duration (day) after the consecutive login failures.
For more information, refer to CREATE PROFILE.

PASSWORD_LIFE_TIME

It sets the password lifetime (day).
For more information, refer to CREATE PROFILE.

PASSWORD_GRACE_TIME

It sets a password expiration grace period when log in after PASSWORD_LIFE_TIME.
For more information, refer to CREATE PROFILE.

PASSWORD_REUSE_MAX

It specifies the number of the recent passwords which can not be reused when a user wants to reuse the old password.
For more information, refer to CREATE PROFILE.

PASSWORD_REUSE_TIME

It specifies the duration which the password can not be reused when a user wants to reuse the old password.
For more information, refer to CREATE PROFILE.

PASSWORD_VERIFY_FUNCTION

It sets the password complexity verification method.
For more information, refer to CREATE PROFILE.

Examples

The following is an example of changing the profile to control the account lockout.

gSQL> ALTER PROFILE prof1 LIMIT
        FAILED_LOGIN_ATTEMPTS 3
        PASSWORD_LOCK_TIME 3;

Profile altered.

gSQL> COMMIT;

Commit complete.

The following is an example of changing the profile to control the password lifetime.

gSQL> ALTER PROFILE prof1 LIMIT
        PASSWORD_LIFE_TIME 90 
        PASSWORD_GRACE_TIME 7;

Profile altered.

gSQL> COMMIT;

Commit complete.

The following is an example of changing the profile to control the password reusability.

gSQL> ALTER PROFILE prof1 LIMIT
        PASSWORD_REUSE_MAX  DEFAULT
        PASSWORD_REUSE_TIME DEFAULT;

Profile altered.

gSQL> COMMIT;

Commit complete.

The following is an example of changing the profile to control the password complexity verification.

gSQL> ALTER PROFILE prof1 LIMIT
        PASSWORD_VERIFY_FUNCTION KISA_VERIFY_FUNCTION;

Profile altered.

gSQL> COMMIT;

Commit complete.

Compatibility

The SQL standard does not define the concepts of the profile.

For More Information

Refer to DROP PROFILE.

ALTER SEQUENCE

Function

It alters the sequence.

Syntax

<alter sequence generator statement> ::=
    ALTER SEQUENCE sequence_name <alter sequence generator options>
    ;

<alter sequence generator options> ::=
    <alter sequence generator option> [, ...]

<alter sequence generator option> ::=
      <alter sequence generator restart option>
    | <basic sequence generator option>

<alter sequence generator restart option> ::=
    RESTART [ WITH integer ]

<basic sequence generator option> ::=
      <sequence generator increment by option>
    | <sequence generator maxvalue option>
    | <sequence generator minvalue option>
    | <sequence generator cycle option>
    | <sequence generator cache option>


<sequence generator increment by option> ::=
    INCREMENT BY integer

<sequence generator maxvalue option> ::=
      MAXVALUE integer
    | (NO MAXVALUE | NOMAXVALUE)

<sequence generator minvalue option> ::=
      MINVALUE integer
    | (NO MINVALUE | NOMINVALUE)

<sequence generator cycle option> ::=
      CYCLE 
    | (NO CYCLE | NOCYCLE)

<sequence generator cache option> ::=
      CACHE integer
    | (NO CACHE | NOCACHE)

Invocation and Access Rules

One of the following privileges is required to perform <alter sequence generator statement>.

Syntax Rules and Parameters

sequence_name

It is the sequence name to be altered.
It can define schema to which the sequence belongs such as schema_name.sequence_name and if schema_name is omitted, the default schema name of the user performing the statement is used.

<alter sequence generator restart option>

It sets NEXT VALUE of the sequence.
However, it does not change the value of START WITH which is defined in CREATE SEQUENCE statement.

If <alter sequence generator restart option> clause is not specified, it changes the sequence attributes based on the current sequence value.

<sequence generator increment by option>

It changes the interval of the sequence number.
The constraints and characteristics are as follows.

<sequence generator maxvalue option>

It changes the maximum value which the sequence can generate.
However, the MAXVALUE should not be smaller than the current sequence value.

<sequence generator minvalue option>

It changes the minimum value which the sequence can generate.
However, the MINVALUE should not be bigger than the current sequence value.

<sequence generator cycle option>

It changes whether to continue generating a value when the sequence value becomes the maximum or minimum value.

<sequence generator cache option>

For quick access of a sequence, it defines the number of sequence values to be pre-loaded on the memory.
When restarting the database, the sequence value loaded on the memory is lost, and it starts from the value after loading.

Description

It can not change START WITH which is one of the sequence attributes defined in CREATE SEQUENCE statement. To change START WITH attribute, it should be re-created by performing CREATE SEQUENCE statement after performing DROP SEQUENCE statement.

Examples

The following is an example of restating the sequence value by using RESTART option, then assigning a new ID.

gSQL> SELECT id, name FROM t1 ORDER BY 1;

 ID NAME  
--- ------
 10 leekmo
 42 mkkim 
 51 jhkim 
172 ehpark

4 rows selected.


gSQL> ALTER SEQUENCE seq1 RESTART;

Sequence altered.


gSQL> UPDATE t1 SET id = seq1.NEXTVAL;

4 rows updated.


gSQL> SELECT id, name FROM t1 ORDER BY 1;

ID NAME  
-- ------
 1 leekmo
 2 mkkim 
 3 jhkim 
 4 ehpark

4 rows selected.

Compatibility

The SQL standard does not define CACHE/ NO CACHE statement.

SQL standard compatibility

Feature ID

Description

Compatibility

T176

Sequence generator support

O

T177

Sequence generator support: simple restart option

O

For More Information

Refer to the followings.

ALTER SESSION CLEANUP GLOBAL TEMPORARY SEGMENT POOL;

Function

It returns all segments which were caught to be reused in a session to tablespaces.

Syntax

<alter session cleanup global temporary segment pool statement> ::=
    ALTER SESSION CLEANUP GLOBAL TEMPORARY SEGMENT POOL
    ;

Description

It cleans up only the segments of a segment cache in the performed session.

Examples

The following is an example of cleaning up the segment cache of the session.

gSQL> ALTER SESSION CLEANUP GLOBAL TEMPORARY SEGMENT POOL;

Session altered.

Compatibility

The SQL standard does not define the concepts of the segment cache of a global temporary table and a global temporary index.

For More Information

Refer to Global Temporary Table.

ALTER SESSION SET property_name

Function

It sets the property value of the session.

Syntax

<alter session set statement> ::=
    ALTER SESSION SET <property name> { = <property value> | TO DEFAULT }
    ;

Syntax Rules and Parameters

<property name>

It is the property name to be set.
For more information, refer to Server Property in an administration manual.

<property value>

It is the property value to be set.

TO DEFAULT

It sets the session property value as a system property value.

Description

For more information about property, refer to Server Property in an administration manual.

Examples

The following is an example of an error when setting ERROR HINT property so the hint clause includes an error.

gSQL> ALTER SESSION SET HINT_ERROR = ON;

Session altered.

gSQL> SELECT /*+ INDEX( t1, invalid_index ) */ name FROM t1 WHERE id = 1;

ERR-42000(16058): not applicable hint : 
SELECT /*+ INDEX( t1, invalid_index ) */ name FROM t1 WHERE id = 1
           *
ERROR at line 1:

The following is an example of setting the session property value as the system property value.

gSQL> ALTER SESSION SET HINT_ERROR TO DEFAULT;

Session altered.

Compatibility

The SQL standard does not define the concepts of the session property.

For More Information

Refer to ALTER SESSION SET property_name.

ALTER SYSTEM CHECKPOINT

Function

It performs CHECKPOINT.

Syntax

<alter system checkpoint statement> ::=
    ALTER SYSTEM CHECKPOINT
    [ AT <domain name> ]
    ;

Invocation and Access Rules

ALTER SYSTEM ON DATABASE privilege is required to perform <alter system checkpoint statement>.

Syntax Rules and Parameters

<alter system checkpoint statement>

CHECKPOINT is an operation to ensure that all altered data by the committed transactions are written to disk.

<domain name>

It is a name of a member or a group for which the statement is performed.
If it is omitted, it is performed for all groups.

Description

The checkpoint operation records all changes by the committed transactions to disk, so it enables a rapid recovery at system error.

Example

The following is an example of performing CHECKPOINT.

ALTER SYSTEM CHECKPOINT;

Compatibility

The SQL standard does not define the concepts of CHECKPOINT.

ALTER SYSTEM CLEANUP BUFFER_CACHE

Function

It clears all buffer pages which can be free from the buffer cache.

Syntax

<alter system cleanup buffer_cache statement> ::=
    ALTER SYSTEM CLEANUP BUFFER_CACHE
    [ AT <domain name> ]
    ;

Invocation and Access Rules

ALTER SYSTEM ON DATABASE privilege is required to perform <alter system cleanup buffer_cache statement>.

Syntax Rules and Parameters

<alter system cleanup buffer_cache statement>

Syntax rules and parameters do not exist for <alter system cleanup buffer_cache statement>.

<domain name>

It is a name of a member or a group for which the statement is performed.
If it is omitted, it is performed for all groups.

Description

It flushes and frees all free buffer pages cached in the buffer.

It should be used to clear the buffer cache before the performance measuring.

If it is used on the operating server, then it could have fatal effect for the performance.

Example

The following is an example of performing CLEANUP BUFFER_CACHE.

ALTER SYSTEM CLEANUP BUFFER_CACHE;

Compatibility

The SQL standard does not define the concepts of CLEANUP BUFFER_CACHE.

ALTER SYSTEM CLEANUP PLAN

Function

It cleans up all SQL plans.

Syntax

<alter system cleanup plan statement> ::=
    ALTER SYSTEM CLEANUP PLAN
    [ AT <domain name> ]
    ;

Invocation and Access Rules

ALTER SYSTEM ON DATABASE privilege is required to perform <alter system cleanup plan statement>.

Syntax Rules and Parameters

<alter system cleanup plan statement>

There is not any syntax rules or parameters for <alter system cleanup plan statement>.

<domain name>

It is a name of a member or a group for which the statement is performed.
If it is omitted, it is performed for all groups.

Description

It cleans up all of the cached SQL plan. However, the plan whose V$SQL CACHE.REF COUNT is bigger than 0 (the plan referenced by the prepared statement) is excluded from cleanup.

Examples

The following is an example of executing CLEANUP PLAN.

ALTER SYSTEM CLEANUP PLAN;

Compatibility

The SQL standard does not define the concepts of CLEANUP PLAN.

ALTER SYSTEM IRRECOVERABLE CLUSTER MEMBER

Function

It specifies an irrecoverable cluster member.

Syntax

<alter system irrecoverable cluster member statement> ::=
    ALTER SYSTEM IRRECOVERABLE CLUSTER MEMBER <domain name>
    ;

Invocation and Access Rules

ALTER SYSTEM ON DATABASE privilege is required to perform <alter system irrecoverable cluster member statement>.

Syntax Rules and Parameters

<alter system irrecoverable cluster member statement>

There is not any syntax rules or parameters for <alter system irrecoverable cluster member statement>.

<domain name>

It is a name of an irrecoverable member. 
It is not allowed to specify all members in a group as an irrecoverable member.

Description

It is used to restart the system excluding the corresponding member if the cluster failed to restart due to an irrecoverable member. The corresponding member should be dropped by using ALTER DATABASE DROP INACTIVE CLUSTER MEMBERS after the system succeeded to restart.

Examples

The following is an example of executing IRRECOVERABLE CLUSTER MEMBER.

gSQL> ALTER SYSTEM IRRECOVERABLE CLUSTER MEMBER g1n1;

Compatibility

The SQL standard does not define the concepts of IRRECOVERABLE CLUSTER MEMBER.

ALTER SYSTEM JOIN DATABASE

Function

It includes a specific inactive cluster member in a cluster system again.

Syntax

<alter system join database statement> ::=
    ALTER SYSTEM JOIN DATABASE 
    ;

Invocation and Access Rules

It can be performed in a cluster system.
ADMINISTRATION ON DATABASE privilege is required to perform <alter system join database statement>.

Description

The inactive state of a cluster member means that it is not connected to the cluster system, and it occurs in the following cases.

If a specific cluster member is inactive, then the member can be included in a cluster system again according to the following procedure.

$ gsql sys gliese --as sysdba --dsn=G3N2
gSQL> \startup
$ gsql sys gliese --as sysdba --dsn=G3N2
gSQL> ALTER SYSTEM JOIN DATABASE;

Use <alter system join database statement> to make an inactive cluster member which is started up to the local open phase to participate in the cluster system without shutting it down.

To make the inactive cluster member to participate in the cluster system again, the database state of the cluster system and that of the inactive cluster member should be same.

The inactive cluster member can not participate in the cluster system again after the transaction altering the database in the cluster system completed.

To operate the cluster system normally the inactive cluster members should be dropped according to the following procedure when multiple inactive cluster members exist.
  1. JOIN inactive cluster members which can participate in the cluster system.

gSQL> ALTER SYSTEM JOIN DATABASE;
  1. DROP inactive cluster members which can not participate in the cluster system.

gSQL> ALTER DATABASE DROP INACTIVE CLUSTER MEMBERS;

All inactive cluster members which can participate in the cluster system should be included in the cluster system before dropping because all inactive cluster members are dropped from the cluster system when performing <alter database drop inactive cluster member statement>.

Examples

gSQL> ALTER SYSTEM JOIN DATABASE;

Compatibility

The SQL standard does not define the concepts of the cluster.

For More Information

Refer to ALTER DATABASE DROP INACTIVE CLUSTER MEMBERS.

ALTER SYSTEM [KILL | DISCONNECT] SESSION

Function

It terminates a session.

Syntax

<alter system end session statement> ::=
      ALTER SYSTEM DISCONNECT SESSION [<member_position>,] <session_id>,
           <serial#> [<disconnect_option>] [AT <domain name>]
    |  ALTER SYSTEM KILL SESSION [<member_position>,]
           <session_id>, <serial#> [AT <domain name>]
    ;
<disconnect_option> ::=
      POST_TRANSACTION
    | IMMEDIATE

Invocation and Access Rules

ALTER SYSTEM ON DATABASE privilege is required to perform <alter system end session statement>.

Syntax Rules and Parameters

<member_position>

It is a member position of a session which is a disconnect/kill target in a cluster environment.

<session_id>

It is the session ID.

<serial#>

It is the SERIAL NUMBER of the session.

<disconnect_option>

If <disconnect_option> is not used, then it is operated in IMMEDIATE.

<domain name>

It is a name of a member or a group for which the statement is performed.
If it is omitted, it is performed for all groups.

Description

DISCONNECT SESSION can specify the options such as POST TRANSACTION and IMMEDIATE. 
POST TRANSACTION terminates the session after the currently running transaction is completed. IMMEDIATE terminates the session after immediately cleaning up the currently running transaction.
KILL SESSION terminates the abnormal session which remains on the system without its process.

Example

gSQL> SELECT USER_NAME, SESSION_ID, SERIAL_NO, SESSION_STATUS, PROGRAM_NAME FROM V$SESSION WHERE USER_NAME = 'TEST';

USER_NAME SESSION_ID SERIAL_NO SESSION_STATUS PROGRAM_NAME
--------- ---------- --------- -------------- ------------
TEST              62        49 CONNECTED      gsql        
TEST              65       109 CONNECTED      gsqlnet     
TEST              66       130 CONNECTED      gsql        

3 rows selected.

gSQL> ALTER SYSTEM DISCONNECT SESSION 65, 109;

System altered.

Compatibility

The SQL standard does not define it.

ALTER SYSTEM {MOUNT | OPEN} DATABASE

Function

It mounts the database on system, or alters the database to the state which is available for the service.

Syntax

<alter system database statement> ::=
    ALTER SYSTEM <alter system database clause>
    ;

<alter system database clause> ::= 
      MOUNT DATABASE
    | OPEN [ <database_scope> ] DATABASE [ <open_database_option> ]

<open_database_option> ::=
      READ WRITE [ NORESETLOGS | RESETLOGS ]
    | READ ONLY

<database_scope> ::=
      LOCAL
    | GLOBAL

Invocation and Access Rules

ADMINISTRATION ON DATABASE privilege is required to perform <alter system database statement>.

Syntax Rules and Parameters

<alter system database clause>

<open database option>

<database_scope>

Examples

The following is an example of driving the database in read only.

ALTER SYSTEM OPEN DATABASE READ ONLY;

The following is an example of driving the database in read/write, and initializing the online redo logs.

ALTER SYSTEM OPEN DATABASE READ WRITE RESETLOGS;

Compatibility

The SQL standard does not define the concepts of MOUNT or OPEN in the database.

For More Information

Refer to ALTER DATABASE RECOVER.

ALTER SYSTEM RECONNECT GLOBAL CONNECTION

Function

It determines whether to reconnect to the session which is connected in GLOBAL CONNECTION form.

Syntax

<alter system reconnect global connection statement> ::=
    ALTER SYSTEM RECONNECT GLOBAL CONNECTION
    ;

Invocation and Access Rules

ALTER SYSTEM ON DATABASE privilege is required to perform <alter system reconnect global connection statement>.

Description

Whether the GLOBAL CONNECTION client reconnects is determined by comparing SCN of a system object acquired from a server at the first connection and SCN of current server system object. This statement leads the client to reconnect by increasing SCN of the system object.

The client does not necessarily reconnect immediately after this statement is performed. The client reconnects by comparing SCN when the client executes a command in a server, and it does not try to reconnect if connections to all members from a client are valid.

Examples

The following is an example of executing the statement.

gSQL> ALTER SYSTEM RECONNECT GLOBAL CONNECTION;

System altered.

Compatibility

The SQL standard does not define the concepts of GLOBAL CONNECTION.

ALTER SYSTEM RESET property_name

Function

It removes a property value from the property file.

Syntax

<alter system reset statement> ::=
    ALTER SYSTEM { RESET | UNSET } <property name>
        [ SCOPE = { FILE | SPFILE } ]
        [ AT <domain name>]
    ;

Invocation and Access Rules

ALTER SYSTEM ON DATABASE privilege is required to perform <alter system reset statement>.

Syntax Rules and Parameters

{ RESET | UNSET }

RESET and UNSET are the reserved words with the same meaning, so either of them can be used.

<property name>

It is the property name to be removed.
For more information, refer to Server Property in an administration manual.

[ SCOPE = { FILE | SPFILE } ]

It removes the property from a property file, so only SCOPE=FILE/SPFILE can be used.

If SCOPE clause is not specified, the default value is SCOPE = FILE.

<domain name>

It is a name of a member or a group for which the statement is performed.
If it is omitted, it is performed for all groups.

Description

If a property is altered by using SCOPE=FILE/SPFILE, the updated property value is stored in the property file, and it is applied when restarting the database.
When executing RESET, the updated property value is removed from the property file and the default value is used when restarting the database.

Examples

The following is an example of altering the property by using SCOPE=FILE.

gSQL> ALTER SYSTEM SET PROCESS_MAX_COUNT=128 SCOPE=FILE;

System altered.

The following is an example of removing the property altered above.

gSQL> ALTER SYSTEM RESET PROCESS_MAX_COUNT SCOPE=FILE;

System altered.

gSQL> ALTER SYSTEM RESET PROCESS_MAX_COUNT SCOPE=SPFILE;

System altered.

gSQL> ALTER SYSTEM RESET PROCESS_MAX_COUNT;

System altered.

gSQL> ALTER SYSTEM UNSET PROCESS_MAX_COUNT;

System altered.

Compatibility

The SQL standard does not define the concepts of the system property.

For More Information

Refer to ALTER SYSTEM SET property_name.

ALTER SYSTEM SET property_name

Function

It sets the system property value.

Syntax

<alter system set statement> ::=
    ALTER SYSTEM SET <property name> { = <property value> | TO DEFAULT }
        [ DEFERRED ]
        [ SCOPE = [ MEMORY | { FILE | SPFILE } | BOTH ] ]
    [AT <domain name>]
    ;

Invocation and Access Rules

ALTER SYSTEM ON DATABASE privilege is required to perform <alter system set statement>.

Syntax Rules and Parameters

<property name>

It is the property name to be set.
For more information, refer to Server Property in an administration manual.

<property value>

It is the property value to be set.

TO DEFAULT

It sets the system property value as the initial value of system driving.

[ DEFERRED ]

It defines the point of time to apply the altered property.

If SYS_MODIFIABLE property value is IMMEDIATE, and DEFERRED is not explicitly specified, then it is immediately applied to all sessions.

[ SCOPE = [ MEMORY | { FILE | SPFILE } | BOTH ] ]

It specifies the range which is affected by the property changes of the system.

If SCOPE clause is omitted, the default value is SCOPE = MEMORY.
If SYS_MODIFIABLE property value is FALSE, it should be specified as SCOPE=FILE/SPFILE.

<domain name>

It is a name of a member or a group for which the statement is performed.
If it is omitted, it is performed for all groups.

Description

For more information, refer to Server Property in an administration manual.

Examples

The following is an example of changing the property whose SYS_MODIFIABLE property is DEFERRED.

gSQL> ALTER SYSTEM SET HINT_ERROR = ON;

ERR-22000(13019): Invalid property modify mode.(HINT_ERROR)

gSQL> ALTER SYSTEM SET HINT_ERROR = ON DEFERRED;

System altered.

The following is an example of changing the property whose SYS_MODIFIABLE property is FALSE.

gSQL> ALTER SYSTEM SET PROCESS_MAX_COUNT=128;

ERR-22000(13018): Specified property cannot be modified with this SCOPE option.(PROCESS_MAX_COUNT)

gSQL> ALTER SYSTEM SET PROCESS_MAX_COUNT=128 SCOPE=FILE;

System altered.

The following is an example of changing the altered property to the default value of when the session was connected.

gSQL> ALTER SYSTEM SET TRANSACTION_COMMIT_WRITE_MODE=0;

System altered.

gSQL> ALTER SYSTEM SET TRANSACTION_COMMIT_WRITE_MODE TO DEFAULT;

System altered.

gSQL> ALTER SYSTEM SET TRANSACTION_COMMIT_WRITE_MODE TO DEFAULT DEFERRED;

System altered.

Compatibility

The SQL standard does not define the concepts of the system property.

For More Information

Refer to ALTER SYSTEM RESET property_name.

ALTER SYSTEM SWITCH LOGFILE

Function

It alters the log files in CURRENT state to ACTIVE state in database.

Syntax

<alter system switch logfile statement> ::=
    ALTER SYSTEM SWITCH LOGFILE
    [ AT <domain name> ]
    ;

Invocation and Access Rules

ALTER SYSTEM ON DATABASE privilege is required to perform <alter system switch logfile statement>.

Syntax Rules and Parameters

<alter system switch logfile statement>

The database should be in MOUNT or OPEN phase.

<domain name>

It is a name of a member or a group for which the statement is performed.
If it is omitted, it is performed for all groups.

Description

Basically, if the log file in CURRENT state is filled, the log switch automatically occurs. That statement is used to forcibly execute log switch in special circumstances.

Example

ALTER SYSTEM SWITCH LOGFILE;

Compatibility

The SQL standard does not define the concepts of the LOGFILE.

For More Information

Refer to ALTER SYSTEM {MOUNT | OPEN} DATABASE.

ALTER TABLE

Function

It alters the table definition.

Syntax

<alter table statement> ::=
      <alter table physical attribute statement>
    | <rename table statement>
    | <add column definition>
    | <drop column definition>
    | <alter column definition>
    | <rename column statement>
    | <add table constraint definition>
    | <drop table constraint definition>
    | <alter table constraint definition>
    | <rename table constraint statement>
    | <add table supplemental log statement>
    | <drop table supplemental log statement>
    | <rebalance statement>
    | <move shard statement>
    | <merge shards statement>
    | <split shard statement>
    | <rename shard statement>
    | <read { only | write } statement>
    ;

Invocation and Access Rules

One of the following privileges is required to perform <alter table statement>.

Syntax Rules and Parameters

<alter table physical attribute statement>

It alters physical attributes of a table.
For more information, refer to ALTER TABLE name STORAGE.

<rename table statement>

It renames the table.
For more information, refer to ALTER TABLE name RENAME TO.

<add column definition>

It adds columns to the table.
For more information, refer to ALTER TABLE name ADD COLUMN.

<drop column definition>

It drops a column from the table.
For more information, refer to ALTER TABLE name SET UNUSED COLUMN.

<alter column definition>

It alters the column definition in the table.
For more information, refer to ALTER TABLE name ALTER COLUMN.

<rename column statement>

It renames the column in the table.
For more information, refer to ALTER TABLE name RENAME COLUMN.

<add table constraint definition>

It adds constraints to the table.
For more information, refer to ALTER TABLE name ADD CONSTRAINT.

<drop table constraint definition>

It drops the constraints of the table.
For more information, refer to ALTER TABLE name DROP CONSTRAINT.

<alter table constraint definition>

It alters the constraints of the table.
For more information, refer to ALTER TABLE name ALTER CONSTRAINT.

<rename table constraint statement>

It renames the constraints of the table.
For more information, refer to ALTER TABLE name RENAME CONSTRAINT.

<add table supplemental log statement>

It sets to add information to the redo log when the data is altered in the table.
For more information, refer to  ALTER TABLE name ADD SUPPLEMENTAL LOG.

<drop table supplemental log statement>

It sets not to add information to the redo log when the data is altered in the table. 
For more information, refer to ALTER TABLE name DROP SUPPLEMENTAL LOG.

<rebalance statement>

It restores consistency by rebalancing the shard of the table or by synchronizing the broken shard in a cluster environment. 
For more information, refer to ALTER TABLE name REBALANCE.

<move shard statement>

It rebalances a specific shard of a table on a specific cluster group in a cluster environment.
For more information, refer to ALTER TABLE name MOVE SHARD.

<merge shards statement>

It merges specific shards in a table in a cluster environment, then rebalances them.
For more information, refer to  ALTER TABLE name MERGE SHARDS.

<split shard statement>

It rebalances a specific shard of a table on a specific cluster group by splitting the shard in a cluster environment.
For more information, refer to ALTER TABLE name SPLIT SHARD.

<rename shard statement>

It renames a specific shard of a table in cluster environment. 
For more information, refer to ALTER TABLE name RENAME SHARD.

<read { only | write } statement>

It sets READ ( only | write } to a table.
For more information, refer to ALTER TABLE name READ { ONLY | WRITE }.

Description

For more information, refer to the description of each detailed statement.

Example

Refer to the examples of each detailed statement.

Compatibility

The SQL standard does not define the following statements.

ALTER TABLE name ADD COLUMN

Function

It adds a column to the table.

Syntax

<add column definition> ::=
      ALTER TABLE table_name ADD [ COLUMN ] <column definition>
    | ALTER TABLE table_name ADD [ COLUMN ] ( <column definition> [, ...] )
    ;

Invocation and Access Rules

The user should satisfy the following conditions to perform <add column definition>.

Syntax Rules and Parameters

table_name

It is the table name to be altered.
It can define the schema to which the table belongs, such as schema_name.table_name. If schema_name is omitted, the default schema name of the user performing the statement is used.

ADD [ COLUMN ]

The reserved word COLUMN can be omitted.

<column definition>

It defines the column to be added. For more information, refer to <column definition> clause of CREATE TABLE statement.
There should not be columns with the same name in a table.
If DEFAULT clause is specified when defining the column, the default value of all rows are stored in the added column.
If <identity column specification> clause is specified when defining the column, each automatically generated value of all rows is stored in the added column.
If NOT NULL constraint is specified when defining the column, the table should be empty or it should be specified together with DEFAULT or <identity column specification> clause.

( <column definition> [, ...] )

It adds multiple columns.
It lists multiple <column definition> inside the parentheses.

Description

The added column is positioned at the end of the existing columns.
When specifying DEFAULT or <identity column specification> clause, the processing time is increased in proportion to the number of the rows in the table.

Examples

The following is an example of adding a column.

gSQL> ALTER TABLE region ADD COLUMN r_new_comment VARCHAR(152);

Table altered.

The following is an example of adding multiple columns.

gSQL> ALTER TABLE partsupp ADD COLUMN ( 
   ps_retailprice NUMERIC(12,2), 
   ps_acctbal NUMERIC(12,2), ps_mktsegment  CHAR(10) );

Table altered.

The following is an example of adding the identity column and the column including DEFAULT clause.

gSQL> ALTER TABLE region ADD COLUMN ( 
    r_regionkey INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
    r_comment   VARCHAR(152) DEFAULT 'N/A' );

Table altered.

gSQL> SELECT r_regionkey, r_name, r_comment FROM region;

R_REGIONKEY R_NAME                    R_COMMENT
----------- ------------------------- ---------
          1 AFRICA                    N/A      
          2 AMERICA                   N/A      
          3 ASIA                      N/A      
          4 EUROPE                    N/A      
          5 MIDDLE EAST               N/A      

5 rows selected.

The following is an example of adding the column including the deferrable constraint.

gSQL> ALTER TABLE t1 ADD COLUMN ( id INTEGER CONSTRAINT t1_uk UNIQUE DEFERRABLE );

Table altered.

gSQL> COMMIT;

Commit complete.

Compatibility

The SQL standard does not define of adding multiple column definitions.

For More Information

Refer to the followings.

ALTER TABLE name ADD CONSTRAINT

Function

It adds a table constraint.

Syntax

<add table constraint definition> ::=
    ALTER TABLE table_name 
        ADD <table constraint definition>
    ;

Invocation and Access Rules

The user should satisfy the following conditions to perform <add table constraint definition> clause.

Constraints of PRIMARY KEY, UNIQUE in a cluster system should include all sharding keys.

Syntax Rules and Parameters

table_name

It is the table name to be altered.
It can define the schema to which the table belongs, such as schema_name.table_name. If schema_name is omitted, the default schema name of the user performing the statement is used.

<table constraint definition>

It defines the constraint to be added.
NOT NULL constraint can not be added by using ALTER TABLE .. ADD CONSTRAINT statement, and it can be defined by using ALTER TABLE name ALTER COLUMN statement as follows.
ALTER TABLE t1 ALTER COLUMN c1 SET NOT NULL;

For more information, refer to <table constraint definition> clause of CREATE TABLE statement.

Description

When adding the key constraints such as primary key, unique key, the index is automatically created for them.

Examples

The following is an example of adding the primary key constraint to the table.

gSQL> ALTER TABLE t1 ADD PRIMARY KEY ( id );

Table altered.

The following is an example of specifying the constraint name when adding a primary key constraint to the table.

gSQL> ALTER TABLE t1 ADD CONSTRAINT t1_pk PRIMARY KEY ( id );

Table altered.

The following is an example of adding a DEFERRABLE constraint.

gSQL> ALTER TABLE t1 ADD CONSTRAINT t1_uk UNIQUE ( id ) DEFERRABLE INITIALLY DEFERRED;

Table altered.

gSQL> COMMIT;

Commit complete.

Compatibility

SQL standard compatibility

Feature ID

Description

Compatibility

F381

Extended schema manipulation

O

For More Information

Refer to the followings.

ALTER TABLE name ADD GLOBAL SECONDARY INDEX

Function

It creates a global secondary index in a table.

Syntax

<alter table add global secondary index definition> ::=
    ALTER TABLE table_name 
        ADD GLOBAL SECONDARY INDEX
        [ <index attributes> [...] ] [ TABLESPACE tablespace_name ]
    ;

<index attributes> ::=
      <physical attribute clause>
    | STORAGE ( <segment attr clause> [...] )
    | <parallel clause> 

<physical attribute clause> ::=
      PCTFREE integer
    | INITRANS integer
    | MAXTRANS integer

<segment attr clause> ::=
      INITIAL <size_clause>
    | NEXT <size_clause>
    | MINSIZE <size_clause>
    | MAXSIZE <size_clause>

<size clause> ::=
      integer [ K | M | G | T ]

<parallel clause> ::=
      NOPARALLEL
    | PARALLEL [ integer ]

Invocation and Access Rules

<alter table add global secondary index definition> can be defined in a cluster system, and a user should satisfy the following conditions.

Syntax Rules and Parameters

table_name

It is the name of a table in which the index is to be created.
It can define a schema to which the table belongs such as schema_name.table_name.
If schema_name is omitted, the default schema name of the user performing the statement is used.

<physical attribute clause>

It defines the physical attribute information of the index.

<segment attr clause>

It specifies the information about the storage space where the index will be stored.

<size clause>

It specifies the file size in byte. (If it is omitted, the default unit is bytes.)

NOPARALLEL | PARALLEL [ integer ]

It specifies the number of threads to be used when building an index.

TABLESPACE tablespace_name

It specifies the name of the tablespace in which the index is to be stored.

Description

A non-deterministic query requires the global secondary index. LOGGING index and NOLOGGING index have the following trade-offs.

Examples

The following is an example of adding a global secondary index to the table T1.

gSQL> ALTER TABLE T1 ADD GLOBAL SECONDARY INDEX;

Table altered.

gSQL> COMMIT;

Commit complete.
The following is an example of creating a global secondary index as a logging index on the tablespace USER_DATA_TBS of table T1.
gSQL> ALTER TABLE T1 ADD GLOBAL SECONDARY INDEX LOGGING TABLESPACE USER_DATA_TBS;

Table altered.

gSQL> COMMIT;

Commit complete.

The following is an example of creating a global secondary index as a nologging index on the tablespace USER_TEMP_TBS of table T1.

gSQL> ALTER TABLE T1 ADD GLOBAL SECONDARY INDEX NOLOGGING TABLESPACE USER_TEMP_TBS;

Table altered.

gSQL> COMMIT;

Commit complete.

Compatibility

The SQL standard does not define the concepts of the global secondary index.

For More Information

Refer to the followings.

ALTER TABLE name ADD SUPPLEMENTAL LOG

Function

If the primary key exists in the table when table data is altered, it sets to add the primary key value to redo log.

Syntax

<add table supplemental log statement> ::=
    ALTER TABLE table_name 
        ADD SUPPLEMENTAL LOG DATA ( PRIMARY KEY ) COLUMNS
    ;

Invocation and Access Rules

One of the following privileges is required to perform <add table supplemental log statement>.

Syntax Rules and Parameters

table_name

It is the table name to be altered.
It can define the schema to which the table belongs, such as schema_name.table_name. If schema_name is omitted, the default schema name of the user performing the statement is used.
Even when the primary key does not exist in the table, the statement can be executed.

Description

It additionally records SUPPLEMENTAL LOG when executing UPDATE/DELETE on the corresponding TABLE. The recorded SUPPLEMENTAL LOG is used to analyze logs or tools such as CDC.
To record SUPPLEMENTAL LOG of every TABLE, set the property as SUPPLEMENTAL_LOG_DATA_PRIMARY_KEY = YES.

Example

The following is an example of setting to additionally add a primary key value to the redo log when changing the data in the table.

gSQL> ALTER TABLE t1 ADD SUPPLEMENTAL LOG DATA ( PRIMARY KEY ) COLUMNS;

Table altered.

Compatibility

The SQL standard does not cover <add table supplemental log statement>.

For More Information

Refer to ALTER TABLE name DROP SUPPLEMENTAL LOG.

ALTER TABLE name ALTER COLUMN

Function

It alters the column definition.

Syntax

<alter column definition> ::=
    ALTER TABLE table_name 
        ALTER [ COLUMN ] column_name <alter column action>

<alter column action> ::=

      <set column default clause>
    | <drop column default clause>
    | <set column not null clause>
    | <drop column not null clause>
    | <alter column data type clause>
    | <alter identity column specification>
    | <drop identity property clause>    
    ;

<set column default clause> ::=
    SET DEFAULT <default option>

<drop column default clause> ::=
    DROP DEFAULT

<set column not null clause> ::=
    SET [ CONSTRAINT constraint_name ] NOT NULL [ <constraint characteristics> ]


<constraint characteristics> ::=
      [ NOT ] DEFERRABLE [ <constraint check time> ]
    | <constraint check time> [ [ NOT ] DEFERRABLE ]

<constraint check time> ::=
      INITIALLY DEFERRED 
    | INITIALLY IMMEDIATE

<drop column not null clause> ::=
    DROP NOT NULL

<alter column data type clause> ::=
    SET DATA TYPE <data type> 

<alter identity column specification> ::=
     <set identity column generation clause> [ <alter identity column option> ... ]
   | <alter identity column option> ...

<set identity column generation clause> ::=
   SET GENERATED { ALWAYS | BY DEFAULT }

<alter identity column option> ::=
     <alter sequence generator restart option>
   | [ SET ] <basic sequence generator option>

<alter sequence generator restart option> ::=
    RESTART [ WITH integer ]

<basic sequence generator option> ::=
      <sequence generator increment by option>
    | <sequence generator maxvalue option>
    | <sequence generator minvalue option>
    | <sequence generator cycle option>
    | <sequence generator cache option>

<drop identity property clause> ::=
    DROP IDENTITY

Invocation and Access Rules

One of the following privileges is required to performing <alter column definition>.

Syntax Rules and Parameters

table_name

It is the table name to be altered.
It can define the schema to which the table belongs, such as schema_name.table_name. If schema_name is omitted, the default schema name of the user performing the statement is used.

ALTER [ COLUMN ]

The reserved word COLUMN can be omitted.

column_name

It is the column name to be altered.

<set column default clause>

It sets the default value of the column.
It should not be an identity column.
The default value set when using the DEFAULT clause is used in INSERT statement later.
The data type of DEFAULT expression should be compatible with the data type of the column.
If there is insufficient space or the data type is not compatible, an error occurs when using DEFAULT  in INSERT, UPDATE statements.
For more information, refer to <default clause> of CREATE TABLE statement.

<drop column default clause>

It drops the default value of the column.
It should not be an identity column.
If the default value is dropped, NULL is set when using DEFAULT clause in INSERT statement.

<set column not null clause>

For more information about the DEFERRABLE constraint, refer to SET CONSTRAINTS.

<drop column not null clause>

<alter column data type clause>

SET DATA TYPE is a DDL statement which is automatically committed.

The type conversion can be executed among the same family, and it should satisfy the following conditions.

Conversion of character string type

from \ to

CHAR(n)

VARHCAR(n)

LONG VARCHAR

CHAR(m)

X

X

X

VARCHAR(m)

X

n >= m

X

LONG VARCHAR

X

X

O

The conversion of char length unit should satisfy the following condition.

Conversion of character length unit

from \ to

OCTETS

CHARACTERS

OCTETS

O

O

CHARACTERS

X

O

Conversion of binary string type

from \ to

BINARY(n)

VARBINARY(n)

LONG VARBINARY

BINARY(m)

X

X

X

VARBINARY(m)

X

n >= m

X

LONG VARBINARY

X

X

O

Conversion of numeric type

from \ to

SMALLINT

INTEGER

BIGINT

NUMERIC

NUMERIC(q)

NUMERIC(q,t)

NUMBER(q)

NUMBER(q,t)

REAL

DOUBLE PRECISION

FLOAT

FLOAT(q)

NUMBER

SMALLINT

O

O

O

O

q >= 5

q >= 5

t >= 0

(q-t) >= 5

q >= 5

q >= 5

t >= 0

(q-t) >= 5

O

O

O

ddc(q) >= 5

O

INTEGER

X

O

O

O

q >= 10

q >= 10

t >= 0

(q-t) >= 10

q >= 10

q >= 10

t >= 0

(q-t) >= 10

X

O

O

ddc(q) >= 10

O

BIGINT

X

X

O

O

q >= 19

q >= 19

t >= 0

(q-t) >= 19

q >= 19

q >= 19

t >= 0

(q-t) >= 19

X

X

O

ddc(q) >= 19

O

NUMERIC

X

X

X

O

q == 38

q == 38

t == 0

q == 38

q == 38

t == 0

X

X

O

ddc(q) == 38

O

NUMERIC(p)

5 >= p

10 >= p

19 >= p

O

q >= p

q >= p

t >= 0

(q-t) >= p

q >= p

q >= p

t >= 0

(q-t) >= p

8 >= p

16 >= p

O

ddc(q) >= p

O

NUMERIC(p,s)

5 >= p

0 >= s

5 >= (p-s)

10 >= p

0 >= s

10 >= (p-s)

19 >= p

0 >= s 19 >= (p-s)

38 >= p

0 >= s

38 >= (p-s)

q >= p

0 >= s

q >= (p-s)

q >= p

t >= s

(q-t) >= (p-s)

q >= p

0 >= s

q >= (p-s)

q >= p

t >= s

(q-t) >= (p-s)

8 >= p

16 >= p

O

ddc(q) >= p

O

NUMBER(p)

5 >= p

10 >= p

19 >= p

O

q >= p

q >= p

t >= 0

(q-t) >= p

q >= p

q >= p

t >= 0 (q-t) >= p

8 >= p

16 >= p

O

ddc(q) >= p

O

NUMBER(p,s)

5 >= p

0 >= s

5 >= (p-s)

10 >= p 0 >= s 10 >= (p-s)

19 >= p

0 >= s

19 >= (p-s)

38 >= p

0 >= s

3

8 >= (p-s)

q >= p

0 >= s

q >= (p-s)

q >= p

t >= s

(q-t) >= (p-s)

q >= p

0 >= s

q >= (p-s)

q >= p

t >= s (q-t) >= (p-s)

8 >= p

16 >= p

O

ddc(q) >= p

O

REAL

X

X

X

X

X

X

X

X

O

O

O

ddc(q) >= 8

O

DOUBLE PRECISION

X

X

X

X

X

X

X

X

X

O

O

ddc(q) >= 16

O

FLOAT

X

X

X

X

X

X

X

X

X

X

O

ddc(q) == 38

O

FLOAT(p)

X

X

X

X

X

X

X

X

8 >= ddc(p)

16 >= ddc(p)

O

ddc(q) >= ddc(p)

O

NUMBER

X

X

X

X

X

X

X

X

X

-

O

ddc(q) == 38

O

Decimal digit count (ddc) value for the FLOAT (p) is as follows.

Decimal digit count (ddc) value

FLOAT(p)

ddc(p)

1 ~ 3

1

4 ~ 6

2

7 ~ 9

3

10 ~ 13

4

14 ~ 16

5

17 ~ 19

6

20 ~ 23

7

24 ~ 26

8

27 ~ 29

9

30 ~ 33

10

34 ~ 36

11

37 ~ 39

12

40 ~ 43

13

44 ~ 46

14

47 ~ 49

15

50 ~ 53

16

54 ~ 56

17

57 ~ 59

18

60 ~ 63

19

64 ~ 66

20

67 ~ 69

21

70 ~ 73

22

74 ~ 76

23

77 ~ 79

24

80 ~ 83

25

84 ~ 86

26

87 ~ 89

27

90 ~ 93

28

94 ~ 96

29

97 ~ 99

30

100 ~ 103

31

104 ~ 106

32

107 ~ 109

33

110 ~ 113

34

114 ~ 116

35

117 ~ 119

36

120 ~ 123

37

124 ~ 126

38

All numeric types are managed in the same structure, and each numeric type is as same as the following NUMBER (p, s) expression.

NUMBER expressions of the numeric types

Numeric type

NUMBER(p,s) expression

SMALLINT

NUMBER(5,0)

INTEGER

NUMBER(10,0)

BIGINT

NUMBER(19,0)

NUMERIC

NUMBER(38,0)

NUMERIC(p)

NUMBER(p,0)

NUMERIC(p,s)

NUMBER(p,s)

NUMBER(p)

NUMBER(p,0)

NUMBER(p,s)

NUMBER(p,s)

REAL

NUMBER(8,N/A) <= FLOAT(24)

DOUBLE PRECISION

NUMBER(16,N/A) <= FLOAT(53)

FLOAT

NUMBER(38,N/A) <= FLOAT(126)

FLOAT(p)

NUMBER( ddc(p), N/A )

NUMBER

NUMBER(38, N/A )

Native numeric type is as same with as C language numeric type, and it can not be converted to another type.

Conversion of native numeric type

from \ to

NATIVE_SMALLINT

NATIVE_INTEGER

NATIVE_BIGINT

NATIVE_REAL

NATIVE_DOUBLE

NATIVE_SMALLINT

O

X

X

X

X

NATIVE_INTEGER

X

O

X

X

X

NATIVE_BIGINT

X

X

O

X

X

NATIVE_REAL

X

X

X

O

X

NATIVE_DOUBLE

X

X

X

X

O

Conversion of boolean type

from \ to

BOOLEAN

BOOLEAN

O

Conversion of date/time type (TZ: WITH TIME ZONE)

from \ to

DATE

TIME

TIME(g)

TIME TZ

TIME(g) TZ

TIMESTAMP

TIMESTAMP(g)

TIMESTAMP TZ

TIMESTAMP(g) TZ

DATE

O

X

X

X

X

X

X

X

X

TIME

X

O

g >= 6

X

X

X

X

X

X

TIME(f)

X

6 >= f

g >= f

X

X

X

X

X

X

TIME TZ

X

X

X

O

g >= 6

X

X

X

X

TIME(f) TZ

X

X

X

6 >= f

g >= f

X

X

X

X

TIMESTAMP

X

X

X

X

X

O

g >= 6

X

X

TIMESTAMP(f)

X

X

X

X

X

6 >= f

g >= f

X

X

TIMESTAMP TZ

X

X

X

X

X

X

X

O

g >= 6

TIMESTAMP(f) TZ

X

X

X

X

X

X

X

6 >= f

g >= f

Type conversion of INTERVAL YEAR TO MONTH family (If p,q are omitted, then it is 2.)

from \ to

YEAR(q)

MONTH(q)

YEAR(q) TO MONTH

YEAR(p)

q >= p

X

X

MONTH(p)

X

q >= p

X

YEAR(p) TO MONTH

X

X

q >= p

Type conversion of INTERVAL DAY TO TIME family (If p,q are omitted, then it is 2.) (If f,g are omitted, then it is 6.)

from \ to

DAY(q)

HOUR(q)

MINUTE(q)

SECOND(q,g)

DAY(q) TO HOUR

DAY(q) TO MINUTE

DAY(q) TO SECOND(g)

HOUR(q) TO MINUTE

HOUR(q) TO SECOND(g)

MINUTE(q) TO SECOND(g)

DAY(p)

q >= p

X

X

X

X

X

X

X

X

X

HOUR(p)

X

q >= p

X

X

X

X

X

X

X

X

MINUTE(p)

X

X

q >= p

X

X

X

X

X

X

X

SECOND(p,f)

X

X

X

q >= p

g >= f

X

X

X

X

X

X

DAY(p) TO HOUR

X

X

X

X

q >= p

X

X

X

X

X

DAY(p) TO MINUTE

X

X

X

X

X

q >= p

X

X

X

X

DAY(p) TO SECOND(f)

X

X

X

X

X

X

q >= p

g >= f

X

X

X

HOUR(p) TO MINUTE

X

X

X

X

X

X

X

q >= p

X

X

HOUR(p) TO SECOND(f)

X

X

X

X

X

X

X

X

q >= p

g >= f

X

MINUTE(p) TO SECOND(f)

X

X

X

X

X

X

X

X

X

q >= p

g >= f

Conversion of ROWID type

from \ to

ROWID

ROWID

O

<alter identity column specification>

It changes the identity property of the column.
The column should be an identity column.

<drop identity property clause>

It drops the identity property of the column.
The column should be the identity column.

Description

SET NOT NULL clause requires the time for checking null in proportion to the number of table rows.
The following columns do not allow NULL values. In other words, even if DROP NOT NULL clause is performed, NULL is not allowed in the following cases.
The change of the default value using SET DEFAULT clause and the change of the identity property using <alter identity column specification> clause, is applied to INSERT or UPDATE statement which is performed later.

Examples

The following is an example of setting DEFAULT property to the column.

gSQL> ALTER TABLE region ALTER COLUMN r_comment SET DEFAULT 'N/A';

Table altered.

The following is an example of dropping DEFAULT property from the column.

gSQL> ALTER TABLE region ALTER COLUMN r_comment DROP DEFAULT;

Table altered.

The following is an example of setting NOT NULL constraint to the column.

gSQL> ALTER TABLE region ALTER COLUMN r_regionkey SET NOT NULL;

Table altered.

The following is an example of dropping the NOT NULL constraint from the column.

gSQL> ALTER TABLE region ALTER COLUMN r_regionkey DROP NOT NULL;

Table altered.

The following is an example of extending the data type size of the column.

gSQL> ALTER TABLE region ALTER COLUMN r_comment SET DATA TYPE VARCHAR(512);

Table altered.

The following is an example of restarting the next value of the identity column.

gSQL> ALTER TABLE region ALTER COLUMN r_regionkey RESTART;

Table altered.

The following is an example of dropping the identity property from the column.

gSQL> ALTER TABLE region ALTER COLUMN r_regionkey DROP IDENTITY;

Table altered.

Compatibility

The SQL satndards compatibility

Feature ID

Description

Compatibility

F381

Extended schema manipulation

X

F382

Alter column data type

O

F383

Set column not null clause

O

F384

Drop identity property value

O

F385

Drop column generation expression clause

X

F386

Set identity column generation clause

O

S043

Enhanced reference types

X

T174

Identity columns

O

T178

Identity columns: simple restart option

O

For More Information

Refer to the followings.

ALTER TABLE name ALTER CONSTRAINT

Function

It alters the characteristics of the table constraint.

Syntax

<alter table constraint definition> ::=
    ALTER TABLE table_name 
        ALTER <constraint object> <constraint characteristics>
    ;

<constraint object> ::=
      CONSTRAINT constraint_name
    | PRIMARY KEY 
    | UNIQUE ( column_name [, ...] ) 

<constraint characteristics> ::=
      [ NOT ] DEFERRABLE [ <constraint check time> ] 
    | <constraint check time> [ [ NOT ] DEFERRABLE ] 

<constraint check time> ::=
      INITIALLY DEFERRED 
    | INITIALLY IMMEDIATE

Invocation and Access Rules

One of the following privileges is required to perform <alter table constraint definition>.

Cluster does not support the deferrable constraints.

Syntax Rules and Parameters

table_name

It is the table name to be altered.
It can define the schema to which the table belongs, such as schema_name.table_name. If schema_name is omitted, the default schema name of the user performing the statement is used.

<constraint object>

The constraint to be altered is specified as follows.

DEFERRABLE | NOT DEFERRABLE

It alters whether the constraint state is deferrable.

For more information about the deferrable constraints, refer to SET CONSTRAINTS.

INITIALLY IMMEDIATE | INITIALLY DEFERRED

It changes an initial value of the check point for the constraint.

The constraints defined as NOT DEFERRABLE can not be altered to INITIALLY DEFERRED.

Description

For more information about the deferrable constraints, refer to SET CONSTRAINTS.

Example

The following is an example that the constraint t1_uk is set as deferrable and its checking time is set as DEFERRED.

gSQL> ALTER TABLE t1 ALTER CONSTRAINT t1_uk DEFERRABLE INITIALLY DEFERRED;

Table altered.

gSQL> COMMIT;

Commit complete.

Compatibility

The SQL standard does not define the following clauses.

SQL standard compatibility

Feature ID

Description

Compatibility

F492

Optional table constraint enforcement

X

ALTER TABLE name ALTER GLOBAL SECONDARY INDEX

Function

It alters the physical attributes of the global secondary index in the table.

Syntax

<alter table alter global secondary index storage statement> ::=
    ALTER TABLE table_name ALTER GLOBAL SECONDARY INDEX
      <physical attribute clause>
    | [ STORAGE ( <segment attr clause> [...] ) ]
    ;

<physical attribute clause> ::=
      PCTFREE integer
    | INITRANS integer
    | MAXTRANS integer

<segment attr clause> ::=
      INITIAL <size_clause>
    | NEXT <size_clause>
    | MINSIZE <size_clause>
    | MAXSIZE <size_clause>

<size clause> ::=
      integer [ K | M | G | T ]

Invocation and Access Rules

One of the following privileges is required to perform <alter table alter global secondary index storage statement>.

Syntax Rules and Parameters

table_name

It is the name of a table in which the index is to be created.
It can define a schema to which the table belongs such as schema_name.table_name.
If schema_name is omitted, the default schema name of the user performing the statement is used.

<physical attribute clause>

It defines the physical attribute information of the index.

<segment attr clause>

It specifies the information for the index storage space.

<size clause>

It specifies the file size in byte. (If it is omitted, the default unit is bytes.)

Description

A global secondary index is required to enquire a non-deterministic query.

Examples

It alters the maximum available size to be used by a global secondary index in the table T1 to 100 MBytes.

gSQL> ALTER TABLE T1 ALTER GLOBAL SECONDARY INDEX STORAGE( MAXSIZE 100M );

Table altered.

gSQL> COMMIT;

Commit complete.

It alters the INITRANS value and the MAXTRANS value to 2 and 4 each which are to be used by a global secondary index in the table T1

gSQL> ALTER TABLE T1 ALTER GLOBAL SECONDARY INDEX INITRANS 2 MAXTRANS 4;

Table altered.

gSQL> COMMIT;

Commit complete.

Compatibility

The SQL standard does not define the concepts of the global secondary index.

For More Information

Refer to the followings.

ALTER TABLE name DROP CONSTRAINT

Function

It drops a table constraint.

Syntax

<drop table constraint definition> ::=
    ALTER TABLE table_name 
        DROP <constraint object>
        [ <drop behavior> ]
    ;

<constraint object> ::=
      CONSTRAINT constraint_name
    | PRIMARY KEY 
    | UNIQUE ( column_name [, ...] ) 

<drop behavior> ::=
      RESTRICT
    | CASCADE
    | CASCADE CONSTRAINTS

Invocation and Access Rules

One of the following privileges is required to perform <drop table constraint definition>.

Syntax Rules and Parameters

table_name

It is the table name to be altered.
It can define the schema to which the table belongs, such as schema_name.table_name. If schema_name is omitted, the default schema name of the user performing the statement is used.

CONSTRAINT constraint_name

It is the constraint name to be dropped.

PRIMARY KEY

It is the primary key constraint for the table.

UNIQUE( column_name [, ...] )

It is the unique constraint for the columns.

<drop behavior>

When it is omitted, the default value is RESTRICT.
Currently, RESTRICT/CASCADE is operated in the same way.

Description

<drop column not null clause> of ALTER TABLE name ALTER COLUMN is used to drop NOT NULL constraint without using the constraint name.

Examples

The following is an example of dropping a primary key constraint from the table.

gSQL> ALTER TABLE t1 DROP PRIMARY KEY;

Table altered.

The following is an example of dropping the table constraint by specifying the constraint name.

gSQL> ALTER TABLE t1 DROP CONSTRAINT t1_pk;

Table altered.

Compatibility

The SQL standard does not define the following clauses.

SQL standard compatibility

Feature ID

Description

Compatibility

F381

Extended schema manipulation

O

For More Information

Refer to the followings.

ALTER TABLE name DROP GLOBAL SECONDARY INDEX

Function

It drops a global secondary index from the table.

Syntax

<alter table drop global secondary index definition> ::=
    ALTER TABLE table_name 
        DROP GLOBAL SECONDARY INDEX
    ;

Invocation and Access Rules

<alter table drop global secondary index definition> statement can be defined in a cluster system, and the user should satisfy the following conditions.

Syntax Rules and Parameters

table_name

It is the name of a table from which the index is to be dropped.

Description

A global secondary index is required to enquire a non-deterministic query.

Examples

It drops a global secondary index from the table T1.

gSQL> ALTER TABLE T1 DROP GLOBAL SECONDARY INDEX;

Table altered.

gSQL> COMMIT;

Commit complete.

Compatibility

The SQL standard does not define the concepts of the global secondary index.

For More Information

Refer to the followings.

ALTER TABLE name DROP SUPPLEMENTAL LOG

Function

It sets not to leave the primary key information on the redo log when changing the data in the table.

Syntax

<add table supplemental log statement> ::=
    ALTER TABLE table_name 
        DROP SUPPLEMENTAL LOG DATA ( PRIMARY KEY ) COLUMNS
    ;

Invocation and Access Rules

One of the following privileges is required to perform <drop table supplemental log statement>.

Syntax Rules and Parameters

table_name

It is the table name to be altered.
It can define the schema to which the table belongs, such as schema_name.table_name. If schema_name is omitted, the default schema name of the user performing the statement is used.
It should have been set by using ALTER TABLE name ADD SUPPLEMENTAL LOG statement.

Description

For more information, refer to the rules for each syntax.

Example

The following is an example of setting not to leave the primary key information on the redo log when changing the data in the table.

gSQL> ALTER TABLE t1 DROP SUPPLEMENTAL LOG DATA ( PRIMARY KEY ) COLUMNS;

Table altered.

Compatibility

The SQL standard does not cover <drop table supplemental log statement>.

ALTER TABLE name MERGE SHARDS

Function

It merges specific shards in a table in a cluster environment, and rebalances them.

Syntax

<alter table merge shards statement> ::=
    ALTER TABLE table_name MERGE SHARDS <source shard list> 
       INTO dest_shard_name [ <dest shard placement> ]
    ;

<source shard list> ::= 
    source_shard_name [, ...]
  | start_shard_name TO end_shard_name

<dest shard placement> ::=
    AT CLUSTER GROUP dest_group_name

Invocation and Access Rules

It can be performed in the cluster system.

One of the following privileges is required to perform <alter table merge shards statement>.

Syntax Rules and Parameters

table_name

It is the name of a table.
It can define a schema to which the table belongs such as schema_name.table_name. If schema_name is omitted, the default schema name of the user performing the statement is used.
The statement can be performed only when the table is a cluster-specific, and a list shard or a range shard.

<source shard list>

It is the list of original shards to be merged.
The shard specified by a list should exist in the table.

source_shard_name

It is the name of an original shard to be merged.
If the shard does not exist in the table, then the statement can not be performed.

start_shard_name

It is the name of the first shard in the range of merging. 
It is used only in a range shard.

end_shard_name

It is the name of the last shard in the range of merging. 
It is used only in a range shard.

dest_shard_name

It is the name of a target shard.

<dest shard placement>

It is the name of a cluster group in which the target shard is to be placed.
If the corresponding clause is omitted, dest_shard_name should be included in <source shard list>.

Description

It merges specific shards in a specific table, then places them in an arbitrary cluster group.

The following is an error which occurred when merging shards which are not neighboring in a range sharded table in a way of listing.

CREATE TABLE t1( i1 INTEGER ) 
    SHARDING BY RANGE (i1)
    SHARD shard1 VALUES LESS THAN ( 200 )      AT CLUSTER GROUP G1,
    SHARD shard2 VALUES LESS THAN ( 400 )      AT CLUSTER GROUP G2,
    SHARD shard3 VALUES LESS THAN ( MAXVALUE ) AT CLUSTER GROUP G3
;

Table created.

ALTER TABLE t1 MERGE SHARDS shard1, shard3 INTO shard4 AT CLUSTER GROUP G2;

ERR-42000(16488): shards being merged are not adjacent : 
ALTER TABLE t1 MERGE SHARDS shard1, shard3 INTO shard4 AT CLUSTER GROUP G2
                                    *
ERROR at line 1:

Examples

The following is an example of merging shards in a way of listing.

gSQL> ALTER TABLE t1 MERGE SHARDS shard1, shard2, shard3 INTO shard4 AT CLUSTER GROUP G2;

Table altered

The following is an example of merging shards in a way of ranging.

gSQL> ALTER TABLE t1 MERGE SHARDS shard1 TO shard3 INTO shard4 AT CLUSTER GROUP G2;

Table altered

Compatibility

The SQL standard does not define the concepts of the cluster.

For More Information

Refer to the followings.

ALTER TABLE name MOVE SHARD

Function

It rebalances a specific shard of a table, or the entire shard in a specific cluster group to a specific cluster group.

Syntax

<alter table move shard statement> ::=
    ALTER TABLE table_name MOVE SHARD
        { shard_name_list | FROM CLUSTER GROUP src_cluster_group }
        TO CLUSTER GROUP dest_cluster_group [ ONLINE | OFFLINE ]
    ;

Invocation and Access Rules

It can be performed in a cluster system.

One of the following privileges is required to perform <alter table move shard statement>.

Syntax Rules and Parameters

table_name

It is the table name.
It can define a schema to which the table belongs such as schema_name.table_name.
If schema_name is omitted, the default schema name of the user performing the statement is used.
The statement can be performed only when that table is a cluster group specific table.

shard_name_list

It is the shard name list to be rebalanced.
If the shard does not exist in that table, then the statement can not be performed.

src_cluster_group

It is the name of a specific cluster group to be rebalanced.

dest_cluster_group

It is the name of a target cluster group on which the shard of the table is to be rebalanced.
If the shard of the table already exists in the specified cluster group, the statement cannot be performed.

[ ONLINE | OFFLINE ]

It determines whether to allow DML when rebalancing table shard.

Description

It rebalances a specific shard of the table from a specific cluster group to another cluster group.
To drop a specific cluster group, rebalance the shard of the table then  perform the DROP CLUSTER GROUP statement.

To move shards of all tables from a specific cluster group to another cluster group, then perform the ALTER DATABASE MOVE SHARD FROM CLUSTER GROUP TO CLUSTER GROUP statement.

Examples

The following is an example of executing the <alter table move shard statement> statement.

gSQL> ALTER TABLE t1 MOVE SHARD shard1, shard2 TO CLUSTER GROUP g3;

Table altered.

gSQL> ALTER TABLE t1 MOVE SHARD FROM CLUSTER GROUP g1 TO CLUSTER GROUP g3;

Table altered.

Compatibility

The SQL standard does not define the concepts of the cluster.

For More Information

Refer to ALTER DATABASE MOVE SHARD.

ALTER TABLE name READ { ONLY | WRITE }

Function

It sets READ { ONLY | WRITE } in a table.

Syntax

<alter table read { only | write } statement> :==
     ALTER TABLE table_name
         READ { ONLY | WRITE }
     ;

Invocation and Access Rules

One of the following privileges is required to perform <alter table read { only | write } statement>.

Syntax Rules and Parameters

table_name

It is the table name.
It can define a schema to which the table belongs such as schema_name.table_name.
If schema_name is omitted, the default schema name of the user performing the statement is used.

Description

It sets table property to READ { ONLY | WRITE }.

If it is set to READ ONLY, neither SELECT .. FOR UPDATE statement, nor DML/ DDL statement which updates table data can be used. However, DDL statement which does not update the table data is allowed.

Disallowed SQL statements when it is set to READ ONLY

• INSERT, UPDATE, DELETE

• TRUNCATE

• SELECT .. FOR UPDATE

• ALTER TABLE RENAME/DROP COLUMN

• ALTER TABLE SET COLUMN UNUSED


Allowed SQL statements when it is set to READ ONLY

• SELECT

• CREATE/ALTER/DROP INDEX

• ALTER TABLE ADD/ALTER COLUMN

• ALTER TABLE ADD/ALTER/RENAME/DROP CONSTRAINT

• ALTER TABLE for physical property changes

• ALTER TABLE DROP UNUSED COLUMNS

• ALTER TABLE RENAME TO

• DROP TABLE

• ALTER TABLE ADD/DROP SUPPLEMENTAL LOG

• LOCK TABLE

Examples

The following is an example of executing <alter table read { only | write } statement>.

gSQL> ALTER TABLE t1 READ ONLY;

Table altered.

gSQL> ALTER TABLE t1 READ WRITE;

Table altered.

Compatibility

The SQL standard does not define <alter table read { only | write } statement>.

For More Information

Refer to ALTER TABLE.

ALTER TABLE name REBALANCE

Function

It rebalances the shard in a table.

Syntax

<alter table rebalance statement> ::=
    ALTER TABLE table_name REBALANCE [ ONLINE | OFFLINE ]
    ;

Invocation and Access Rules

It can be performed in a cluster system.
One of the following privileges is required to perform <alter table rebalance statement>.

Syntax Rules and Parameters

table_name

It is the table name.
It can define the schema to which the table belongs, such as schema_name.table_name. If schema_name is omitted, the default schema name of the user performing the statement is used.

[ ONLINE | OFFLINE ]

It determines whether to allow DML when rebalancing table shard.

Description

It does not rebalance shards in a table when adding a cluster member or a cluster group by using the following statements.

To rebalance the shards of a table in the added cluster group and the cluster member, perform the <alter table rebalance statement> statement. The operation succeeds without a separate rebalancing if the shard of the table is already rebalanced.

To rebalance shards in all tables, perform the ALTER DATABASE REBALANCE statement.

Examples

The following is an example of executing the <alter table rebalance statement> statement.

gSQL> ALTER TABLE t1 REBALANCE;

Table altered.

Compatibility

The SQL standard does not define the concepts of the cluster.

ALTER TABLE name REBALANCE EXCLUDE CLUSTER GROUP cluster_group_list

Function

It rebalances the shard of the table not to include a shard in a specific cluster group.

Syntax

<alter table rebalance exclude cluster group statement> ::=
    ALTER TABLE table_name REBALANCE 
        EXCLUDE CLUSTER GROUP cluster_group_list [ ONLINE | OFFLINE ]
    ;

Invocation and Access Rules

It can be performed in a cluster system.

One of the following privileges is required to perform <alter table rebalance exclude cluster group statement>.

Syntax Rules and Parameters

table_name

It is the table name.
It can define a schema to which the table belongs such as schema_name.table_name.
If schema_name is omitted, the default schema name of the user performing the statement is used.
The statement can be performed only when that table is a cluster-wide table.

cluster_group_list

It is a list of the cluster group which does not include a shard of a table.
If the cluster group to be excluded from the rebalancing is the entire group, the statement can not be performed.

[ ONLINE | OFFLINE ]

It determines whether to allow DML when rebalancing table shard.

Description

It excludes a specific cluster group and rebalances the shard of the table.
If the shard of the table does not exist in that cluster group, the operation succeeds without a separate rebalancing. 
It rebalances the shard based on the cluster group in which the shard of the table is located.
To drop a specific cluster group, rebalance the shard of the table and perform  DROP CLUSTER GROUP statement.
To rebalance the shard excluding a cluster group from all tables, perform the  ALTER DATABASE REBALANCE EXCLUDE CLUSTER GROUP statement.

Examples

The following is an example of executing the <alter table rebalance exclude cluster group statement> statement.

gSQL> ALTER TABLE t1 REBALANCE EXCLUDE CLUSTER GROUP g3;

Table altered.

Compatibility

The SQL standard does not define the concepts of the cluster.

ALTER TABLE name REBUILD GLOBAL SECONDARY INDEX

Function

It rebuilds a global secondary index

Syntax

<rebuild global secondary index statement> ::=
    ALTER TABLE table_name REBUILD GLOBAL SECONDARY INDEX
        [ ONLINE | OFFLINE ]
        [ <index attributes> [...] ]
        [ TABLESPACE tablespace_name ]
    ;

<index attributes> ::=
      <physical attribute clause>
    | STORAGE ( <segment attr clause> [...] )
    | <parallel clause> 

<physical attribute clause> ::=
      PCTFREE integer
    | INITRANS integer
    | MAXTRANS integer

<segment attr clause> ::=
      INITIAL <size_clause>
    | NEXT <size_clause>
    | MINSIZE <size_clause>
    | MAXSIZE <size_clause>

<size clause> ::=
      integer [ K | M | G | T ]

<parallel clause> ::=
      NOPARALLEL
    | PARALLEL [ integer ]

Invocation and Access Rules

The user should satisfy the following conditions to perform <rebuild global secondary index statement>.

Syntax Rules and Parameters

table_name

It is the table name on which the index is to be rebuilt. 
It can define the schema to which the table belongs, such as schema_name.table_name. If schema_name is omitted, the default schema name of the user performing the statement is used.

[ ONLINE | OFFLINE ]

It determines whether to allow DML on the table when rebuilding the index.

<physical attribute clause>

It defines the physical attribute information of an index.

<segment attr clause>

It specifies the information for the index storage space.

<size clause>

It specifies the file size in bytes. (If the unit is omitted, the default value is bytes.)

NOPARALLEL | PARALLEL [ integer ]

It specifies the number of threads to be used when rebuilding an index.

TABLESPACE tablespace_name

It specifies the name of the tablespace in which the index is to be rebuilt.

Description

Examples

Rebuild the global secondary index in the table T1.

gSQL> ALTER TABLE T1 REBUILD GLOBAL SECONDARY INDEX;

Alter the tablespace and logging settings of the global secondary index in the table T1.

gSQL> ALTER TABLE T1 REBUILD GLOBAL SECONDARY INDEX TABLESPACE MEM_DATA_TBS;

gSQL> ALTER TABLE T1 REBUILD GLOBAL SECONDARY INDEX TABLESPACE MEM_TEMP_TBS;

Compatibility

The SQL standard does not cover the concepts of the global secondary index.

For More Information

Refer to the followings.

ALTER TABLE name RENAME COLUMN

Function

It renames the table column.

Syntax

<rename column statement> ::=
    ALTER TABLE table_name 
        RENAME COLUMN old_column_name TO new_column_name
    ;

Invocation and Access Rules

One of the following privileges is required to perform <rename column statement>.

Syntax Rules and Parameters

table_name

It is the table name to be altered.
It can define the schema to which the table belongs, such as schema_name.table_name. If schema_name is omitted, the default schema name of the user performing the statement is used.

old_column_name

It is the old column name to be altered.

new_column_name

It is the new column name to be altered.
The same column name should not exist in a table.

Description

Even when the column name is altered it does not require the object change such as index, constraint which is generated based on the previous column.

Example

The following is an example of exchanging the names of two columns, col_1 and col_2.

gSQL> ALTER TABLE t1 RENAME COLUMN col_1 TO col_temp;

Table altered.

gSQL> ALTER TABLE t1 RENAME COLUMN col_2 TO col_1;

Table altered.

gSQL> ALTER TABLE t1 RENAME COLUMN col_temp TO col_2;

Table altered.

gSQL> COMMIT;

Commit complete.

Compatibility

The SQL standard does not define <rename column statement>.

For More Information

Refer to the followings.

ALTER TABLE name RENAME CONSTRAINT

Function

It renames the table constraints.

Syntax

<rename table constraint statement> ::=
    ALTER TABLE table_name 
        RENAME <constraint object> TO new_constraint_name
    ;

<constraint object> ::=
      CONSTRAINT constraint_name
    | PRIMARY KEY 
    | UNIQUE ( column_name [, ...] )

Invocation and Access Rules

One of the following privileges is required to perform <rename table constraint statement>.

Syntax Rules and Parameters

table_name

It is the table name to be altered.
It can define the schema to which the table belongs, such as schema_name.table_name. If schema_name is omitted, the default schema name of the user performing the statement is used.

<constraint object>

The existing name of the constraint to be altered is specified as follows.

new_column_name

It is the new name of a constraint to be altered.

Description

The index name which was automatically created with a key constraint such as primary key, unique key is not altered. Use ALTER INDEX name RENAME TO statement to rename the index.

Examples

The following is an example of renaming the primary key constraint of the table.

gSQL> ALTER TABLE t1 RENAME PRIMARY KEY TO pk_t1;

Table altered.

The following is an example of renaming the table constraint by specifying the constraint name.

gSQL> ALTER TABLE t1 RENAME CONSTRAINT pk_t1 TO t1_pk;

Table altered.

Compatibility

The SQL standard does not define the <rename table constraint statement> statement.

For More Information

Refer to the followings.

ALTER TABLE name RENAME SHARD

Function

It renames a specific shard of a table in cluster environment.

Syntax

<alter table rename shard statement> ::=
    ALTER TABLE table_name 
        RENAME SHARD shard_name TO new_shard_name
    ;

Invocation and Access Rules

It can be performed in a cluster system.
One of the following privileges is required to perform <alter table rename shard statement>.

Syntax Rules and Parameters

table_name

It is the table name to be altered.
It can define a schema to which the table belongs such as schema_name.table_name.
If schema_name is omitted, the default schema name of the user performing the statement is used.

shard_name

It is the existing name of a shard to be altered.
If the shard does not exist in that table, then the statement can not be performed.

new_shard_name

It is the new name of a shard to be altered. 
The same shard name should not exist in the table.

Description

It alters the name of a specific shard of a hash, a range, or a list table. This statement can not be performed for a cloned table.

Examples

The following is an example of executing <alter table rename shard statement> statement.

gSQL> ALTER TABLE t_range RENAME SHARD r_01 TO r_new_01;

Table altered.

gSQL> ALTER TABLE t_list RENAME SHARD l_01 TO l_new_01;

Table altered.

gSQL> ALTER TABLE t_hash RENAME SHARD shard_000000 TO h_new_00;

Table altered.

gSQL> COMMIT;

Commit complete.

Compatibility

The SQL standard does not define the concepts of the cluster.

For More Information

Refer to the followings.

ALTER TABLE name RENAME TO

Function

It renames the table.

Syntax

<rename table statement> ::=
    ALTER TABLE table_name 
        RENAME TO new_table_name
    ;

Invocation and Access Rules

One of the following privileges is required to perform <rename table statement>.

Syntax Rules and Parameters

table_name

It is the existing name of the table.
It can define the schema to which the table belongs, such as schema_name.table_name. If schema_name is omitted, the default schema name of the user performing the statement is used.

new_table_name

It is a new name of the table.
The same table name should not exist in the schema.

Description

Even when the table is renamed, the object referring to the table such as index, constraint does not need to be renamed.

Example

The following is an example of exchanging the name of the two tables t1, t2.

gSQL> ALTER TABLE t1 RENAME TO t_temp;

Table altered.

gSQL> ALTER TABLE t2 RENAME TO t1;

Table altered.

gSQL> ALTER TABLE t_temp RENAME TO t2;

Table altered.

gSQL> COMMIT;

Commit complete.

Compatibility

The SQL standard does not define <rename table statement>.

For More Information

Refer to ALTER TABLE.

ALTER TABLE name SET UNUSED COLUMN

Function

It drops a table column.

Syntax

<drop column definition> ::=
    ALTER TABLE table_name <drop column clause>
    ;

<drop column clause> ::=
      SET UNUSED [ COLUMN ] <column_name_list> [ <drop behavior> ]

<column name list> ::=
      column_name
    | ( column_name [, ...] )

<drop behavior> ::=
      RESTRICT
    | CASCADE
    | CASCADE CONSTRAINTS

Invocation and Access Rules

One of the following privileges is required to perform <drop column definition>.

Syntax Rules and Parameters

table_name

It is the table name to be altered.
It can define the schema to which the table belongs, such as schema_name.table_name. If schema_name is omitted, the default schema name of the user performing the statement is used.

SET UNUSED [ COLUMN ]

It sets the column not to be used.

column_name_list

One or more column names to be dropped.

column_name

It is the column name to be dropped.
It also drops the constraints and indexes which use the column.

drop behavior

When it is omitted, the default value is RESTRICT.
Currently, RESTRICT/CASCADE is operated in the same way.

Description

SET UNUSED COLUMN does not delete the data physically, so it ensures consistent performance regardless of the number of the rows.

Example

The following is an example of setting the column not to be used.

gSQL> ALTER TABLE t1 SET UNUSED COLUMN ( addr );

Table altered.

Compatibility

The SQL standard does not define the following clauses.

SQL standard compatibility

Feature ID

Description

Compatibility

F033

ALTER TABLE statement: DROP COLUMN clause

X

For More Information

Refer to the followings.

ALTER TABLE name SPLIT SHARD

Function

It rebalances a specific shard of a table by splitting it in a cluster environment.

Syntax

<alter table split shard statement> ::=
    ALTER TABLE table_name SPLIT SHARD source_shard_name
        INTO ( <split shard placement> [, ...] )
    ;

<split shard placement> ::=
    <split shard bound def> AT CLUSTER GROUP dest_group_name

<split shard bound def> ::=
    <split list shard def>
  | <split range shard def>

<split list shard def> :=
    SHARD dest_shard_name VALUES IN ( <split list value clause> )

<split list value clause> :=
    <split list value> [, ...]

<split list value> :=
    constant
  | NULL

<split range shard def> :=
    SHARD dest_shard_name VALUES LESS THAN ( <split range value clause> )

<split range value clause> :=
    <split range value> [, ...]

<split range value> :=
    constant

Invocation and Access Rules

It can be performed in a cluster system.
One of the following privileges is required to perform <alter table split shard statement>.

Syntax Rules and Parameters

table_name

It is the table name.
It can define a schema to which the table belongs such as schema_name.table_name.
If schema_name is omitted, the default schema name of the user performing the statement is used.
The statement can be performed only when that table is a cluster group specific table, and when the shard is a list shard or a range shard.

source_shard_name

It is the name of an original shard to be split. 
If the shard does not exist in that table, the statement can not be performed.

<split shard placement>

It defines the target shard to which the original shard is rebalanced by splitting.

<split shard bound def>

It defines the bound of a target shard to be split.

It can be defined as one of two following bound defs.

<split list shard def>

It defines a split shard bound for a list shard.

<split range shard def>

It defines a split shard bound for a range shard.

dest_group_name

It is the name of a cluster group in which the split shard is to be rebalanced.

Description

It splits a specific shard of a specific table and rebalances it to a random cluster group.
This is used to distribute records and loads by splitting the shards when records corresponding to a specific shard is too much or when a specific group member is overloaded.

Examples

The following is an example of executing the <alter table split shard statement> statement.

gSQL> ALTER TABLE t1 SPLIT SHARD shard1 INTO ( SHARD shard11 VALUES IN ( 11 ) AT CLUSTER GROUP G2 );

Table altered.

gSQL> ALTER TABLE t1 SPLIT SHARD shard1 INTO ( SHARD shard11 VALUES LESS THAN ( 11 ) AT CLUSTER GROUP G2 );


Table altered.

Compatibility

The SQL standard does not define the concepts of the cluster.

For More Information

Refer to the followings.

ALTER TABLE name STORAGE

Function

It alters physical attributes of a table.

Syntax

<alter table physical attribute statement> ::=
    ALTER TABLE table_name 
      [ <physical attribute clause> ]
    | [ STORAGE ( <segment attr clause> [...] ) ]
    ;

<physical attribute clause> ::=
      PCTFREE integer
    | PCTUSED integer
    | INITRANS integer
    | MAXTRANS integer

<segment attr clause> ::=
    NEXT <size_clause>
    | MINSIZE <size_clause>
    | MAXSIZE <size_clause>

<size clause> ::=
      integer [ K | M | G | T ]

Invocation and Access Rules

One of the following privileges is required to perform <alter table physical attribute statement>.

Syntax Rules and Parameters

table_name

It is the table name to be altered.
It can define the schema to which the table belongs, such as schema_name.table_name. If schema_name is omitted, the default schema name of the user performing the statement is used.

<physical attribute clause>

It alters the physical attribute of a page which configures the table.
It is not applied to the already allocated page, but is applied to the newly allocated page.
For more information, refer to <table physical attribute clause> of CREATE TABLE.

<segment attr clause>

It alters the physical attribute of the extent configuring the segment. It is not applied to the already allocated extent but is applied to the newly allocated extent.

Description

For more information, refer to the rules for each syntax.

Example

The following is an example of changing the physical attribute of the table.

gSQL> ALTER TABLE t1 PCTFREE 10 PCTUSED 40 STORAGE ( NEXT 10M  MAXSIZE  100M );

Table altered.

Compatibility

The SQL standard does not define the physical property of a table.

For More Information

Refer to ALTER TABLE.

ALTER TABLESPACE

Function

It alters the tablespace definition.

Syntax

<alter tablespace statement> ::=
      <rename tablespace statement>
    | <backup tablespace statement>
    | <on/offline tablespace statement>
    | <add file statement>
    | <drop file statement>
    | <rename datafile statement>
    ;

Invocation and Access Rules

ALTER TABLESPACE privilege is required to perform <alter tablespace statement>.

Syntax Rules and Parameters

<rename tablespace statement>

It renames the tablespace.
For more information, refer to ALTER TABLESPACE name RENAME TO statement.

<backup tablespace statement>

It backs up the tablespace.
For more information, refer to ALTER TABLESPACE name BACKUP statement.

<on-offline tablespace statement>

It changes all files in the tablespace to the online state or offline state.
For more information, refer to ALTER TABLESPACE name [ONLINE|OFFLINE] statement.

<add file statement>

It adds a file to the tablespace.
For more information, refer to ALTER TABLESPACE name ADD [DATAFILE|MEMORY] statement.

<drop file statement>

It drops a file from the tablespace.
For more information, refer to ALTER TABLESPACE name DROP [DATAFILE|MEMORY] statement.

<rename datafile statement>

It renames the datafile in the data tablespace. 
For more information, refer to ALTER TABLESPACE name RENAME DATAFILE statement.

Description

Unlike other Data Definition Language (DDL), ALTER TABLESPACE statement is not allowed to ROLLBACK, and its transaction is automatically committed after executing the statement.

Example

Refer to the examples of each detailed statement.

Compatibility

The SQL standard does not define the concepts of the tablespace.

For More Information

Refer to the followings.

ALTER TABLESPACE name ADD [DATAFILE|MEMORY]

Function

It extends the space of the tablespace.

Syntax

<add space statement> ::=
    ALTER TABLESPACE tablespace_name ADD <space specification>
        [AT <domain name>]
    ;

<space specification> ::=
      MEMORY <memory clause> [, ...]
    | DATAFILE <add datafile clause> [, ...]

<size clause> ::=
    integer [ K | M | G | T ]

<memory clause> 
     'memory_name' { SIZE <size clause> }

<add datafile clause> ::=
     'filename' 
        { SIZE <size clause> | REUSE | SIZE <size clause> REUSE }

Invocation and Access Rules

ALTER TABLESPACE ON DATABASE privilege is required to perform <add space statement>.

Syntax Rules and Parameters

tablespace_name

It is the tablespace name to be altered.

<file specification>

The following syntax should be used according to the tablespace type.

<add datafile clause>

It defines the memory datafile to be added.

<memory clause>

For more information, refer to  <memory clause> of CREATE MEMORY TEMPORARY TABLESPACE statement.

<domain name>

It is a name of a member or a group for which the statement is performed.
If it is omitted, it is performed for all groups.

Description

For more information, refer to the rules for each syntax.

Example

The following is an example of adding datafile to the tablespace.

gSQL> ALTER TABLESPACE space1 ADD DATAFILE 'test_file_a2.dbf' SIZE 10M REUSE;

Tablespace altered.

Compatibility

The SQL standard does not define the concepts of the tablespace.

For More Information

Refer to the followings.

ALTER TABLESPACE name BACKUP

Function

It switches the tablespace to backup enabled state and backup disabled state to perform backup.

Syntax

<backup tablespace statement> ::=
      <tablespace begin backup statement>
    | <tablespace end backup statement>
    | <tablespace incremental backup statement>    
    ;

<tablespace begin backup statement> ::=
    ALTER TABLESPACE tablespace_name BEGIN BACKUP [AT <domain_name>]
    ;

<tablespace end backup statement> ::=
    ALTER TABLESPACE tablespace_name END BACKUP [AT <domain_name>]
    ;

<tablesapce incremental backup statement> ::=
    ALTER TABLESPACE tablespace_name
        BACKUP INCREMENTAL <incremental backup option> [AT <domain_name>]    ;

<incremental backup option> ::=
      LEVEL integer [ CUMULATIVE | DIFFERENTIAL ]

Invocation and Access Rules

ALTER TABLESPACE ON DATABASE privilege is required to perform <backup space statement>.

Syntax Rules and Parameters

<tablespace begin backup statement>

It sets the tablespace to the backup enabled state.

tablespace_name

It is the tablespace name whose backup state is to be switched.

<tablespace end backup statement>

It sets the tablespace to the backup disabled state.

<tablesapce incremental backup statement>

It performs the incremental backup of the tablespace.
The database is in OPEN phase and it should be operated in ARCHIVELOG mode.

<incremental backup option>

<domain name>

It is a name of a member or a group for which the statement is performed.
If it is omitted, it is performed for all groups.

Description

It backs up the datafiles which are created in the tablespace. A full backup of the tablespace begins with BEGIN BACKUP, and copies the datafiles by OS file copy and ends with END BACKUP. The incremental backup file is created in the path set by BACKUP_DIR 1 property using a single statement.

Examples

The following is an example of setting the full backup state to 'ACTIVE' for the tablespace DICTIONARY_TBS.

ALTER TABLESPACE DICTIONARY_TBS BEGIN BACKUP;

The following is an example of setting the full backup state to 'INACTIVE' for the tablespace DICTIONARY_TBS.

ALTER TABLESPACE DICTIONARY_TBS END BACKUP;

The following is an example of generating the LEVEL 0 incremental backup of the tablespace DICTIONARY_TBS.

ALTER TABLESPACE DICTIONARY_TBS BACKUP INCREMENTAL LEVEL 0;

Compatibility

The SQL standard does not define the concepts of the tablespace.

For More Information

Refer to the followings.

ALTER TABLESPACE name DROP [DATAFILE|MEMORY]

Function

It reduces the space of the tablespace.

Syntax

<drop space statement> ::=
    ALTER TABLESPACE tablespace_name DROP <file specification>
    [ AT <domain name> ]
    ;

<file specification> ::=
      DATAFILE 'filename' 
    | MEMORY 'memory_name'

Invocation and Access Rules

ALTER TABLESPACE ON DATABASE privilege is required to perform <drop space statement>.

Syntax Rules and Parameters

tablespace_name

It is the tablespace name to be altered.

<file specification>

The following syntax should be used according to the tablespace type.

The file of OFFLINE tablespace can not be dropped.

The first file of the tablespace can not be dropped.

The data file which has been used once can not be dropped.

<domain name>

It is a name of a member or a group for which the statement is performed.
If it is omitted, it is performed for all groups.

Description

For more information, refer to the rules for each syntax.

Example

The following is an example of dropping the file from the tablespace.

gSQL> ALTER TABLESPACE space1 DROP DATAFILE 'test_file_f2.dbf';

Tablespace altered.

Compatibility

The SQL standard does not define the concepts of the tablespace.

For More Information

Refer to the followings.

ALTER TABLESPACE name [ONLINE|OFFLINE]

Function

It alters the tablespace status.

Syntax

<on/off tablespace statement> ::=
    ALTER TABLESPACE tablespace_name { ONLINE | OFFLINE [ NORMAL | IMMEIDATE ] }
    [ AT <domain name> ]
    ;

Invocation and Access Rules

ALTER TABLESPACE ON DATABASE privilege is required to perform <on/off tablespace statement>.

Syntax Rules and Parameters

ONLINE

It alters the tablespace status in OFFLINE state to ONLINE state.

OFFLINE NORMAL

It alters the tablespace status in ONLINE state to OFFLINE state.
The media recovery is not required in ONLINE state because the tablespace which was altered to OFFLINE state is in consistent state.

OFFLINE NORMAL is not allowed in MOUNT phase.

(However, if the previous instance is terminated by \SHUTDOWN NORMAL, OFFLINE NORMAL is allowed.)

OFFLINE IMMEDIATE

It alters the tablespace status in ONLINE state to OFFLINE state.
The media recovery is required in ONLINE state because the tablespace which was altered to OFFLINE state is in inconsistent state.

The SYSTEM tablespace can not be altered to OFFLINE state.

OFFLINE IMMEDIATE requires the media recovery, so it can be performed only in ARCHIVELOG mode.

<domain name>

It is a name of a member or a group for which the statement is performed.
If it is omitted, it is performed for all groups.

Description

For more information, refer to the rules for each syntax.

Examples

The following is an example of setting the tablespace to OFFLINE.

gSQL> ALTER TABLESPACE space1 OFFLINE;

Tablespace altered.

The following is an example of that OFFLINE NORMAL for the tablespace fails in MOUNT phase.

gSQL> ALTER TABLESPACE space1 OFFLINE;

ERR-42000(16290): OFFLINE NORMAL is only allowed if the database is in OPEN phase : 
ALTER TABLESPACE space1 OFFLINE
                 *
ERROR at line 1:

gSQL> ALTER TABLESPACE space1 OFFLINE NORMAL;

ERR-42000(16290): OFFLINE NORMAL is only allowed if the database is in OPEN phase : 
ALTER TABLESPACE space1 OFFLINE NORMAL
                 *
ERROR at line 1:

Compatibility

The SQL standard does not define the concepts of the tablespace.

For More Information

Refer to the followings.

ALTER TABLESPACE name RENAME DATAFILE

Function

It renames the datafiles that configure the tablespace.

Syntax

<rename datafile statement> ::=
    ALTER TABLESPACE tablespace_name RENAME DATAFILE <filename_list> TO <filename_list>
    ;

    <filename_list> ::= 
        'filename' [, ...]

Invocation and Access Rules

ALTER TABLESPACE ON DATABASE privilege is required to perform <rename datafile statement>.

ONLINE tablespace file can not be altered when it is in TDS mode and the database is in OPEN phase. (Except for the temporary memory tablespace.)

The file should exist even after the alteration.

Syntax Rules and Parameters

tablespace_name

It is the tablespace name to be altered.

'filename'

The memory temporary tablespace is 'memory_name' and the other kinds of tablespace is 'filename'.

<domain name>

It is a name of a member or a group for which the statement is performed.
If it is omitted, it is performed for all groups.

Description

The tablespace status determines whether the operation can be performed.

Example

The following is an example of renaming 'test.dbf' to 'test1.dbf'.

gSQL> ALTER TABLESPACE TEST_TBS RENAME DATAFILE 'test.dbf' TO 'test1.dbf';

Tablespace altered.

Compatibility

The SQL standard does not define the concepts of the tablespace.

For More Information

Refer to the followings.

ALTER TABLESPACE name RENAME TO

Function

It renames the tablespace.

Syntax

<rename tablespace statement> ::=
    ALTER TABLESPACE tablespace_name RENAME TO <new_tablespace_name>
    ;

Invocation and Access Rules

ALTER TABLESPACE ON DATABASE privilege required to perform <rename space statement>.

Syntax Rules and Parameters

tablespace_name

It is a name of the old tablespace.

new_tablespace_name

It is a name of the new tablespace.

Description

Even when the tablespace is renamed, the table or index which was already created in the existing tablespace does not need to be renamed.

Example

The following is an example of renaming the tablespace.

gSQL> ALTER TABLESPACE space1 RENAME TO space2;

Tablespace altered.

Compatibility

The SQL standard does not define the concepts of the tablespace.

For More Information

Refer to ALTER TABLESPACE.

ALTER USER

Function

It alters the user definition of the database.

Syntax

<alter user statement> ::=
      ALTER USER user_identifier <alter user action>
    | ALTER USER PUBLIC <alter schema path>
    ;

<alter user action> ::=
      <alter password>
    | <alter profile>
    | <password expire>
    | <account lock>
    | <alter default tablespace>
    | <alter temporary tablespace>
    | <alter schema path>

<alter password> ::=
    IDENTIFIED BY new_password [ REPLACE old_password ]

<alter profile> ::=
    PROFILE { profile_name | DEFAULT | NULL }

<password expire> ::=
    PASSWORD EXPIRE

<account lock> ::=
    ACCOUNT { LOCK | UNLOCK }

<alter default tablespace> ::=
    DEFAULT TABLESPACE tablespace_name

<alter temporary tablespace> ::=
    TEMPORARY TABLESPACE tablespace_name

<alter schema path> ::=
    SCHEMA PATH ( { schema_name | CURRENT PATH } [, ...] )

Invocation and Access Rules

ALTER USER ON DATABASE privilege is required to perform <alter user statement>.
However, <alter password> can be performed without any privilege, when the user and user_identifier are identical.

Syntax Rules and Parameters

user_identifier

It is the username to be altered.

<alter password>

It alters the user's password.

<alter profile>

It alters the profile for the password management policy.

<password expire>

It expires the user's password.

<account lock>

<alter default tablespace>

It alters the user's default tablespace.
The tablespace_name should be a data tablespace.

<alter temporary tablespace>

It alters the user's temporary tablespace.
The tablespace_name should be a temporary tablespace.

<alter index tablespace>

It alters an index tablespace of the user.

<alter schema path>

It alters the user's schema access path.
If the schema is not specified in user's SQL statement, the schema access path is determined in the schema order for the naming resolution of the object.
If the schema name is as same as another schema which is previously listed, it is not applied.
The following is an example of objects existing in a schema when performing ALTER USER u1 SCHEMA PATH ( u1, s2, public );  statement.

Schema name

u1

s2

public

-

t1

-

t1

-

-

t2

-

-

-

-

t3

The object name whose schema name is not specified when the user u1 executes the schema is interpreted by the SCHEMA PATH as follows.

CURRENT PATH

It is the current user's schema path.
A new schema path can be added using CURRENT PATH maintaining the existing schema path as follows.

ALTER USER PUBLIC <alter schema path>

It alters the schema path of PUBLIC account.
The schema path of PUBLIC account is included in every user's schema path.
The initial schema path which is allocated to PUBLIC account is as follows.

Description

For more information, refer to the rules for each syntax.

Examples

The following is an example of altering the user's password.

gSQL> ALTER USER u1 IDENTIFIED BY new_password;

User altered.

The following is an example of allocating the profile to the user.

gSQL> ALTER USER u1 PROFILE prof1;

User altered.

gSQL> COMMIT;

Commit complete.

The following is an example of dropping the user's profile.

gSQL> ALTER USER u1 PROFILE NULL;

User altered.

gSQL> COMMIT;

Commit complete.

The following is an example of expiring the user's password.

gSQL> ALTER USER u1 PASSWORD EXPIRE;

User altered.

gSQL> COMMIT;

Commit complete.

The following is an example of unlocking the user's account.

gSQL> ALTER USER u1 ACCOUNT UNLOCK;

User altered.

gSQL> COMMIT;

Commit complete.

The following is an example of altering the user's DEFAULT TABLESPACE.

gSQL> ALTER USER u1 DEFAULT TABLESPACE mem_data_tbs;

User altered.

The following is an example of altering the user's TEMPORARY TABLESPACE.

gSQL> ALTER USER u1 TEMPORARY TABLESPACE mem_temp_tbs;

User altered.

The following is an example of altering the user's INDEX TABLESPACE.

gSQL> ALTER USER u1 INDEX TABLESPACE mem_temp_tbs;

User altered.

The following is an example of altering the user's schema path.

gSQL> ALTER USER u1 SCHEMA PATH ( s1, CURRENT PATH );

User altered.

Compatibility

SQL standard covers the concepts of a user, but it does not define the SQL statements associated with creating, altering, dropping a user.

For More Information

Refer to the followings.

ALTER VIEW

Function

It alters the view definition.

Syntax

<alter view statement> ::=
    ALTER VIEW view_name <alter view action>
    ;

<alter view action> ::=
    COMPILE

Invocation and Access Rules

One of the following privileges is required to perform <alter view statement>.

Syntax Rules and Parameters

view_name

It is the view name to be altered.
It can define the schema to which the view belongs, such as schema_name.view_name. If schema_name is omitted, the default schema name of the user performing the statement is used.

COMPILE

It compiles the view again.
COMMENT which is given to the view column is initialized.

Description

When the table or the view which is referenced by the view is altered or dropped, then it affects that view.
This information can be retrieved from INFORMATION_SCHEMA.VIEWS.

Example

The following is an example of compiling the view which is affected by the table change referenced by that view.

gSQL> SELECT TABLE_NAME, IS_AFFECTED 
        FROM INFORMATION_SCHEMA.VIEWS 
       WHERE TABLE_SCHEMA = 'PUBLIC'
         AND TABLE_NAME = 'V1';

TABLE_NAME IS_AFFECTED
---------- -----------
V1         TRUE       

1 row selected.


gSQL> ALTER VIEW v1 COMPILE;

View altered.

COMMIT;

Commit complete.

gSQL> SELECT TABLE_NAME, IS_AFFECTED 
        FROM INFORMATION_SCHEMA.VIEWS 
       WHERE TABLE_SCHEMA = 'PUBLIC'
         AND TABLE_NAME = 'V1';

TABLE_NAME IS_AFFECTED
---------- -----------
V1         FALSE      

1 row selected.

Compatibility

The SQL standard does not define <alter view statement>.

For More Information

Refer to the followings.

ANALYZE SYSTEM

Function

It controls the statistics information of the system.

Syntax

<analyze system statement> ::=
    ANALYZE SYSTEM [ <analyze action> ]
    ;

<analyze action> ::=
      COMPUTE STATISTICS
    | DELETE STATISTICS

Invocation and Access Rules

ANALYZE ANY ON DATABASE privilege is required to perform <analyze system statement>.

Syntax Rules and Parameters

<analyze action>

When it is omitted, the default value is COMPUTE STATISTICS.

COMPUTE STATISTICS

It builds the following statistics information related to the system.

DELETE STATISTICS

It deletes the statistics information of the system.

Description

The built statistics information of the system is used to calculate the cost of optimization for the query process.

Examples

The following is an example of building the statistics information of the system by using the <analyze system statement> statement.

gSQL> ANALYZE SYSTEM COMPUTE STATISTICS;

analyzed.

The following is an example of retrieving the built statistics information of the system.

gSQL> 
SELECT * FROM DBA_STAT_SYSTEM;

 CPU_OPS NETWORK_IOPS NETWORK_BUFSIZE LAST_ANALYZED             
-------- ------------ --------------- --------------------------
53000412         2914           65536 2017-03-30 16:49:42.200000

1 row selected.

Compatibility

The SQL standard does not define the concepts of the statistics information.

For More Information

Refer to ANALYZE TABLE.

ANALYZE TABLE

Function

It controls the statistics information of the table.

Syntax

<analyze table statement> ::=
    ANALYZE TABLE table_name
    [ <parallel clause> ]
    [ <analyze action> ]
    ;

<parallel clause> ::=
      NOPARALLEL
    | PARALLEL [thread_count]

<analyze action> ::=
      COMPUTE STATISTICS [ <for_clause> ]
    | ESTIMATE STATISTICS <sample_clause> [ <for_clause> ]
    | DELETE STATISTICS

<sample_clause>
      SAMPLE row_count ROWS
    | SAMPLE percentage PERCENT

<for_clause>
      FOR ALL COLUMNS
    | FOR ALL INDEXED COLUMNS
    | FOR COLUMNS column_name [, ...]
    | FOR ALL INDEXES
    | FOR INDEXES index_name [, ...]

Invocation and Access Rules

ANALYZE ANY ON DATABASE privilege is required to perform <analyze table statement>.

Syntax Rules and Parameters

table_name

It is the table name.
It can define the schema to which the table belongs, such as schema_name.table_name. If schema_name is omitted, the default schema name of the user performing the statement is used.

<parallel clause>

It specifies the number of threads to be used in a analyzing process.
If it is not specified, the default value is PARALLEL.

<analyze action>

When it is omitted, the default value is COMPUTE STATISTICS.

COMPUTE STATISTICS

It builds the following statistics information related to the table through the all inspection.

The statistics information which is built according to the data type of the column is as follows.

Statistics information built according to the data type

Data type

NUM_DISTINCT

NUM_NULLS

AVG_LENGTH

MIN/MAX

BOOLEAN

O

O

O

X

NATIVE_SMALLINT

O

O

O

O

NATIVE_INTEGER

O

O

O

O

NATIVE_BIGINT

O

O

O

O

NATIVE_REAL

O

O

O

O

NATIVE_DOUBLE

O

O

O

O

NUMBER

O

O

O

O

NUMERIC

O

O

O

O

FLOAT

O

O

O

O

CHAR(n)

O

O

O

It is built when it is 64 bytes or smaller.

VARCHAR(n)

O

O

O

It is built when it is 64 bytes or smaller.

LONG VARCHAR

X

X

X

X

BINARY

O

O

O

X

VARBINARY

O

O

O

X

LONG VARBINARY

X

X

X

X

DATE

O

O

O

O

TIME

O

O

O

O

TIMESTAMP

O

O

O

O

INTERVAL

O

O

O

O

ROWID

O

O

O

X

ESTIMATE STATISTICS <sample_clause>

It builds the statistics information of the column and the index by using as many samples as the specified <sample_clause>.

If the number of the sampling rows is smaller than the value of MIN_SAMPLE_ROW_COUNT property, then it follows the property value.

<for_clause>

If it is omitted, it builds the statistics information of all possible columns and indexes.

FOR ALL COLUMNS

It builds the statistics information of all possible columns.
It does not build the statistics information of an index.

FOR ALL INDEXED COLUMNS

It builds the statistics information of all columns included in an index.
It does not build the statistics information of other columns.
It does not build the statistics information of an index.

FOR COLUMNS column_name [, ...]

It builds the statistics information of the listed columns.
It does not build the statistics information of unlisted columns.
It does not build the statistics information of an index.

FOR ALL INDEXES

It builds the statistics information of all indexes.
It does not build the statistics information of columns.

FOR INDEXES index_name [, ...]

It builds the statistics information of the listed indexes.
It does not build the statistics information of unlisted indexes.
It does not build the statistics information of a column.

DELETE STATISTICS

It deletes the statistics information of the table.

Description

The statistics information of the table affects the query optimization, so it is very important information.

The time to build the statistics information is increased in proportion to the data volumes in a table. Therefore, when the data volume is big, then it is recommended to build the statistics information by using the sampling or to build only the statistics of major information which affects the query.

ANALYZE TABLE lineitem ESTIMATE STATISTICS SAMPLE 10 PERCENT;
ANALYZE TABLE lineitem COMPUTE STATISTICS FOR ALL INDEXED COLUMNS;
ANALYZE TABLE lineitem COMPUTE STATISTICS FOR ALL INDEXES;

Examples

The following is an example of building the statistics information through the all inspection.

gSQL> ANALYZE TABLE orders;

Table analyzed.

The following is an example of retrieving the built statistics information of the table.

gSQL>
SELECT 
       TABLE_NAME
     , NUM_ROWS
  FROM
       DICTIONARY_SCHEMA.USER_TABLES
 WHERE
       TABLE_SCHEMA = 'PUBLIC'
   AND TABLE_NAME   = 'ORDERS'
;

TABLE_NAME NUM_ROWS
---------- --------
ORDERS      1500000

1 row selected.


gSQL>
SELECT 
       TABLE_NAME
     , COLUMN_NAME
     , NUM_DISTINCT
     , NUM_NULLS
     , LOW_VALUE
     , HIGH_VALUE
  FROM
       DICTIONARY_SCHEMA.USER_TAB_COLUMNS
 WHERE
       TABLE_SCHEMA = 'PUBLIC'
   AND TABLE_NAME   = 'ORDERS'
;

TABLE_NAME COLUMN_NAME     NUM_DISTINCT NUM_NULLS LOW_VALUE           HIGH_VALUE         
---------- --------------- ------------ --------- ------------------- -------------------
ORDERS     O_ORDERKEY           1500000         0 1                   6000000            
ORDERS     O_CUSTKEY              99996         0 1                   149999             
ORDERS     O_ORDERSTATUS              3         0 F                   P                  
ORDERS     O_TOTALPRICE         1464556         0 857.71              555285.16          
ORDERS     O_ORDERDATE             2406         0 1992-01-01 00:00:00 1998-08-02 00:00:00
ORDERS     O_ORDERPRIORITY            5         0 1-URGENT            5-LOW              
ORDERS     O_CLERK                 1000         0 Clerk#000000001     Clerk#000001000    
ORDERS     O_SHIPPRIORITY             1         0 0                   0                  
ORDERS     O_COMMENT            1482071         0 null                null               

9 rows selected.

gSQL>
SELECT 
       TABLE_NAME
     , INDEX_NAME
     , DISTINCT_KEYS
  FROM
       DICTIONARY_SCHEMA.USER_INDEXES
 WHERE
       TABLE_SCHEMA = 'PUBLIC'
   AND TABLE_NAME   = 'ORDERS'
;

TABLE_NAME INDEX_NAME        DISTINCT_KEYS
---------- ----------------- -------------
ORDERS     ORDERS_PK_INDEX         1500000
ORDERS     ORDERS_CUSTKEY_FK         99996

2 rows selected.

Compatibility

The SQL standard does not define the concepts of the statistics information.

For More Information

Refer to ANALYZE SYSTEM.

AUDIT POLICY

Function

It activates the audit policy.

Syntax

<audit policy statement> ::= 
    AUDIT POLICY policy_name
    [ <specified_user_option> ]
    [ <specified_success_option> ]
    ;

<specified_user_option> ::=
      BY user_name [, ...]
    | EXCEPT user_name [, ...]

<specified_success_option> ::=
      WHENEVER SUCCESSFUL
    | WHENEVER NOT SUCCESSFUL

Invocation and Access Rules

AUDIT SYSTEM ON DATABASE privilege is required to perform <audit policy statement>.

Syntax Rules and Parameters

policy_name

It is the name of the audit policy object to be activated.
The activated audit policy does not effect on the existing session, and it effects only on the newly created session.

<specified_user_option>

It specifies the user to be audited.
If omitted, all users are audited.

BY clause and EXCEPT clause can not be used together for the same audit policy.

<specified_success_option>

Description

Activating the audit policy does not affect the existing session, but it starts to audit the newly created session.

Retrieving Audit Record

The audit record is created when it corresponds to the audit policy, and it can be retrieved through DICTIONARY_SCHEMA.AUDIT_TRAIL view as follows.
SELECT logon_user
     , event_timestamp
     , action_name
     , object_name 
     , sql_text
  FROM audit_trail
 WHERE policy_name = 'P1'
;

SELECT privilege should be given to an ordinary user to retrieve AUDIT_TRAIL.

GRANT SELECT ON DICTIONARY_SCHEMA.AUDTI_TRAIL TO user_name;

Retrieving Audit Policy Information

The information about the audit policy object can be retrieved through DICTIONARY_SCHEMA.AUDIT_POLICY_OPTIONS view.

SELECT policy_name
     , audit_option
     , object_schema
     , object_name
  FROM audit_policy_options
;

The information about whether the audit policy object is activated can be retrieved through DICTIONARY_SCHEMA.AUDIT_POLICY_ENABLED view.

SELECT policy_name
     , enabled_opt
     , user_name
     , when_success
     , when_failure
  FROM audit_policy_enabled
;

Cautions When Using BY and EXCEPT Clauses

Activate the users group if multiple AUDIT POLICY BY clauses are used for the same audit policy.
In other words, the following two examples have the same meaning.
AUDIT POLICY p1 BY u1;
AUDIT POLICY p1 BY u2;
AUDIT POLICY p1 BY u1, u2;
If multiple AUDIT POLICY EXCEPT clauses are used for the same audit policy, only the last AUDIT POLICY clause is valid.
In other words, the following two examples have different meanings.
AUDIT POLICY p1 EXCEPT u1;
AUDIT POLICY p1 EXCEPT u2;
AUDIT POLICY p1 EXCEPT u1, u2;

BY and EXCEPT can not be used together for the same policy.

AUDIT POLICY p1 BY u1;
AUDIT POLICY p1 EXCEPT u2;
AUDIT POLICY p1 EXCEPT u1;
AUDIT POLICY p1;
If a user wants to convert the audit policy activated with BY to EXCEPT or to convert the audit policy activated with EXCEPT to BY, the activated audit policy should be deactivated first, then it can be converted.

Deactivate the audit policy with NOAUDIT POLICY statement as follows.

WHENEVER clause which is used together with BY clause is accumulated.

The following two examples have the same meaning.

AUDIT POLICY p1 BY u1 WHENEVER SUCCESSFUL;
AUDIT POLICY p1 BY u1 WHENEVER NOT SUCCESSFUL;
AUDIT POLICY p1 BY u1;

If WHENEVER clauses are used together with EXCEPT clause, only the last WHENEVER clause is valid.

The following two examples have different meanings.

AUDIT POLICY p1 EXCEPT u1 WHENEVER SUCCESSFUL;
AUDIT POLICY p1 EXCEPT u1 WHENEVER NOT SUCCESSFUL;
AUDIT POLICY p1 EXCEPT u1;

Examples

The following is an example of activating the audit policy for all users.

AUDIT POLICY table_pol;

The information about activation can be viewed through the following query.

SELECT policy_name
     , enabled_opt
     , user_name
  FROM audit_policy_enabled
 WHERE policy_name = 'TABLE_POL';

POLICY_NAME  ENABLED_OPT  USER_NAME
-----------  -----------  ---------
TABLE_POL    BY           ALL USERS

The following is an example of activating the audit policy by defining specific users.

AUDIT POLICY dml_pol BY u1, u2;

The following is an example of activating the audit policy by excluding a specific user.

AUDIT POLICY read_seq_pol EXCEPT sys;

The following is an example of auditing the failure of SQL statement by a specific user.

AUDIT POLICY delete_pol BY u1 WHENEVER NOT SUCCESSFUL;

Compatibility

The SQL standard does not have the audit policy.

For More Information

Refer to the followings.

CLOSE cursor_name

Function

It closes a cursor.

Syntax

<close statement> ::=
    CLOSE cursor_name
    ;

Syntax Rules and Parameters

cursor_name

The cursor should be open.
The cursor should be declared with DECLARE cursor_name statement in the session.

Description

The cursor is an object which exists in the session and it does not affect the cursor in a different session.

Example

The following is an example of DECLARE, OPEN, FETCH, and CLOSE the cursor by using gsql (interactive SQL tool).

gSQL> DECLARE cur1 CURSOR FOR SELECT id, data FROM t1;

Cursor declared.

gSQL> OPEN cur1;

Cursor is open.

gSQL> \var v_id   INTEGER
gSQL> \var v_data VARCHAR(128)

gSQL> FETCH cur1 INTO :v_id, :v_data;

V_ID V_DATA
---- ------
   1 data_1

1 row fetched.


gSQL> FETCH cur1 INTO :v_id, :v_data;

V_ID V_DATA
---- ------
   2 data_2

1 row fetched.

gSQL> FETCH cur1 INTO :v_id, :v_data;

no rows fetched.

gSQL> CLOSE cur1;

Cursor closed.

Compatibility

SQL standard compatibility

Feature ID

Description

Compatibility

B031

Basic dynamic SQL

O

For More Information

Refer to the followings.

COMMENT ON name IS

Function

It stores the comments about the object in the dictionary.

Syntax

<comment statement> ::=
    COMMENT ON <comment object> IS 'comment string'
    ;

<comment object> ::=
      CLUSTER GROUP group_name
    | CLUSTER MEMBER member_name
    | DATABASE
    | PROFILE profile_name
    | AUTHORIZATION user_name
    | TABLESPACE tablespace_name
    | SCHEMA schema_name
    | TABLE [schema_name].table_name
    | COLUMN [schema_name].table_name.column_name
    | INDEX [schema_name].index_name
    | SEQUENCE [schema_name].sequence_name
    | CONSTRAINT [schema_name].constraint_name
    | PROCEDURE [schema_name].procedure_name

Invocation and Access Rules

The altering privileges on each object are required to perform <comment statement> as follows.

Syntax Rules and Parameters

<comment object>

It is an object in which the comments are to be stored. The comments for the following database objects are stored.

If schema_name for the schema object is not specified, the schema name is determined by Schema Path of the user performing the statement.
COMMENT ON TABLE test_table IS 'test comment'; 
→ COMMENT ON TABLE user_default_schema.test_table IS 'test comment';

'comment string'

It describes the comments to be stored.
Use the empty string ('') to delete the comments as follows.
COMMENT ON TABLE test_table IS '';
The length of the comment string can not exceed 1024 bytes.

Description

The information can be retrieved from the COMMENTS column of the following dictionary view per each object type.

For more information about the detailed description of each view, refer to DICTIONARY_SCHEMA.

Examples

The following is an example of creating the comment on the table.

gSQL> COMMENT ON TABLE t1 IS 'test comment on table t1';

Comment created.

The following is an example of creating the comment on the column.

gSQL> COMMENT ON COLUMN t1.id IS 'test comment on column t1.id';

Comment created.

The following is an example of creating the comment on the schema.

gSQL> COMMENT ON SCHEMA s1 IS 'test comment on schema s1';

Comment created.

Compatibility

<comment statement> does not exist in SQL standard.

COMMIT

Function

It terminates the current transaction and makes all changes permanent.

Syntax

<commit statement> ::=
    COMMIT [ WORK ] 
       [ [ <commit comment clause> ] [ <commit write clause> ] |
         [ <commit force clause> ] [ <commit comment clause> ] ]
    ;

<commit comment clause> ::=
      COMMENT 'comment_string'

<commit write clause> ::=
      WRITE [ WAIT | NOWAIT ]

<commit force clause> ::=
    FORCE 'xid_string'

Syntax Rules and Parameters

WORK

It is the reserved word which does not affect the operation.

<commit comment clause>

<commit write clause>

It determines whether to wait until the redo logs generated by the commit operation are written on the redo log file.

<commit force clause>

It is used to manually commit a distributed transaction.

Description

COMMIT statement completes the following statements which were executed in a transaction.

Exceptionally, the following DDL statements which manage the OS resources or change the DATA TYPE are automatically committed.

When performing COMMIT, the cursor opened by WITHOUT HOLD option is automatically closed. For more information about cursors, refer to the following cursor related statements.

If the transaction violates the DEFERRED constraint, the COMMIT statement fails and the transaction is rolled back. For more information about DEFERRED constraint, refer to SET CONSTRAINTS.

Example

The following is an example of performing COMMIT after executing INSERT statement.

gSQL> INSERT INTO t1 VALUES ( 1, 'anonymous' );

1 row created.

gSQL> COMMIT WORK COMMENT 'INSERT T1';

Commit complete.

Compatibility

SQL standard compatibility

Feature ID

Description

Compatibility

T261

Chained transactions

X

For More Information

Refer to the followings.

CREATE AUDIT POLICY

Function

It creates an audit policy object.
AUDIT POLICY should be performed to activate the created audit policy object.

Syntax

<audit policy definition> ::= 
    CREATE AUDIT POLICY policy_name
    { <privilege_audit_clause> |  <action_audit_clause> | <privilege_audit_clause> <action_audit_clause> }
    ; 

<privilege_audit_clause> ::=
    PRIVILEGES <database_privilege> [, ...]

<action_audit_clause> ::=
    ACTIONS { <object_action_audit> | <system_action_audit> } [, ...]

<object_action_audit> ::=
      ALL ON [schema_name.]object_name
    | <object_action> ON [schema_name.]object_name

<system_action_audit> ::=
      ALL
    | DDL
    | <system_action>

Invocation and Access Rules

AUDIT SYSTEM ON DATABASE privilege is required to perform <audit policy definition>.

Syntax Rules and Parameters

policy_name

It is the name of the audit policy to be created.

<privilege_audit_clause>

The privilege audit is auditing when the SQL statement is successfully performed by using the database privilege.
It can audit a specific user performing SQL statement by using the database privilege, and it does not record the privilege audit for SYS user who is the owner of the database.

The following is an example of granting SELECT ANY TABLE privilege to user u1 and activating the audit policy.

CREATE AUDIT POLICY p1 
       PRIVILEGES SELECT ANY TABLE;

AUDIT POLICY p1;

If the user u1 performs the following SQL statement, the privilege audit differently operates.

<database_privilege> which can be described in the privilege audit can be viewed with the following query.

SELECT PRIVILEGE_NAME FROM V$AUDITABLE_DB_PRIVILEGES;

<action_audit_clause>

It audits an action for a specific object and an action for the entire database.

<object_action_audit>

ALL ON object_name

It means all actions which can list objects corresponding to object_name.

The following table describes audit actions of which each object type can audit.

Audit action per object type

Object type

Action

Table

ALTER, COMMENT, DELETE, GRANT, INDEX, INSERT, LOCK, RENAME, SELECT, UPDATE

View

ALTER, COMMENT, GRANT, SELECT

Sequence

ALTER, COMMENT, GRANT, SELECT

Stored Function/Procedure

ALTER, COMMENT, EXECUTE, GRANT

<object_action> ON object_name

Each separate action per a specific object should be listed by specifying ON clause as follows.

CREATE AUDIT POLICY p1
       ACTIONS INSERT ON u1.t1
             , DELETE ON u1.t1
             , UPDATE ON u1.t1
;

Caution of EXECUTE action

Auditing the success or the failure of stored function or stored procedure is determined only based on whether it is executable at the time of execution.

<system_action_audit>

It audits the system action which occurs in the database regardless of a specific object.

The valid system action can be retrieved by using the following query.

SELECT ACTION_NAME FROM V$AUDITABLE_SYSTEM_ACTIONS;

It means all system actions.

It means all Data Definition Language (DDL).

Description

An audit policy object is an object which defines auditing targets.  
Perform AUDIT POLICY statement to activate an audit policy.
Though it is possible to define and activate multiple audit policies, but it is recommended to maintain certain number of audit policies.  
It is also recommended to bind multiple small pieces of policies into a small number of groups.

The information about an option of the created audit policy object can be retrieved through AUDIT_POLICY_OPTIONS view as follows.

SELECT audit_option
     , audit_option_type
     , object_schema
     , object_name
  FROM audit_policy_options
 WHERE policy_name = 'P1'
;

AUDIT_OPTION AUDIT_OPTION_TYPE OBJECT_SCHEMA  OBJECT_NAME
------------ ----------------- -------------- ------------
DELETE         OBJECT ACTION     U1          T1
INSERT         OBJECT ACTION     U1          T1
UPDATE         OBJECT ACTION     U1          T1

Creating Audit Record

If an action corresponding to multiple audit policies occurs, then one or more audit records are created.

If similar audit options are listed as follows, then one audit record is created.

CREATE AUDIT POLICY p1
       PRIVILEGES SELECT ANY TABLE
       ACTIONS SELECT;

AUDIT POLICY p1;
SELECT * FROM other_user.t1;

If two different audit options are listed as follows, then two audit records are created.

CREATE AUDIT POLICY p1
       ACTIONS SELECT ON u1.t1
             , SELECT ON u2.t2;

AUDIT POLICY p1;
SELECT COUNT(*) FROM u1.t1 A, u2.t2 B WHERE A.id = B.id;

If multiple audit policies are activated for the same action as follows, then two audit records are created.

CREATE AUDIT POLICY p1
       PRIVILEGES SELECT ANY TABLE;
AUDIT POLICY p1;

CREATE AUDIT POLICY p2
       ACTIONS SELECT;
AUDIT POLICY p2;
SELECT * FROM other.t1;

Examples

The following is an example of defining an audit policy which audits an privilege.

CREATE AUDIT POLICY policy_table
       PRIVILEGES CREATE ANY TABLE
                , DROP ANY TABLE
;

The following is an example of defining an audit policy which audits an action for an object.

CREATE AUDIT POLICY policy_dml
       ACTIONS INSERT ON u1.t1
             , DELETE ON u1.t1
             , UPDATE ON u1.t1
             , ALL    ON u1.t2
;

The following is an example of defining an audit policy which audits the system action.

CREATE AUDIT POLICY policy_drop
       ACTIONS DROP TABLE, TRUNCATE TABLE
;

The following is an example of defining an audit policy which combines all examples above.

CREATE AUDIT POLICY policy_group
       PRIVILEGES CREATE ANY TABLE
                , DROP ANY TABLE
       ACTIONS INSERT ON u1.t1
             , DELETE ON u1.t1
             , UPDATE ON u1.t1
             , ALL    ON u1.t2
             , DROP TABLE
             , TRUNCATE TABLE
;

Compatibility

The audit policy does not exist in SQL standard.

For More Information

Refer to the followings.

CREATE CLUSTER GROUP

Function

It creates a cluster group which is to participate in a cluster system.

Syntax

<cluster group definition> ::=
    CREATE CLUSTER GROUP group_name 
        <cluster member definition> [, ...]
    ;

<cluster member definition> ::=
    CLUSTER MEMBER member_name <connection attribute> [<member position>]

<connection attribute> ::=
    HOST 'address' PORT port_no

<member position> ::=
    POSITION DEFAULT
  | POSITION MAX
  | POSITION number

Invocation and Access Rules

It can be performed in a cluster system.

ADMINISTRATION ON DATABASE privilege is required to perform <cluster group definition>.

Syntax Rules and Parameters

group_name

It is the name of a cluster group.
An identical cluster group name or a cluster member name should not exist.
The name length should be shorter than 128 bytes.

<cluster member definition>

It defines a cluster member to be included in a cluster group.
A cluster group can include maximum 32 cluster members.
A cluster group which is created first in a cluster system can define only one cluster member, and should include itself as a cluster member.

member_name

It is the name of a cluster member.
The name of a cluster member should be same as the name of the member which was defined when creating the database of that member.
An identical cluster group name or a cluster member name should not exist.
The name length should be shorter than 128 bytes.

The start-up phase of the cluster member should be the GLOBAL OPEN phase.

<connection attribute>

It defines the connection information for the communication between the cluster members.
<connection attribute> should be as same as the HOST and PORT which were defined when the database of that cluster member was created.
The combination of HOST and PORT should be unique in the cluster system.

<member position>

It assigns the position number of the cluster member.

The member_position information of the cluster member can be retrieved through DBA_CLUSTER view.

SELECT member_name, member_id, member_position FROM dba_cluster;

If the following position numbers are being used,

The following values are assigned according to each option.

Description

<cluster group definition> statement does not rebalance the shard of tables.

Perform the following statements to rebalance the shard to an added cluster group.

Examples

The following is an example of creating a cluster group which consists of two cluster members.

gSQL> 
CREATE CLUSTER GROUP g1
    CLUSTER MEMBER g1n1 HOST '192.168.0.11' PORT 10110
;

Cluster Group created.

gSQL>
ALTER CLUSTER GROUP g1
    ADD CLUSTER MEMBER g1n2 HOST '192.168.0.12' PORT 10120
;

Cluster Group altered.

gSQL> 
CREATE CLUSTER GROUP g2
    CLUSTER MEMBER g2n1 HOST '192.168.0.21' PORT 10210,
    CLUSTER MEMBER g2n2 HOST '192.168.0.22' PORT 10220
;

Cluster Group created.

Compatibility

The SQL standard does not define the concepts of the cluster.

For More Information

Refer to the followings.

CREATE CLUSTER LOCATION

Function

It creates the connection information of a cluster member.

Syntax

<cluster location definition> ::=
    CREATE CLUSTER LOCATION member_name 
    <cluster connection attribute>
    ;

<cluster connection attribute> ::
       HOST 'address' PORT port_no

Invocation and Access Rules

It can be performed in a cluster system.
ADMINISTRATION ON DATABASE privilege is required to perform <cluster location definition>.

Syntax Rules and Parameters

member_name

It is the name of a cluster member.
The same cluster member name should not exist in the registered cluster location information.
The length of the name should be shorter than 128 bytes.

<cluster connection attribute>

It defines the connection information for the communication between the cluster members.
The combination of HOST and PORT should be unique in the cluster system.

Description

Generally, the information of the cluster location is automatically created by using the connection information provided when creating the cluster group or adding the cluster member. The created information is deleted together when deleting the cluster member and the cluster group.

If the information of the cluster location is modified, then the connection information can be modified by using ALTER CLUSTER LOCATION without deleting or recreating the cluster member.

Examples

gSQL> 
CREATE CLUSTER LOCATION g1n2
    HOST '192.168.0.12' PORT 10120,
;

Created

Compatibility

The SQL standard does not define the concepts of the cluster.

For More Information

Refer to DROP CLUSTER LOCATION .

CREATE DISK DATA TABLESPACE

Function

It defines the disk data tablespace.

Syntax

<disk data tablespace statement> ::=
    CREATE DISK [ DATA ] TABLESPACE tablespace_name
        DATAFILE <disk datafile clause> [, ...]
        [ <data tablespace management clause> [, ...] ]

<disk datafile clause> ::=
     'filename' 
        [ SIZE <size clause> | REUSE | SIZE <size clause> REUSE ]
        [ <autoextend clause> ]
        [ AT <domain_name> ]

<autoextend clause>
    AUTOEXTEND { ON [ <next size clause> ] [ <max size clause> ] | OFF }

<next size clause>
    NEXT <size clause>

<max size clause>
    MAXSIZE { <size clause> | UNLIMITED }

<size clause> ::=
    integer [ K | M | G | T ]

<data tablespace management clause> ::=
      { ONLINE | OFFLINE }
    | EXTSIZE <size clause>

Invocation and Access Rules

CREATE TABLESPACE ON DATABASE privilege is required to perform <disk data tablespace definition>.

The user who performed the statement has CREATE OBJECT ON TABLESPACE privilege for the created tablespace.

The following privileges are required to create an object on the created tablespace.

Syntax Rules and Parameters

tablespace_name

It is the name of the tablespace to be created.
The length of the tablespace name should be shorter than 128 bytes.

<disk datafile clause>

<autoextend clause>

It sets the automatic expand property to ON or OFF. If it is set to ON, then it can specify the automatic expanded size and the maximum size of the data file.

<next size clause>

It specifies the size to be extended when the data file in use does not have available space.

<max size clause>

It specifies the maximum expanded size of the data file.

<size clause>

It specifies the file size in byte. (If it is omitted, the default unit is bytes.)

<domain_name>

It is the name of member or the group to performs the statement.
If it is omitted, then it is performed for all groups.

ONLINE | OFFLINE

It determines whether to ONLINE/ OFFLINE the tablespace.

EXTSIZE <size clause>

It specifies the extent size of the tablespace.

Description

The data tablespace is an object which provides a physical storage to store SQL schema objects such as a table, and index (LOGGING).

Examples

The following is an example of creating the disk data tablespace.

gSQL> CREATE DISK TABLESPACE space1 DATAFILE 'test_file_1.dbf' SIZE 10M REUSE;

Tablespace created.

The following is an example of creating the tablespace which consists of multiple data files.

gSQL> CREATE DISK TABLESPACE space1 
             DATAFILE 'test_file_3_1.dbf' SIZE 10M REUSE,
                      'test_file_3_2.dbf' SIZE 10M REUSE;

Tablespace created.

Compatibility

The SQL standard does not define the concepts of the tablespace.

For More Information

Refer to the followings.

CREATE GLOBAL TEMPORARY TABLE

Function

It creates a new global temporary table.

Syntax

<global temporary table definition> ::=
    CREATE GLOBAL TEMPORARY TABLE table_name
        ( <table element> [, ...] )
        [ <table commit action clause> ]
        [ TABLESPACE tablespace_name ]
    ;

<global temporary table definition: AS query expression> ::=
    CREATE GLOBAL TEMPORARY TABLE table_name 
        [ TABLESPACE tablespace_name ]
        AS <query expression> [ WITH [ NO ] DATA ]
    ;

<table commit action clause> ::=
    ON COMMIT { PRESERVE | DELETE } ROWS

The definition of <table element> is as same as that of <table_definition>.

For more information, refer to CREATE TABLE.

Invocation and Access Rules

A user should satisfy the following conditions to perform <global temporary table definition> statement.

Syntax Rules and Parameters

table_name

It is the table name to be created.
For more information, refer to table_name.

other syntax

For more information about other syntaxes, refer to the syntax in CREATE TABLE and in CREATE TABLE AS SELECT statement.

Description

GLOBAL TEMPORARY TABLE is used to store the data which is maintained while a transaction or a session is performed. 
It is used for the purpose as same as that of the variable of which a developer temporarily stores the mid-data of the operation when developing an application.
The global temporary table has the following features.

Whether to specify tablespace

The tablespace in which the table is created

It specifies the tablespace.

It is created in the specified tablespace.

It does not specify the tablespace.

It is created in the default temporary tablespace of the current session user.

Table commit action

Description

ON COMMIT PRESERVE ROWS

It maintains the data remained in a table even after COMMIT or ROLLBACK.

ON COMMIT DELETE ROWS (default)

It deletes all data remained in a table at the time of COMMIT or ROLLBACK (TRUNCATE).

TEMP_UNDO_ENABLED value

Description

TRUE

The undo log is recorded in the default temporary tablespace of the database system.

FALSE

The undo log is recorded in the undo tablespace of the database system.

Examples

The following is an example of performing CREATE GLOBAL TEMPORARY TABLE statement.

gSQL> CREATE  GLOBAL TEMPORARY TABLE SESSION_TABLE1(
        COL1    CHAR(10)
       ,COL2    VARCHAR2(20)
       ,COL3    NUMBER(10)
)   ON  COMMIT  DELETE ROWS;

Table created.

The following is an example of performing CREATE GLOBAL TEMPORARY TABLE ... AS SELECT statement.

gSQL> CREATE  GLOBAL TEMPORARY TABLE SESSION_TABLE2
    ON  COMMIT  PRESERVE ROWS
    AS  SELECT  *
          FROM  EMPLOYEES;

Table created.

Compatibility

CREATE GLOBAL TEMPORARY TABLE and CREATE GLOBAL TEMPORARY TABLE AS SELECT statements follow the definition of SQL standard <table definition>. However, the following is an extension of SQL standard.

SQL standard compatibility

Feature ID

Description

Compatibility

T171

LIKE clause in table definition

X

T172

AS subquery clause in table definition

O

F531

Temporary tables

X

S051

Create table of type

X

S043

Enhanced reference types

X

S081

Subtables

X

T173

Extended LIKE clause in table definition

X

T180

System-versioned tables

X

F692

Extended collation support

X

T174

Identity columns

O

T175

Generated columns

X

S071

SQL paths in function and type name resolution

X

F321

User authorization

O

T322

Extended roles

X

F762

CURRENT_CATALOG

O

F763

CURRENT_SCHEMA

O

For More Information

Refer to the followings.

CREATE IMMUTABLE TABLE

Function

It creates a new immutable table.

Syntax

<immutable table definition> ::=
    CREATE IMMUTABLE TABLE table_name
        ( <table element> [, ...] )
        [ <table sharding strategy> ]
        [ <table attribute clause> [...] ]
        [ TABLESPACE tablespace_name ]
        [ <table global secondary index clause> ]
    ;

<immutable table definition: AS query expression> ::=
    CREATE IMMUTABLE TABLE table_name
        [ ( column_name [, ...] ) ]
        [ <table sharding strategy> ]
        [ <table attribute clause> [, ...] ]
        [ TABLESPACE tablespace_name ]
        [ <table global secondary index clause> ]
        AS <query expression> [ WITH [ NO ] DATA ]
    ;

The definition for <table element>, <table sharding strategy>, <table attribute clause> and <table global secondary index clause> are as same as those in <table_definition>. For more information, refer to CREATE TABLE.

Invocation and Access Rules

The user should satisfy the following conditions to perform <immutable table definition>.

Syntax Rules and Parameters

table_name

It is the table name to be created and it should be unique in the schema.
It can define the schema to which the table belongs, such as schema_name.table_name. If schema_name is omitted, the default schema name of the user performing the statement is used.
The length of the table name should be shorter than 128 bytes.

Other Syntax

For other syntaxes, refer to the syntaxes for CREATE TABLE and CREATE TABLE AS SELECT.

Description

An immutable table is used when it is required to prevent the record stored in the table from being altered or deleted and to prevent the table from being dropped.

An immutable table can be dropped when a user, a schema, a tablespace and a cluster group are dropped.

The following SQL statements are not allowed for an immutable table.


The following SQL statements are allowed for an immutable table.

Examples

The following is an example of executing CREATE IMMUTABLE TABLE statement.

gSQL> CREATE IMMUTABLE TABLE t1
(
    id INTEGER PRIMARY KEY,
    name VARCHAR(128),
    addr VARCHAR(128)
);

Table created.

The following is an example of executing CREATE IMMUTABLE TABLE ... AS SELECT statement.

gSQL> CREATE IMMUTABLE TABLE T2
       AS SELECT *
             FROM T1;

Table created.

Compatibility

The SQL standard does not cover CREATE IMMUTABLE TABLE and CREATE IMMUTABLE TABLE AS SELECT statements.

For More Information

Refer to the followings.

CREATE INDEX

Function

It creates an index.

Syntax

<index definition> ::=
    CREATE [ UNIQUE ] INDEX index_name
        ON table_name ( <index column element> [, ...] )
        [ <index attributes> [...] ]
        [ TABLESPACE tablespace_name ]
    ;

<index column element> ::=
    column_name [ ASC | DESC ] [ NULLS FIRST | NULLS LAST ]

<index attributes> ::=
      <physical attribute clause>
    | STORAGE ( <segment attr clause> [...] )
    | <parallel clause> 

<physical attribute clause> ::=
      PCTFREE integer
    | INITRANS integer
    | MAXTRANS integer

<segment attr clause> ::=
      INITIAL <size_clause>
    | NEXT <size_clause>
    | MINSIZE <size_clause>
    | MAXSIZE <size_clause>

<size clause> ::=
      integer [ K | M | G | T ]

<parallel clause> ::=
      NOPARALLEL
    | PARALLEL [ integer ]

Invocation and Access Rules

The user should satisfy the following conditions to perform <index definition>.

Unique indexes in a cluster system should include all sharding keys.

Syntax Rules and Parameters

UNIQUE

It does not allow duplicate values for the columns of the index.

index_name

It is the index name to be created and it should be a unique name within the schema.
If the schema name is omitted, the index is created in the schema to which the referring table belongs.
The length of the index name should be shorter than 128 bytes.

table_name

It is the table name which creates the index.
The schema to which a table belongs, such as schema_name.table_name, can be defined. If schema_name is omitted, the default schema name of the user performing the statement is used.

column_name

It is the column name to be used as an index key.
One or more columns should be defined, and maximum 32 columns can be used as an index key.
The following constraints can occur depending on the implementation.

ASC | DESC

It specifies the sort order of a column.

NULLS FIRST | NULLS LAST

It specifies the sort order of the NULL value.

<physical attribute clause>

It defines the physical attribute of the index.

<segment attr clause>

It specifies the information for the index storage space.

<size clause>

It specifies the file size in bytes. (If the unit is omitted, the default value is bytes.)

NOPARALLEL | PARALLEL [ integer ]

It specifies the number of threads to be used when building an index.

TABLESPACE tablespace_name

It specifies the name of the tablespace in which the index is to be stored.

Description

LOGGING index and NOLOGGING index have the following trade-offs.

Examples

The following is an example of creating the unique index.

gSQL> CREATE UNIQUE INDEX idx_t1_id ON t1( id );

Index created.

The following is an example of creating an index for multiple columns.

gSQL> CREATE INDEX idx_t1_id_name ON t1( id, name );

Index created.

The following is an example of specifying the sort order of the index column.

gSQL> CREATE INDEX idx_t1_dept_id ON t1( dept_id DESC );

Index created.

The following is an example of specifying the sort order of NULL value of the index column.

gSQL> CREATE INDEX idx_t1_name ON t1( name NULLS FIRST );

Index created.

The following is an example of setting information about the space in which index is stored.

gSQL> CREATE INDEX idx_t1_id ON t1( id )
             STORAGE ( INITIAL 10M NEXT 1M MINSIZE 10M MAXSIZE 100M );

Index created.

The following is an example of creating the redo logging for the index.

gSQL> CREATE INDEX idx_t1_id ON t1( id );

Index created.

The following is an example of creating the index with parallel option.

gSQL> CREATE INDEX idx_t1_name ON t1( name ) PARALLEL;

Index created.

The following is an example of specifying the tablespace when creating an index.

gSQL> CREATE INDEX idx_t1_name ON t1( name ) TABLESPACE mem_temp_tbs;

Index created.

Compatibility

The SQL standard does not cover the concepts of the index.

For more information

Refer to DROP INDEX.

CREATE MEMORY DATA TABLESPACE

Function

It defines a memory data tablespace.

Syntax

<memory data tablespace statement> ::=
    CREATE [ MEMORY ] [ DATA ] TABLESPACE tablespace_name
        DATAFILE <memory datafile clause> [, ...]
        [ <data tablespace management clause> [, ...] ]

<memory datafile clause> ::=
     'filename' 
        [ SIZE <size clause> | REUSE | SIZE <size clause> REUSE ]
        [ AT <domain_name> ]
<size clause> ::=
    integer [ K | M | G | T ]

<data tablespace management clause> ::=
      { ONLINE | OFFLINE }
    | EXTSIZE <size clause>

Invocation and Access Rules

CREATE TABLESPACE ON DATABASE privilege is required to perform <memory data tablespace definition>.

The user who performed the statement has CREATE OBJECT ON TABLESPACE privilege on the created tablespace.

One of the following privileges is required to create the objects on the created tablespace.

Syntax Rules and Parameters

[ MEMORY ] [ DATA ]

It is a memory tablespace to store the permanent objects such as tables, indexes, etc.
The reserved words, MEMORY and DATA, can be omitted.

tablespace_name

It is the tablespace name to be created.
The length of the tablespace name should be shorter than 128 bytes.

<memory datafile clause>

<size clause>

It specifies the file size in bytes. (If it is omitted, the default unit is bytes.)

<domain name>

It is a name of a member or a group for which the statement is performed.
If it is omitted, it is performed for all groups.

ONLINE | OFFLINE

It sets ONLINE or OFFLINE of the tablespace.

EXTSIZE <size clause>

It specifies extent size of the tablespace.

Description

The data tablespace is an object which provides the physical space to store the SQL schema object such as a table, an index (LOGGING).

Examples

The following is an example of creating a memory data tablespace.

gSQL> CREATE TABLESPACE space1 DATAFILE 'test_file_1.dbf' SIZE 10M REUSE;

Tablespace created.

The following is an example of creating a tablespace which consists of multiple data files.

gSQL> CREATE TABLESPACE space1 
             DATAFILE 'test_file_3_1.dbf' SIZE 10M REUSE,
                      'test_file_3_2.dbf' SIZE 10M REUSE;

Tablespace created.

Compatibility

The SQL standard does not cover the concepts of the tablespace.

For More Information

Refer to the followings.

CREATE MEMORY TEMPORARY TABLESPACE

Function

It defines a memory temporary tablespace.

Syntax

<memory temporary tablespace statement> ::=
    CREATE [ MEMORY ] TEMPORARY TABLESPACE tablespace_name
        MEMORY <memory clause> [, ...]
        <temporary tablespace management clause>

<memory clause> 
     'memory_name' { SIZE <size clause> } [ AT <domain_name> ]

<temporary tablespace management clause> ::=
    EXTSIZE <size clause>

Invocation and Access Rules

CREATE TABLESPACE ON DATABASE privilege is required to perform <memory temporary tablespace definition>.

The user who performed the statement has CREATE OBJECT ON TABLESPACE privilege on the created tablespace.

One of the following privileges is required to create the objects on the created tablespace.

Syntax Rules and Parameters

[ MEMORY ] TEMPORARY

It is a memory temporary tablespace to store the no logging indexes or the temporary objects such as intermediate results which are generated during the query processing.
The reserved word, MEMORY, can be omitted.

tablespace_name

It is the tablespace name to be created.
The length of the tablespace name should be shorter than 128 bytes.

<memory clause>

<size clause>

It specifies the size of shared memory space in bytes.(If it is omitted, the default unit is bytes.)
The image is not managed as a file in case of the temporary memory data.

<domain name>

It is a name of a member or a group for which the statement is performed.
If it is omitted, it is performed for all groups.

EXTSIZE <size clause>

It specifies extent size of the tablespace.

Description

The temporary tablespace is an object which provides the physical space to store the SQL schema object such as an index (NOLOGGING), and to store the intermediate results for sorting, hashing during the query processing.

Examples

The following is an example of creating a temporary tablespace.

gSQL> CREATE TEMPORARY TABLESPACE temp_space1 MEMORY 'test_memory_1' SIZE 10M;

Tablespace created.

The following is an example of creating a temporary tablespace which includes multiple memory spaces.

gSQL> CREATE TEMPORARY TABLESPACE temp_space1 
             MEMORY 'test_memory_3_1' SIZE 10M,
                    'test_memory_3_2' SIZE 10M;

Tablespace created.

Compatibility

The SQL standard does not cover the concepts of the tablespace.

For More Information

Refer to the followings.

CREATE PROFILE

Function

It is the statement which creates the profile, and it sets the password management method. 
When a profile is allocated to a user, the user's password is managed in the way defined in the profile.

Syntax

<profile definition> ::=

    CREATE PROFILE profile_name LIMIT 
    { <password_parameters>, ...}
    ; 

<password parameters> ::= 
      FAILED_LOGIN_ATTEMPTS { integer | UNLIMITED | DEFAULT }
    | PASSWORD_LOCK_TIME  { password_parameter_number_interval | UNLIMITED | DEFAULT }
    | PASSWORD_LIFE_TIME  { password_parameter_number_interval | UNLIMITED | DEFAULT }
    | PASSWORD_GRACE_TIME { password_parameter_number_interval | UNLIMITED | DEFAULT }
    | PASSWORD_REUSE_MAX  { integer | UNLIMITED | DEFAULT }
    | PASSWORD_REUSE_TIME { password_parameter_number_interval | UNLIMITED | DEFAULT }
    | PASSWORD_VERIFY_FUNCTION { <verify_policy> | NULL | DEFAULT }

<verify_policy> ::= 
      KISA_VERIFY_FUNCTION
    | ORA12C_VERIFY_FUNCTION
    | ORA12C_STRONG_VERIFY_FUNCTION
    | VERIFY_FUNCTION_11G 
    | VERIFY_FUNCTION

<password_parameter_number_interval> ::=
   integer 
 | integer / integer

Invocation and Access Rules

CREATE PROFILE ON DATABASE privilege is required to perform <profile definition>.

Syntax Rules and Parameters

profile_name

It specifies the profile name to be created.

password_parameters

It sets the parameters for password management.

The omitted parameters follow the "DEFAULT" profile policy.

FAILED_LOGIN_ATTEMPTS

It sets the number of consecutive login attempts allowed to fail.
If the failed attempts exceed the specified number, the account is locked.

PASSWORD_LOCK_TIME

It sets the period (days) which the account is locked after consecutive login failure.

PASSWORD_LIFE_TIME

It sets the life time of the password (day).

PASSWORD_GRACE_TIME

It sets the grace period of password expiration when logging in after PASSWORD_LIFE_TIME.

PASSWORD_GRACE_TIME starts at first login trial after the password life time. If the password is not altered during the grace period, the password expires.

PASSWORD_REUSE_MAX

It sets the number of the recent passwords which can not be reused when the user wants to reuse the old password.

PASSWORD_REUSE_MAX should be used together with PASSWORD_REUSE_TIME.

PASSWORD_REUSE_TIME

It sets the duration which the password can not be reused when the user wants to reuse the old password.

PASSWORD_REUSE_TIME should be used together with PASSWORD_REUSE_MAX.

PASSWORD_VERIFY_FUNCTION

It sets the password complexity verification methods.

KISA_VERIFY_FUNCTION

It is the password verification method of KISA (Korea Internet & Security Agency).

ORA12C_VERIFY_FUNCTION

It is the password verification method of Oracle, ORA12C_VERIFY_FUNCTION.

ORA12C_STRONG_VERIFY_FUNCTION

It is the password verification method of Oracle, ORA12C_STRONG_VERIFY_FUNCTION.

VERIFY_FUNCTION_11G

It is the password verification method of Oracle, VERIFY_FUNCTION_11G.

VERIFY_FUNCTION

It is the password verification method of Oracle, VERIFY_FUNCTION.

Description

Account Lockout

The followings are the parameters affecting the account lockout.

For example, when a user and a profile are created as follows.

CREATE PROFILE prof LIMIT
    FAILED_LOGIN_ATTEMPTS 4
    PASSWORD_LOCK_TIME 30;

ALTER USER u1 PROFILE prof;
If the user u1 fails to log in more than four times, the account is locked for 30 days. Then the account lockout is released after 30 days.
If PASSWORD_LOCK_TIME is UNLIMITED, the account lockout should be explicitly released by using ALTER USER statement.
ALTER USER user1 ACCOUNT UNLOCK;

Password Expiration

The followings are the parameters affecting the password expiration.

The password is expired in the following order.

  1. The password is set.

    • The time of the password expiration is set to the time elapsed as much as PASSWORD_LIFE_TIME since when a password is altered.

    • The password expiration status is OPEN, and it allows a normal login.

  1. When a user logs in after the password expiration

    • The login succeeds but the password expiration status becomes EXPIRED (GRACE) and the following warnings occur.

      • ERR-28000(16310): The password will expire in n days

      • ERR-28000(16311): The password will expire soon

      • The SQL standard does not cover the concepts of password expiration.

      • 28000 is the authentication warning or SQL standard status code of an error. 16310, 16311 are the GOLDILOCKS error code.

    • The time of the password expiration is reset to the time elapsed as much as PASSWORD_GRACE_TIME since when a user logged in.

  1. When a user logs in after the grace time

    • The password expiration status becomes EXPIRED, the user can not log in, and the following error occurs.

      • ERR-28000(16312): The password has expired

      • The SQL standard does not cover the concepts of password expiration.

      • 28000 is the authentication warning or SQL standard status code of an error. 16312 is the GOLDILOCKS error code.

      • GOLDILOCKS internal error code of 16312 should be used to control password reentering using program.

Password expiration status transition

Step

Point of time

login

Status

1

The password is changed.

Success

OPEN

2

PASSWORD_LIFE_TIME is elapsed.

Success with warning

EXPIRED(GRACE)

3

PASSWORD_GRACE_TIME is elapsed.

Error

EXPIRED

The following is another example.

CREATE PROFILE prof LIMIT
   PASSWORD_LIFE_TIME 90
   PASSWORD_GRACE_TIME 3;

ALTER USER u1 PROFILE prof;
The example above describes that the user u1 succeeds in login after 90 days of password expiration. However, the user receives a warning that the password expires in three days.
If the password is not changed within three days, the password expires.
Once the password expires, it reminds that the new password should be entered when logging in, and the account access is denied.

Password Reusability

The followings are the parameters affecting the password reusability.

The password reusability of the two parameters above is determined according to the following table.

Conditions for the password reusability

PASSWORD_REUSE_MAX

PASSWORD_REUSE_TIME

Reusable condition

value

value

It can be reused when both conditions of PASSWORD_REUSE_TIME and PASSWORD_REUSE_MAX are satisfied.

value

UNLIMITED

It can not be reused.

UNLIMITED

value

It can not be reused.

UNLIMITED

UNLIMITED

It can always be reused.

If a profile is created as follows,

CREATE PROFILE prof LIMIT
   PASSWORD_REUSE_MAX 5
   PASSWORD_REUSE_TIME 3;

the password can not be reused if it is the five recent passwords or the password changed within three days.

The following is an example of the user u1's password change history. If the current password is P # _000007 and the current date is 2015-08-08, the reusability of existing passwords is as follows.

Examples of password reusability

Password

Password_date

Password reusability

P#_000001

2015-08-01

It can be reused.

P#_000002

2015-08-02

It can be reused.

P#_000003

2015-08-03

It violates REUSE_MAX.

P#_000004

2015-08-04

It violates REUSE_MAX.

P#_000005

2015-08-05

It violates REUSE_MAX, REUSE_TIME.

P#_000006

2015-08-06

It violates REUSE_MAX, REUSE_TIME.

P#_000007

2015-08-07

It violates REUSE_MAX, REUSE_TIME.

The password change history accumulated for checking the password reusability can be deleted by using the following statement.

ALTER DATABASE CLEAR PASSWORD HISTORY;

DEFAULT profile

When creating the database, the following "DEFAULT" profile is automatically created. The password parameters of the "DEFAULT" profile are as follows.

Configuration of DEFAULT profile

Parameter

Value

FAILED_LOGIN_ATTEMPTS

10

PASSWORD_LOCK_TIME

1

PASSWORD_LIFE_TIME

180

PASSWORD_GRACE_TIME

7

PASSWORD_REUSE_MAX

UNLIMITED

PASSWORD_REUSE_TIME

UNLIMITED

PASSWORD_VERIFY_FUNCTION

NULL

The default values of "DEFAULT" profile have the following characteristics.

DEFAULT profile can not be dropped but it can be altered as follows.

ALTER PROFILE DEFAULT LIMIT ...

Examples

The following is an example of creating the profile to control the account lockout. The account is locked for three days after three consecutive login failures.

gSQL> CREATE PROFILE prof1 LIMIT
        FAILED_LOGIN_ATTEMPTS 3
        PASSWORD_LOCK_TIME 3;

Profile created.

gSQL> COMMIT;

Commit complete.

The following is an example of creating the profile to control the password expiration. The life time of the password is 90 days, and the grace time of the password is seven days.

gSQL> CREATE PROFILE prof1 LIMIT
        PASSWORD_LIFE_TIME 90 
        PASSWORD_GRACE_TIME 7;

Profile created.

gSQL> COMMIT;

Commit complete.

The following is an example of creating the profile to control whether the password is reusable. The following example does not verify the old password when changing the password.

gSQL> CREATE PROFILE prof1 LIMIT
        PASSWORD_REUSE_MAX  DEFAULT
        PASSWORD_REUSE_TIME DEFAULT;

Profile created.

gSQL> COMMIT;

Commit complete.

The following is an example of creating the profile to control the password complexity check.

gSQL> CREATE PROFILE prof1 LIMIT
        PASSWORD_VERIFY_FUNCTION KISA_VERIFY_FUNCTION;

Profile created.

gSQL> COMMIT;

Commit complete.

The following is an example of creating the profile by setting all parameter.

gSQL> CREATE PROFILE prof1 LIMIT
        FAILED_LOGIN_ATTEMPTS 3
        PASSWORD_LOCK_TIME 3
        PASSWORD_LIFE_TIME 90 
        PASSWORD_GRACE_TIME 7
        PASSWORD_REUSE_MAX  DEFAULT
        PASSWORD_REUSE_TIME DEFAULT
        PASSWORD_VERIFY_FUNCTION KISA_VERIFY_FUNCTION;

Profile created.

gSQL> COMMIT;

Commit complete.

Compatibility

The SQL standard does not cover the concepts of the profile.

For More Information

Refer to the followings.

CREATE SCHEMA

Function

It defines the schema.

Syntax

<schema definition> ::=
    CREATE SCHEMA <schema name clause>
        [ <schema element> [...] ]
    ;

<schema name clause> ::=
      schema_name
    | AUTHORIZATION user_identifier
    | schema_name AUTHORIZATION user_identifier

<schema element> ::=
      <table definition>
    | <view definition>
    | <index definition>
    | <sequence generator definition>
    | <grant privilege statement>
    | <comment statement>

Invocation and Access Rules

The user should satisfy the following conditions to perform <schema definition>.

Syntax Rules and Parameters

schema_name

It is the schema name to be created.
An identical schema name should not exist in the database.
The length of the schema name should be shorter than 128 bytes.

AUTHORIZATION user_identifier

If the schema name is omitted, a schema with the same name as the user_identifier is created.
If the AUTHORIZATION is not specified, the user_identifier of the user performing the statement is used.

schema_name AUTHORIZATION user_identifier

It specifies the schema name and schema owner to be created.
The owner can not be a role or PUBLIC.

<schema element>

It defines the objects to be created in the schema along with the schema creation.
The schema_element is executed in the listed order, and they are separated by a white space without a comma (,). 
The object can not be defined in a schema which has different name from the schema to be created.

Description

A schema is an object which logically classifies SQL schema objects such as table, view, index, sequence and constraint.
In GOLDILOCKS, the relationship between the user and the schema is 1 : N. In other words, the schema owned by a user may not exist, or the user may own multiple schemas.
The SQL standard does not explicitly define the relationship of the non-schema objects such as user, schema, database, but each DBMS defines the relationship between the non-schema objects as a different concept. Refer to the following note.

The relationship between user and schema in other DBMS





Examples

The following is an example of creating a schema.

gSQL> CREATE SCHEMA s1;

Schema created.

The following is an example of creating a schema and assigning the schema owner.

gSQL> CREATE SCHEMA s1 AUTHORIZATION test;

Schema created.

The following is an example of creating a schema together with the objects which belong to the schema.

gSQL> CREATE SCHEMA s1 
             CREATE TABLE t1 ( id INTEGER, name VARCHAR(128) )
             CREATE INDEX idx_t1_id ON t1 ( id )
             COMMENT ON TABLE t1 IS 'comment on s1.t1'
;

Schema created.

Compatibility

SQL standard compatibility

Feature ID

Description

Compatibility

S071

SQL paths in function and type name resolution

X

F461

Named character sets

X

F171

Multiple schemas per user

O

T332

Extended roles

X

For More Information

Refer to the followings.

CREATE SEQUENCE

Function

It creates a sequence.

Syntax

<sequence generator definition> ::=
    CREATE SEQUENCE [schema_name.] sequence_name 
        [ <sequence generator option> [, ...] ]
    ;

<sequence generator option> ::=
      <sequence generator start with option> 
    | <basic sequence generator option>

<sequence generator start with option> ::=
    START WITH integer

<basic sequence generator option> ::=
      <sequence generator increment by option>
    | <sequence generator maxvalue option>
    | <sequence generator minvalue option>
    | <sequence generator cycle option>
    | <sequence generator cache option>

<sequence generator increment by option> ::=
    INCREMENT BY integer

<sequence generator maxvalue option> ::=
      MAXVALUE integer
    | (NO MAXVALUE | NOMAXVALUE)

<sequence generator minvalue option> ::=
      MINVALUE integer
    | (NO MINVALUE | NOMINVALUE)

<sequence generator cycle option> ::=
      CYCLE 
    | (NO CYCLE | NOCYCLE)

<sequence generator cache option> ::=
      CACHE integer
    | (NO CACHE | NOCACHE)

Invocation and Access Rules

The user should have one of the following privileges to perform <sequence generator definition> statement.
• (CREATE SEQUENCE or CONTROL SCHEMA) ON SCHEMA for the schema to which the sequence 
   belongs
• CREATE ANY SEQUENCE ON DATABASE
The sequence owner is determined as follows.
• The owner of the schema to which the sequence belongs
• If the schema to which the sequence belongs is PUBLIC, then it is the user who executed the statement.

The sequence owner has USAGE ON SEQUENCE WITH GRANT OPTION privilege.

One of the following privileges is required to use the created sequence.
• USAGE ON SEQUENCE for the sequence
• (USAGE SEQUENCE or CONTROL SCHEMA) ON SCHEMA for the schema to which the sequence 
   belongs
• USAGE ANY SEQUENCE ON DATABASE

Syntax Rules and Parameters

sequence_name

It is the sequence name to be created, and it should be a unique name within the schema.
The schema to which the sequence belongs, such as schema_name.sequence_name, can be defined. If schema_name is omitted, the default schema name of the user performing the statement is used.
The length of the sequence name should be shorter than 128 bytes.

<sequence generator option>

If any of <sequence generator option> is not used, the following two statements have the same meaning.

<sequence generator start with option>

It defines the first sequence number to be generated.
Depending on the ascending or the descending order, it has the following features.

<sequence generator increment by option>

It defines the interval of sequence numbers.
The constraints and features are as follows.

<sequence generator maxvalue option>

It defines the maximum value of which the sequence can generate.

<sequence generator minvalue option>

It defines the minimum value of which the sequence can generate.

<sequence generator cycle option>

It specifies whether to continue generating a value when the sequence value becomes the maximum value or the minimum value.

<sequence generator cache option>

For quick access of a sequence, it defines the number of the sequence values to be preloaded in memory.
When restarting database, the sequence values loaded in memory are lost, and it starts from the value since being loaded.

Description

The sequence values of the created sequence objects are used by using NEXTVAL and CURRVAL functions.

The sequence value does not have a transaction property. The sequence value maintains the most recent value, even when an error occurs in the SQL statement in which the sequence function is used or when explicit ROLLBACK is performed.
CURRVAL function returns NEXTVAL value from the most recent call by a session. 
Therefore, using this feature, the sequence value obtained by NEXTVAL can still be usable in the other SQL statements. However, when the session does not call NEXTVAL, using CURRVAL function generates an error.

Examples

The object seq1 without the defined sequence options is an ascending sequence of the same meanings as the object seq2 in the following example.

gSQL> CREATE SEQUENCE seq1;

Sequence created.


gSQL> CREATE SEQUENCE seq2 START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE NO CYCLE CACHE 20;

Sequence created.

The following is an example of a sequence which generates an odd value.

gSQL> CREATE SEQUENCE seq1 START WITH 1 INCREMENT BY 2;

Sequence created.

The following is an example of generating sequence which repeatedly generates an even number starting from 0 to 1000.

gSQL> CREATE SEQUENCE seq1 START WITH 0 MINVALUE 0 MAXVALUE 1000 INCREMENT BY 2 CYCLE;

Sequence created.

The following is an example of generating a descending sequence starting from -1.

gSQL> CREATE SEQUENCE seq1 INCREMENT BY -1;

Sequence created.

Compatibility

The SQL standard does not define <sequence generator cache option> clause.

SQL standard compatibility

Feature ID

Description

Compatibility

T176

Sequence generator support

O

For More Information

Refer to the followings.

CREATE SYNONYM

Function

It creates a synonym. A synonym is an alternative name for a table, view, sequence, or another synonym, and it can be used in the following statements.

Syntax

<synonym definition> ::=    
    CREATE [OR REPLACE] [PUBLIC] SYNONYM [schema_name.]synonym_name 
    FOR [schema_name.]object_name
    ;

Invocation and Access Rules

The user should satisfy the following conditions to perform <synonym definition> statement.

Syntax Rules and Parameters

[ OR REPLACE ]

It replaces the existing synonym if the synonym already exists.

[ PUBLIC ]

It is specified when creating public synonym.
If it is omitted, private synonym is created.

synonym_name

It is the synonym name to be created, and it should be a unique name within the schema.
The schema to which the synonym belongs, such as schema_name.synonym_name, can be defined. If schema_name is omitted, default schema name of the user performing the statement is used.
The length of the synonym name should be shorter than 128 bytes.
Public synonym is a non-schema object. Therefore, a schema name can not be specified when creating public synonym by explicitly specifying PUBLIC.

object_name

The schema to which the object belongs, such as schema_name.object_name, can be defined. If schema_name is omitted, default schema name of the user performing the statement is used.
The object types which can specify the object_name are as follows.

Existence of the target object, cycle check and privilege check are performed when executing the statement using the synonym.

Description

A synonym is an alternative name for a table, view, sequence, or another synonym.

If synonym is created, the applications do not need to be modified even when the base object is changed instead only the synonyms should be redefined. Therefore, it is convenient. 
Also, the database security is improved by hiding the objects' real names and their schemas, and the usability is enhanced by changing the object's long name to a shorter name.

The synonym is literally an alternative name so creating the synonym does not mean that the synonym can be used to access the object. The proper privilege is required to access the object.

When executing the statement using the synonym, the object access procedure is as follows.
  1. Find a table of the corresponding name.

  2. If the table does not exist, find the private synonym of the corresponding name.

  3. If the private synonym does not exist, find the public synonym of the corresponding name.

gSQL> CREATE PUBLIC SYNONYM syn1 FOR u1.t1;

Synonym created.

gSQL> CREATE PUBLIC SYNONYM syn2 FOR syn1;

Synonym created.

gSQL> SELECT * FROM syn2;
The example above is the object access procedure in SELECT statement.
  1. It searched for the table syn2, but it does not exist.

  2. It searched for the private synonym syn2, but it does not exist.

  3. It searched for the public synonym syn2, and it exists.

    1. It searched for the table syn1, but it does not exist.

    2. It searched for the private synonym syn1, but it does not exist.

    3. It searched for the public synonym syn2, and it exists.

      1. It searched for the table u1.t1, and it exists.

Examples

The following is an example of creating a private synonym.

gSQL> CREATE SYNONYM MyEmp FOR branch.Employee;

Synonym created.


gSQL> SELECT * FROM MyEmp;

The following is an example of creating a public synonym.

gSQL> CREATE PUBLIC SYNONYM MainEmp FOR main.Employee;

Synonym created.


gSQL> SELECT * FROM MainEmp;

Compatibility

The SQL standard does not define the CREATE SYNONYM statement.

For More Information

Refer to DROP SYNONYM.

CREATE TABLE

Function

It defines a table.

Syntax

<table definition> ::=
    CREATE TABLE table_name
        ( <table element> [, ...] )
        [ <table sharding strategy> ]
        [ <table attribute clause> [...] ]
        [ TABLESPACE tablespace_name ]
        [ <table global secondary index clause> ]
    ;

<table element> ::=
      <column definition>
    | <table constraint definition>

<column definition> ::=
    column_name <data type> 
        [ <default clause> | <identity column specification> ]
        [ <column constraint definition> ]

<data type> ::=
      <character string type>
    | <binary string type>
    | <numeric type>
    | <boolean type>
    | <datetime type>
    | <interval type>

<character string type> ::=
      CHARACTER [ ( integer [ <character length units> ] ) ]
    | CHAR [ ( integer [ <character length units> ] ) ]
    | CHARACTER VARYING ( integer [ <character length units> ] )
    | CHAR VARYING ( integer [ <character length units> ] )
    | VARCHAR ( integer [ <character length units> ] )
    | CHARACTER LONG VARYING
    | LONG VARCHAR
  
<character length units> ::=
      CHARACTERS
    | CHAR
    | OCTETS
    | BYTE

<binary string type> ::=
      BINARY [ ( length ) ]
    | BINARY VARYING ( length )
    | VARBINARY ( length )
    | LONG BINARY VARYING
    | LONG VARBINARY

<numeric type> ::=
      <exact numeric type>
    | <approximate numeric type>
    | <native numeric type>

<exact numeric type> ::=
      NUMERIC [ ( precision [, scale ] ) ]
    | SMALLINT
    | INTEGER
    | INT
    | BIGINT

<approximate numeric type> ::=
    | FLOAT [ ( precision ) ]
    | REAL
    | DOUBLE PRECISION

<native numeric type> ::=
      NATIVE_SMALLINT
    | NATIVE_INTEGER
    | NATIVE_BIGINT
    | NATIVE_REAL
    | NATIVE_DOUBLE

<boolean type> ::=
    BOOLEAN

<datetime type> ::=
      DATE
    | TIME [ ( time_precision ) ] [ WITH TIME ZONE | WITHOUT TIME ZONE ]
    | TIMESTAMP [ ( timestamp_precision ) ] [ WITH TIME ZONE | WITHOUT TIME ZONE ]

<interval type> ::=
    INTERVAL <interval qualifier>

<interval qualifier> ::=
      <non-second primary datetime field> [ ( interval_leading_field_precision ) ]
          TO { <non-second primary datetime field> | SECOND [ ( interval_fractional_seconds_precision ) ] }
    | <non-second primary datetime field> [ ( interval_leading_field_precision ) ]
    | SECOND [ ( interval_leading_field_precision [, interval_fractional_seconds_precision ] ) ]

<non-second primary datetime field> ::=
      YEAR
    | MONTH
    | DAY
    | HOUR
    | MINUTE

<default clause> ::=
    DEFAULT <default option>

<default option> ::=
      constant
    | NULL
    | expression

<identity column specification> ::=
    GENERATED { ALWAYS | BY DEFAULT } AS IDENTITY 
    [ ( <common sequence generator option> [, ...] ) ]

<common sequence generator option> ::=
      START WITH integer_constant
    | <basic sequence generator option>

<basic sequence generator option> ::=
      INCREMENT BY integer_constant 
    | { MAXVALUE integer_constant | NO MAXVALUE }
    | { MINVALUE integer_constant | NO MINVALUE }
    | { CYCLE | NO CYCLE }
    | { CACHE integer_constant | NO CACHE }

<column constraint definition> ::=
    [ CONSTRAINT constraint_name ] <column constraint> [ <constraint characteristics> ]

<column constraint> ::=
      NOT NULL
    | { UNIQUE | PRIMARY KEY } [ <index name clause> [ <index attributes> ] [ TABLESPACE index_tablespace_name ] ]

<index name clause> ::=
    INDEX index_name

<index attributes> ::=
      <index physical attribute clause>
    | STORAGE ( <segment attr clause> [...] )


<table constraint definition> ::=
    [ CONSTRAINT constraint_name ] <table constraint> [ <constraint characteristics> ]

<table constraint> ::=
      <unique constraint definition> [ <index name clause> [ <index attributes> ] [ TABLESPACE index_tablespace_name ] ]

<unique constraint definition> ::=
    { UNIQUE | PRIMARY KEY } ( <key column element> [, ...] )

<key column element> ::=
    column_name [ ASC | DESC ] [ NULLS FIRST | NULLS LAST ]


<table sharding strategy> ::=
      <cloned strategy>
    | <hash sharding strategy>
    | <range sharding strategy>
    | <list sharding strategy>

<cloned strategy> ::=
    CLONED [ <clone placement> ]

<clone placement> ::=
      AT CLUSTER WIDE
    | AT CLUSTER GROUP group_list

<hash sharding strategy> ::=
    SHARDING BY [HASH] ( column_list )
    [ <hash shard count> ]
    [ <hash shard placement> ]

<hash shard count> ::=
    SHARD COUNT integer

<hash shard placement> ::=
      AT CLUSTER WIDE
    | AT CLUSTER GROUP group_list

<range sharding strategy> ::=
    SHARDING BY RANGE ( column_list )
    { <cluster-wide range shard placement> | <group-specific range shard placement> }

<cluster-wide range shard placement> ::=
    AT CLUSTER WIDE
    <range shard definition> [, ...]

<group-specific range shard placement> ::=
    <group-specific range shard definition> [, ...]

<group-specific range shard definition> ::=
    <range shard definition> AT CLUSTER GROUP group_name

<range shard definition> ::=
    SHARD range_name VALUES LESS THAN ( <range value clause> )

<range value clause> ::=
    <range value> [, ...]

<range value> ::=
      constant
    | MAXVALUE

<list sharding strategy> ::=
    SHARDING BY LIST ( column_name )
    { <cluster-wide list shard placement> | <group-specific list shard placement> }

<cluster-wide list shard placement> ::=
    AT CLUSTER WIDE
    <list shard definition> [, ...]

<group-specific list shard placement> ::=
    <group-specific list shard definition> [, ...]

<group-specific list shard definition> ::=
    <list shard definition> AT CLUSTER GROUP group_name

<list shard definition> ::=
      SHARD shard_name VALUES IN ( <list value clause> )

<list value clause> ::=
    <list value> [, ...]

<list value> ::=
      constant
    | NULL
    | DEFAULT


<table attribute clause> ::=
      [ <table physical attribute clause> ]
    | [ STORAGE ( <segment attr clause> [...] ) ]

<table physical attribute clause> ::=
      PCTFREE integer
    | PCTUSED integer
    | INITRANS integer
    | MAXTRANS integer

<index physical attribute clause> ::=
      PCTFREE integer
    | INITRANS integer
    | MAXTRANS integer

<segment attr clause> ::=
      INITIAL <size_clause>
    | NEXT <size_clause>
    | MINSIZE <size_clause>
    | MAXSIZE <size_clause>

<size clause> ::=
      integer [ K | M | G | T ]


<constraint characteristics> ::=
      [ NOT ] DEFERRABLE [ <constraint check time> ]
    | <constraint check time> [ [ NOT ] DEFERRABLE ]

<constraint check time> ::=
      INITIALLY DEFERRED 
    | INITIALLY IMMEDIATE

<table global secondary index clause> ::=
      WITH GLOBAL SECONDARY INDEX [ <index attributes> [...] ] [ TABLESPACE tablespace_name ]
    |  WITHOUT GLOBAL SECONDARY INDEX

Invocation and Access Rules

The differences between the stand-alone database and the cluster database are as follows.

The user should satisfy the following conditions to perform <table definition> statement.

<table sharding strategy> statement can be used in a cluster system.

Syntax Rules and Parameters

table_name

It is the table name to be created and it should be a unique name within the schema.
The schema to which the table belongs, such as schema_name.table_name, can be defined. If schema_name is omitted, the default schema name of the user performing the statement is used.
The length of the table name should be shorter than 128 bytes.

<column definition>

It defines the columns which configure the table.
The table should include one or more column definitions. 
It can specify the column data type, default value, automatically generated value, and constraints.

column_name

It is name of the column which configures a table and each column should have a unique name within the table.
The length of the column name should be shorter than 128 bytes.

<data type>

It defines the data type of the column.
When defining the column including automatically generated values(<identity column specification>), its data type should be one of SMALLINT, INTEGER or BIGINT.
For more information about data types, refer to Data Type.

<character length units>

It specifies the length unit of a single character for the character type.

The SQL standard defines CHARACTERS as a default value.

The default value of the char length unit in other DBMS are as follows.

[ <default clause> | <identity column specification> ]

It specifies the default value of a column.
<default clause> and <identity column specification> can not be used together.
When both of them are omitted, the default value is NULL.

<default clause>

The DEFAULT clause defines the default value to be used when DEFAULT is specified in INSERT, UPDATE statements or the corresponding column name is omitted.

The data type of DEFAULT expression should be compatible with the data type of the column.
If the data type is not compatible or the space is insufficient, an error occurs when using DEFAULT in INSERT, UPDATE statements.
DEFAULT expression can use any built-in functions but it can not use the followings.

<identity column specification>

It defines a column which has automatically generated values.
The table can have only one identity column.
The identity column becomes not nullable column even though NOT NULL constraint is not specified.
<identity column specification> clause can not be specified together with DEFAULT clause.
<identity column specification> clause, like as DEFAULT clause, specifies DEFAULT in INSERT, UPDATE statements or it defines the default value to be used when the column name is omitted.

The generation method is defined as follows.

For more information about <common sequence generator option> and <basic sequence generator option>, which are options to create an identity column, refer to CREATE SEQUENCE.

<column constraint definition>

It defines the following constraints for a column.

constraint_name

It is the constraint name and it can be omitted.
If the constraint_name is omitted, it is automatically set as follows.
If the automatically generated name is duplicated, the constraint_name should be explicitly specified.

The length of the constraint name should be shorter than 128 bytes.

NOT NULL Constraint

NULL is not allowed for the column value.

UNIQUE Constraint

The identical value is not allowed for the column value, but NULL is allowed.

PRIMARY KEY Constraint

NULL or the identical value is not allowed as the column value. A single PRIMARY KEY constraint can be defined on a single table.

<index name clause>

It defines the index name to be created when defining UNIQUE constraint and PRIMARY KEY constraint.

When defining UNIQUE constraint and PRIMARY KEY constraint, if INDEX clause is omitted, an index which satisfies the constraints is automatically created.
"constraint_name" + "INDEX" is added to the name of index which is automatically generated.

<table constraint definition>

<unique constraint definition>

The table constraint definition has the following syntactic difference compared to the column constraint definition.

key column element

It specifies the column to be a target of the key.

<table sharding strategy>

It defines the sharding strategy of a table.
It can be defined as one of the four following strategies.

If it is omitted, it is determined by DEFAULT_SHARDING property value.

<cloned strategy>

It clones all data in a table.

<clone placement>

It defines the placement strategy of a clone.

<hash sharding strategy>

It shards the table data according to the hash value of the sharding key.

SHARDING BY [HASH] ( column_list )

It defines a sharding key for a hash sharding.

<hash shard count>

It defines the number of the hash shards to be sharded.
The number of shards can be defined from 1 to 512.
If it is omitted, the default value is 24.

<hash shard placement>

It defines the placement strategy of a hash shard.

<range sharding strategy>

It shards the table data according to the range value of the sharding key.

SHARDING BY RANGE ( column_list )

It defines a sharding key for the range sharding.

<cluster-wide range shard placement>

It automatically places range shards in all cluster groups of a cluster system.
AT CLUSTER WIDE statement is described before describing <range shard definition>.
Shards can be relocated by using ALTER TABLE name REBALANCE statement when adding a cluster group and a cluster member.
CREATE TABLE t1 
(
   id   INTEGER,
   name VARCHAR(32)
)
SHARDING BY RANGE (id)
    AT CLUSTER WIDE
    SHARD s1 VALUES LESS THAN ( 200000 ),
    SHARD s2 VALUES LESS THAN ( 400000 ),
    SHARD s3 VALUES LESS THAN ( 500000 ),
    SHARD s4 VALUES LESS THAN ( 600000 ),
    SHARD s5 VALUES LESS THAN ( 800000 ),
    SHARD s6 VALUES LESS THAN ( MAXVALUE )
;
CREATE CLUSTER GROUP g4 
       CLUSTER MEMBER g4n1 HOST '192.168.0.41' PORT 10401
;
ALTER TABLE t1 REBALANCE;

<group-specific range shard placement>

It places range shards in a specified cluster group.
It describes AT CLUSTER GROUP group_name statement which places that shard together with <range shard definition>.
Shards can be automatically relocated by using ALTER TABLE name REBALANCE statement when adding a cluster member to a specified cluster group.
Adding a cluster group does not affect the relocation of the range shard.
CREATE TABLE t1 
(
   id   INTEGER,
   name VARCHAR(32)
)
SHARDING BY RANGE (id)
    SHARD s1 VALUES LESS THAN ( 200000 )   AT CLUSTER GROUP g1,
    SHARD s2 VALUES LESS THAN ( 400000 )   AT CLUSTER GROUP g2,
    SHARD s3 VALUES LESS THAN ( 500000 )   AT CLUSTER GROUP g3,
    SHARD s4 VALUES LESS THAN ( 600000 )   AT CLUSTER GROUP g2,
    SHARD s5 VALUES LESS THAN ( 800000 )   AT CLUSTER GROUP g3,
    SHARD s6 VALUES LESS THAN ( MAXVALUE ) AT CLUSTER GROUP g1
;
CREATE CLUSTER GROUP g4 
       CLUSTER MEMBER g4n1 HOST '192.168.0.41' PORT 10401
;
ALTER TABLE t1 REBALANCE;

<range shard definition>

SHARD range_name should be unique in a table.
It can define maximum 512 of <range shard definition>.
The listed <range shard definition> is sorted in an order of <range value clause>, and it should use each different <range value clause>.
The <range shard definition> whose all values are define as MAXVALUE is a MAX shard.
MAX shard should exist, and it should be a single one.
gSQL>
CREATE TABLE t1 
(
   id INTEGER,
   name VARCHAR(32)
)
SHARDING BY RANGE (id)
   AT CLUSTER WIDE
   SHARD s1 VALUES LESS THAN ( 100000 ),
   SHARD s2 VALUES LESS THAN ( 200000 ),
   SHARD s3 VALUES LESS THAN ( MAXVALUE )
;

Table created.
gSQL>
CREATE TABLE t1 
(
   id INTEGER,
   name VARCHAR(32)
)
SHARDING BY RANGE (id)
   AT CLUSTER WIDE
   SHARD s1 VALUES LESS THAN ( 100000 ),
   SHARD s2 VALUES LESS THAN ( 200000 ),
   SHARD s3 VALUES LESS THAN ( 300000 )
;

ERR-42000(16377): MAX shard not defined : 
   SHARD s3 VALUES LESS THAN ( 300000 )
   *
ERROR at line 10:

<range value clause>

<range value> should be a constant or a MAXVALUE (a maximum value).

NULL can not be used as <range value>.

MAXVALUE is always bigger than any other value, and it includes null.

If there are multiple sharding keys, only a MAXVALUE can be specified after the MAXVALUE.

If a sharding key is defined by using multiple columns, a MAX shard which is listed with MAXVALUE for its all values as like the SHARD s3 below should exist.

CREATE TABLE t1 
(
   id INTEGER,
   name VARCHAR(32)
)
SHARDING BY RANGE (id, name)
   AT CLUSTER WIDE
   SHARD s1 VALUES LESS THAN ( 100000, MAXVALUE ),
   SHARD s2 VALUES LESS THAN ( 200000, 20000 ),
   SHARD s3 VALUES LESS THAN ( MAXVALUE, MAXVALUE )
;

<list sharding strategy>

It shards the table data according to the listed value of the sharding key.

SHARDING BY LIST ( column_name )

It defines a sharding key for a list sharding.

<cluster-wide list shard placement>

It automatically places list shards in all cluster groups of a cluster system.
AT CLUSTER WIDE statement is described before describing <range shard definition>.
Shards can be relocated by using ALTER TABLE name REBALANCE statement when adding a cluster group and a cluster member.
CREATE TABLE city 
(
   id   INTEGER,
   name VARCHAR(32)
)
SHARDING BY LIST (name)
    AT CLUSTER WIDE
    SHARD s1 VALUES IN ( 'SEOUL' ),
    SHARD s2 VALUES IN ( 'PUSAN', 'ULSAN', 'DAEGU' ),
    SHARD s3 VALUES IN ( 'DAEJEON', 'GWANGJU' ),
    SHARD s4 VALUES IN ( 'ANSAN', 'GOYANG' ),
    SHARD s5 VALUES IN ( DEFAULT )
;
CREATE CLUSTER GROUP g4 
       CLUSTER MEMBER g4n1 HOST '192.168.0.41' PORT 10401
;
ALTER TABLE t1 REBALANCE;

<group-specific list shard placement>

It places list shards in a specified cluster group.
It describes AT CLUSTER GROUP group_name statement which places that shard together with <list shard definition>.
Shards can be automatically relocated by using ALTER TABLE name REBALANCE statement when adding a cluster member to a specified cluster group.
Adding a cluster group does not affect the relocation of the list shard.
CREATE TABLE city 
(
   id   INTEGER,
   name VARCHAR(32)
)
SHARDING BY LIST (name)
    SHARD s1 VALUES IN ( 'SEOUL' )                   AT CLUSTER GROUP g1,
    SHARD s2 VALUES IN ( 'PUSAN', 'ULSAN', 'DAEGU' ) AT CLUSTER GROUP g2,
    SHARD s3 VALUES IN ( 'DAEJEON', 'GWANGJU' )      AT CLUSTER GROUP g3,
    SHARD s4 VALUES IN ( 'ANSAN', 'GOYANG' )         AT CLUSTER GROUP g2,
    SHARD s5 VALUES IN ( DEFAULT )                   AT CLUSTER GROUP g1
;
CREATE CLUSTER GROUP g4 
       CLUSTER MEMBER g4n1 HOST '192.168.0.41' PORT 10401
;
ALTER TABLE t1 REBALANCE;

<list shard definition>

LIST list_name should be unique in a table.
It can define maximum 512 of <list shard definition>.
All <list value> of the listed <list shard definition> should be different each other.
DFFAULT are other values which is not the listed <list value>.
DFFAULT can not be defined together with another value.
A shard including DEFAULT is a DEFAULT shard.
MAX shard should exist, and it should be a single one.
gSQL>
CREATE TABLE t1 
(
   category INTEGER,
   name     VARCHAR(32)
)
SHARDING BY LIST (category)
   AT CLUSTER WIDE
   SHARD s1 VALUES IN ( 1, 3, 5, 7 ),
   SHARD s2 VALUES IN ( 2, 4, 6, 8 ),
   SHARD s3 VALUES IN ( DEFAULT )
;

Table created.
gSQL>

CREATE TABLE t1 
(
   category INTEGER,
   name     VARCHAR(32)
)
SHARDING BY LIST (category)
   AT CLUSTER WIDE
   SHARD s1 VALUES IN ( 1, 3, 5, 7 ),
   SHARD s2 VALUES IN ( 2, 4, 6, 8 ),
   SHARD s3 VALUES IN ( 9, 10 )
;

ERR-42000(16385): DEFAULT shard not defined : 
   SHARD s3 VALUES IN ( 9, 10 )
   *
ERROR at line 10:

<list value clause>

<list value> should be a constant.
NULL or DEFAULT can be used as <list value>.

<table physical attribute clause>

It defines the physical attribute information of the table.

<index physical attribute clause>

It defines the physical attributes of the index.

<segment attr clause>

It describes the information about the space in which the table is stored.

<size clause>

It specifies the file size in bytes. (If it is omitted, the default unit is bytes.)

TABLESPACE tablespace_name

It specifies the tablespace name in which a table is to be stored.
If TABLESPACE clause is omitted, the default tablespace_name of the user performing the statement is used.

TABLESPACE index_tablespace_name

It specifies the tablespace name in which an index is to be stored.
If TABLESPACE clause is omitted, then it uses the index tablespace of the user. 
If the index tablespace of the user is NULL, then the DISK table uses the user's data tablespace and the MEMORY table uses the user's default temporary tablespace.

<constraint characteristics>

It defines characteristics of the constraint.
When defining constraints, the following characteristics can be set.

If <constraint characteristics> is omitted, it is set to NOT DEFERRABLE INITIALLY IMMEDIATE.

DEFERRABLE | NOT DEFERRABLE

It sets whether the constraints checking is deferrable so that the constraints can be checked when executing COMMIT without checking when executing DML statements.

The checking time of the deferrable constraint is controlled by SET CONSTRAINTS.

<constraint check time>

If the constraints are DEFERRABLE, it sets an initial value for the checking time.

For more information about the deferrable constraints, refer to SET CONSTRAINTS.

<table global secondary index clause>

It defines a global secondary index of the table.

Description

Constraint Characteristics

GOLDILOCKS automatically creates an index to check the uniqueness when generating key constraints.

The following columns do not allow NULL value.

Cluster Table

A table manages data using one of the following sharding strategies in a cluster environment.

The sharding strategy is determined considering the followings when creating a table. Tables operated in a cluster system are specified as a code table and a fact table based on its features.

<cloned strategy> is appropriate for a code table, and an appropriate <table sharding strategy> should be determined according to the table access pattern in case of a fact table.

Examples

The following is an example of generating an ordinary table.

gSQL> CREATE TABLE region
(
    r_regionkey   INTEGER
  , r_name        CHAR(25)
  , r_comment     VARCHAR(152)
);

Table created.

The following is an example of specifying the constraints on the columns when creating a table.

gSQL> CREATE TABLE supplier
(
    s_suppkey     INTEGER PRIMARY KEY
  , s_name        CHAR(25) NOT NULL
  , s_address     VARCHAR(40)
  , s_nationkey   INTEGER
  , s_phone       CHAR(15)
  , s_acctbal     NUMERIC(12,2)
  , s_comment     VARCHAR(101)
);

Table created.

The following is an example of specifying the constraint which includes multiple columns when creating a table.

gSQL> CREATE TABLE partsupp
(
    ps_partkey    INTEGER
  , ps_suppkey    INTEGER
  , ps_availqty   INTEGER
  , ps_supplycost NUMERIC(12,2)    
  , ps_comment    VARCHAR(199)
  , CONSTRAINT ps_unique_key UNIQUE(ps_partkey, ps_suppkey)
);

Table created.

The following is an example of specifying whether constraints are deferrable when creating a table.

gSQL> CREATE TABLE t1 
( 
    id     NUMBER        PRIMARY KEY 
                         NOT DEFERRABLE INITIALLY IMMEDIATE
  , name   VARCHAR(128)  CONSTRAINT t1_nn NOT NULL 
                         DEFERRABLE INITIALLY IMMEDIATE
  , addr   VARCHAR(1024) 
  , CONSTRAINT t1_uk UNIQUE ( id, name ) 
                     DEFERRABLE INITIALLY DEFERRED
);

Table created.

gSQL> COMMIT;

Commit complete.

The following is an example of specifying a column including automatically generated values and the default value when creating a table.

CREATE TABLE customer
(
    c_custkey     INTEGER   GENERATED BY DEFAULT AS IDENTITY
  , c_name        VARCHAR(25)
  , c_address     VARCHAR(40) DEFAULT 'N/A'
  , c_nationkey   INTEGER
  , c_phone       CHAR(15)
  , c_acctbal     NUMERIC(12,2)
  , c_mktsegment  CHAR(10)
  , c_comment     VARCHAR(117)
);

Table created.

The following is an example of specifying the tablespace which is to be stored when creating a table.

gSQL> CREATE TABLE lineitem
(
    l_orderkey      INTEGER
  , l_partkey       INTEGER
  , l_suppkey       INTEGER
  , l_linenumber    INTEGER
  , l_quantity      NUMERIC(12,2)
  , l_extendedprice NUMERIC(12,2)
  , l_discount      NUMERIC(12,2)
  , l_tax           NUMERIC(12,2)
  , l_returnflag    CHAR(1)
  , l_linestatus    CHAR(1)
  , l_shipdate      DATE
  , l_commitdate    DATE
  , l_receiptdate   DATE
  , l_shipinstruct  CHAR(25)
  , l_shipmode      CHAR(10)
  , l_comment       VARCHAR(44)
  , PRIMARY KEY (l_orderkey, l_linenumber) INDEX lineitem_pk_idx TABLESPACE mem_temp_tbs
) TABLESPACE mem_data_tbs;

Table created.

The following is an example of defining a cluster-wide cloned table. The table data is copied and placed all over the cluster system.

gSQL>
CREATE TABLE region
(
    r_regionkey   INTEGER
  , r_name        CHAR(25)
  , r_comment     VARCHAR(152)
)
CLONED
AT CLUSTER WIDE
;

Table created.

The following is an example of defining a group-specific cloned table. The table data is copied and placed in a cluster group g1 and g2 specified by a user.

gSQL> 
CREATE TABLE region
(
    r_regionkey   INTEGER
  , r_name        CHAR(25)
  , r_comment     VARCHAR(152)
)
CLONED
AT CLUSTER GROUP g1, g2
;

Table created.

The following is an example of defining a cluster-wide hash sharded table. The table data is divided into 24 shards based on the hash value of a ps_partkey column, and each shard is automatically placed all over the cluster system.

gSQL>
CREATE TABLE partsupp
(
    ps_partkey    INTEGER
  , ps_suppkey    INTEGER
  , ps_availqty   INTEGER
  , ps_supplycost NUMERIC(12,2)    
  , ps_comment    VARCHAR(199)
)
SHARDING BY HASH ( ps_partkey )
SHARD COUNT 24
AT CLUSTER WIDE
;

Table created.

The following is an example of defining a group-specific hash sharded table. The table data is divided into 24 shards based on the hash value of a ps_partkey column, and each shard is automatically placed in the specified cluster groups g2 and g3.

gSQL>
CREATE TABLE partsupp
(
    ps_partkey    INTEGER
  , ps_suppkey    INTEGER
  , ps_availqty   INTEGER
  , ps_supplycost NUMERIC(12,2)    
  , ps_comment    VARCHAR(199)
)
SHARDING BY HASH ( ps_partkey )
SHARD COUNT 24
AT CLUSTER GROUP g2, g3
;

Table created.

The following is an example of defining a cluster-wide range sharded table. The table data is divided into 24 shards based on the range value of D_ID column, and each shard is automatically placed all over the cluster system.

gSQL>
CREATE TABLE DISTRICT (
    D_ID        INTEGER, 
    D_W_ID      INTEGER, 
    D_NAME      VARCHAR(10), 
    D_STREET_1  VARCHAR(20), 
    D_STREET_2  VARCHAR(20), 
    D_CITY      VARCHAR(20), 
    D_STATE     CHAR(2), 
    D_ZIP       CHAR(9), 
    D_TAX       NUMERIC(4,4), 
    D_YTD       NUMERIC(15,2), 
    D_NEXT_O_ID INTEGER,

    PRIMARY KEY (D_W_ID, D_ID) INDEX DISTRICT_PK_IDX
) 
    SHARDING BY RANGE (D_ID)
    AT CLUSTER WIDE
    SHARD s1 VALUES LESS THAN ( 100 ),
    SHARD s2 VALUES LESS THAN ( 200 ),
    SHARD s3 VALUES LESS THAN ( 300 ),
    SHARD s4 VALUES LESS THAN ( 400 ),
    SHARD s5 VALUES LESS THAN ( 500 ),
    SHARD s6 VALUES LESS THAN ( 600 ),
    SHARD s7 VALUES LESS THAN ( 700 ),
    SHARD s8 VALUES LESS THAN ( MAXVALUE );
;

Table created.
The following is an example of defining a group-specific range sharded table. The table data is divided into three range values based on the range value of a NO_D_ID column, and a shard s1 is placed in a cluster group g1, a shard s2 is placed in a cluster group g2, a shard s3 is placed in a cluster group g3.
gSQL>
CREATE TABLE NEW_ORDER
(
    NO_O_ID INTEGER,
    NO_D_ID INTEGER,
    NO_W_ID INTEGER,

    PRIMARY KEY(NO_W_ID, NO_D_ID, NO_O_ID) INDEX NEW_ORDER_PK_IDX
) 
    SHARDING BY RANGE (NO_D_ID)
    SHARD s1 VALUES LESS THAN ( 5 )        AT CLUSTER GROUP g1,
    SHARD s2 VALUES LESS THAN ( 8 )        AT CLUSTER GROUP g2,
    SHARD s3 VALUES LESS THAN ( MAXVALUE ) AT CLUSTER GROUP g3
;

Table created.

The following is an example of defining a cluster-wide list sharded table. A list shard is divided into five based on a city column, and each shard is automatically placed all over the cluster system.

gSQL>
CREATE TABLE t1 
(
    id   INTEGER
  , name VARCHAR(32)
  , city VARCHAR(128) 
) 
   SHARDING BY LIST (city)
      AT CLUSTER WIDE
      SHARD s1 VALUES IN ( 'seoul' ),
      SHARD s2 VALUES IN ( 'busan', 'ulsan' ),
      SHARD s3 VALUES IN ( 'suwon', 'ansan', 'osan' ),
      SHARD s4 VALUES IN ( 'goyang', 'paju', 'guri' ),
      SHARD s5 VALUES IN ( DEFAULT )            
;

Table created.

The following is an example of defining a group-specific list sharded table. A list shard is divided into five based on a city column, and each shard is placed in a specified cluster group.

gSQL>
CREATE TABLE t1 
(
    id   INTEGER
  , name VARCHAR(32)
  , city VARCHAR(128) 
) 
   SHARDING BY LIST (city)
      SHARD s1 VALUES IN ( 'seoul' )                  AT CLUSTER GROUP g1,
      SHARD s2 VALUES IN ( 'busan', 'ulsan' )         AT CLUSTER GROUP g2,
      SHARD s3 VALUES IN ( 'suwon', 'ansan', 'osan' ) AT CLUSTER GROUP g1,
      SHARD s4 VALUES IN ( 'goyang', 'paju', 'guri' ) AT CLUSTER GROUP g2,
      SHARD s5 VALUES IN ( DEFAULT )                  AT CLUSTER GROUP g3
;

Table created.

A table T1 is created without a global secondary index.

gSQL> CREATE TABLE T1 ( I1 INTEGER, I1 CHAR(32) )  WITHOUT GLOBAL SECONDARY INDEX;

Table created.

A global secondary index is created after creating a table T1.

gSQL> CREATE TABLE T1 ( I1 INTEGER, I1 CHAR(32) )  WITH GLOBAL SECONDARY INDEX;

Table created.

A global secondary index of table T1 is created in a tablespace USER_DATA_TBS as a logging index after creating a table T1.

gSQL> CREATE TABLE T1 ( I1 INTEGER, I1 CHAR(32) ) 
      WITH GLOBAL SECONDARY INDEX
      TABLESPACE USER_DATA_TBS;

Table created.
A global secondary index of table T1 is created in a tablespace USER_TEMP_TBS as a nologging  index after creating a table T1.
gSQL> CREATE TABLE T1 ( I1 INTEGER, I1 CHAR(32) ) 
      WITH GLOBAL SECONDARY INDEX
      TABLESPACE USER_TEMP_TBS;

Table created.

Compatibility

The SQL standard does not define the following clauses.

SQL standard compatibility

Feature ID

Description

Compatibility

T171

LIKE clause in table definition

X

F531

Temporary tables

X

S051

Create table of type

X

S043

Enhanced reference types

X

S081

Subtables

X

T173

Extended LIKE clause in table definition

X

T180

System-versioned tables

X

F692

Extended collation support

X

T174

Identity columns

O

T175

Generated columns

X

S071

SQL paths in function and type name resolution

X

F321

User authorization

O

T322

Extended roles

X

F762

CURRENT_CATALOG

O

F763

CURRENT_SCHEMA

O

For More Information

Refer to the followings.

CREATE TABLE AS SELECT

Function

It creates a new table from the query result.

Syntax

<table definition: AS query expression> ::=
    CREATE TABLE table_name 
        [ ( column_name [, ...] ) ]
        [ <table sharding strategy> ]
        [ <table attribute clause> [, ...] ]
        [ TABLESPACE tablespace_name ]
        [ <table global secondary index clause> ]
        AS <query expression> [ WITH [ NO ] DATA ]
    ;

<table sharding strategy> ::=
      <cloned strategy>
    | <hash sharding strategy>
    | <range sharding strategy>
    | <list sharding strategy>

<cloned strategy> ::=
    CLONED [ <clone placement> ]

<clone placement> ::=
      AT CLUSTER WIDE
    | AT CLUSTER GROUP group_list

<hash sharding strategy> ::=
    SHARDING BY [HASH] ( column_list )
    [ <hash shard count> ]
    [ <hash shard placement> ]

<hash shard count> ::=
    SHARD COUNT integer

<hash shard placement> ::=
      AT CLUSTER WIDE
    | AT CLUSTER GROUP group_list

<range sharding strategy> ::=
    SHARDING BY RANGE ( column_list )
    { <cluster-wide range shard placement> | <group-specific range shard placement> }

<cluster-wide range shard placement> ::=
    AT CLUSTER WIDE
    <range shard definition> [, ...]

<group-specific range shard placement> ::=
    <group-specific range shard definition> [, ...]

<group-specific range shard definition> ::=
    <range shard definition> AT CLUSTER GROUP group_name

<range shard definition> ::=
    SHARD range_name VALUES LESS THAN ( <range value clause> )

<range value clause> ::=
    <range value> [, ...]

<range value> ::=
      constant
    | MAXVALUE

<list sharding strategy> ::=
    SHARDING BY LIST ( column_name )
    { <cluster-wide list shard placement> | <group-specific list shard placement> }

<cluster-wide list shard placement> ::=
    AT CLUSTER WIDE
    <list shard definition> [, ...]

<group-specific list shard placement> ::=
    <group-specific list shard definition> [, ...]

<group-specific list shard definition> ::=
    <list shard definition> AT CLUSTER GROUP group_name

<list shard definition> ::=
      SHARD shard_name VALUES IN ( <list value clause> )

<list value clause> ::=
    <list value> [, ...]

<list value> ::=
      constant
    | NULL
    | DEFAULT


<table attribute clause> ::=
      [ <table physical attribute clause> ]
    | [ STORAGE ( <segment attr clause> [...] ) ]

<table physical attribute clause> ::=
      PCTFREE integer
    | PCTUSED integer
    | INITRANS integer
    | MAXTRANS integer

<index physical attribute clause> ::=
      PCTFREE integer
    | INITRANS integer
    | MAXTRANS integer

<segment attr clause> ::=
      INITIAL <size_clause>
    | NEXT <size_clause>
    | MINSIZE <size_clause>
    | MAXSIZE <size_clause>

<size clause> ::=
      integer [ K | M | G | T ]

<table global secondary index clause> ::=
      WITH GLOBAL SECONDARY INDEX [ <index attributes> [...] ] [ TABLESPACE tablespace_name ]
    |  WITHOUT GLOBAL SECONDARY INDEX

Invocation and Access Rules

A user should satisfy the following conditions to perform <table definition:AS query expression>statement.

Syntax Rules and Parameters

table_name

It is the table name to be created.
For more information, refer to table_name.

column_name_list

These are the names of the columns that configure the table, and it should be unique names within the table.
The number of columns should be as same as the number of result columns in SELECT clause.
If not specified, the column names of SELECT clause in <query expression> are used.
However, if an expression (such as a function, operation, or subquery) is used instead of a column in SELECT clause, the alias or column name should be specified.
The length of the column name should be shorter than 128 bytes.

WITH [NO] DATA

If WITH DATA is specified, the result of SELECT clause is inserted to the table to be created.
If WITH NO DATA is specified, the result of SELECT clause is not inserted to the table to be created. 
If not specified, it is operated as same as when WITH DATA is specified.

Other Syntax

For more information about other syntaxes, refer to the syntax in CREATE TABLE statement.

Description

When executing CREATE TABLE AS SELECT, if a column including a  NOT NULL constraint is specified in SELECT list, the NOT NULL constraint is also created in the new table.
However, if the NOT NULL constraint is deferrable, then NOT NULL constraint is not created in the new table.
On the other hand, the NOT NULL constraint is not created in the new table if NOT NULL constraint was not explicitly created but there is NOT NULL property such as primary key column or identity column.

Examples

The following is an example of executing CREATE TABLE AS SELECT statement.

gSQL> CREATE TABLE recent_orders 
                AS SELECT order_id, order_item, order_date
                   FROM orders 
                   WHERE order_date >= '2015-03-03'
Table created.

The following is an example of specifying the column name.

gSQL> CREATE TABLE recent_orders ( order_id, order_item, order_date )
                AS SELECT order_id, order_item, order_date
                   FROM orders 
                   WHERE order_date >= '2015-03-03'
Table created.

The following is an example of a function in SELECT list.

gSQL> CREATE TABLE recent_orders ( order_date, order_count )
                AS SELECT order_date, COUNT(*) 
                   FROM orders 
                   WHERE order_date >= '2015-03-03'
                   GROUP BY order_date;
Table created.

The following is an example of the statement including WITH DATA.

gSQL>CREATE TABLE orders 
( 
    order_id   NUMBER        
  , order_item VARCHAR(128)  
  , order_date DATE
);
gSQL> COMMIT;
gSQL> INSERT INTO orders VALUES ( 1, 'Pen', '2010-01-01' );
gSQL> INSERT INTO orders VALUES ( 2, 'Book', '2015-03-03' );
gSQL> COMMIT;
gSQL> CREATE TABLE recent_orders
                AS SELECT order_id, order_item, order_date 
                   FROM orders 
                   WHERE order_date >= '2015-03-03'
      WITH DATA;
Table created.
gSQL> SELECT COUNT(*) FROM recent_orders;

COUNT(*)
--------
       1

1 row selected.

The following is an example of the statement including WITH NO DATA.

gSQL>CREATE TABLE orders 
( 
    order_id   NUMBER        
  , order_item VARCHAR(128)  
  , order_date DATE
);
gSQL> COMMIT;
gSQL> INSERT INTO orders VALUES ( 1, 'Pen', '2010-01-01' );
gSQL> INSERT INTO orders VALUES ( 2, 'Book', '2015-03-03' );
gSQL> COMMIT;
gSQL> CREATE TABLE recent_orders
                AS SELECT order_id, order_item, order_date 
                   FROM orders 
                   WHERE order_date >= '2015-03-03'
      WITH NO DATA;
Table created.
gSQL> SELECT COUNT(*) FROM recent_orders;

COUNT(*)
--------
       0

1 row selected.

Compatibility

CREATE TABLE AS SELECT statement follows SQL standard. However, the following is an extension of SQL standard.

SQL standard compatibility

Feature ID

Description

Compatibility

T172

AS subquery clause in table definition

O

For More Information

Refer to the followings.

CREATE TABLESPACE

Function

It creates a tablespace.

Syntax

<create tablespace statement> ::=
      <memory data tablespace statement>
    | <memory temporary tablespace statement>
    ;

Invocation and Access Rules

CREATE TABLESPACE ON DATABASE privilege is required to perform <create tablespace statement>.

The user who performed the statement has CREATE OBJECT ON TABLESPACE privilege on the created tablespace.

One of the following privileges is required to create the objects on the created tablespace.

Syntax Rules and Parameters

<memory data tablespace statement>

It is a memory temporary tablespace to store the no logging indexes or the temporary objects such as intermediate results which are generated during the query processing.
The reserved word MEMORY can be omitted.

<memory data tablespace clause>

It defines a memory data tablespace.
For more information, refer to CREATE MEMORY DATA TABLESPACE.

<memory temporary tablespace definition>

It defines a memory temporary tablespace.
For more information, refer to CREATE MEMORY TEMPORARY TABLESPACE.

Description

For more information, refer to the description of each detailed statement.

Example

For more information, refer to usage example of each detailed statement.

Compatibility

The SQL standard does not cover the concepts of the tablespace.

For More Information

Refer to the followings.

CREATE USER

Function

It defines a database user.

Syntax

<user definition> ::=
    CREATE USER user_identifier IDENTIFIED BY password
    [ PROFILE { profile_name | DEFAULT | NULL } ]
    [ PASSWORD EXPIRE ]
    [ ACCOUNT { LOCK | UNLOCK } ]
    [ DEFAULT TABLESPACE tablespace_name ]
    [ TEMPORARY TABLESPACE tablespace_name ]
    [ INDEX TABLESPACE { tablespace_name | NULL } ]
    [ <schema clause> ]
    ;

<schema clause> ::=
      WITH SCHEMA [schema_name]
    | WITHOUT SCHEMA

Invocation and Access Rules

CREATE USER ON DATABASE privilege is required to perform <user definition>.

The created user, user_identifier, has the privilege, which is the owner the schema created by using <schema clause>.

A separate privilege is not granted to the created user_identifier.

The appropriate privileges should be granted to user_identifier to access and perform SQL statements.

Syntax Rules and Parameters

user_identifier

It is the username to be created.
The identical username (user identifier) or role (role name) should not exist.
The length of user_identifier should be shorter than 128 bytes.

password

It is the user's password to be created. It is encrypted and stored.
The length of password should be shorter than 128 bytes.
The password is case sensitive.
The password should start with an alphabetic character, and it can include alphabetic characters, numbers, underscore (_), and $. 
The other special characters should be enclosed in double quotes (").

PROFILE { profile_name | DEFAULT | NULL }

The profile for password management policy is assigned.

If PROFILE clause is omitted, it is as same as PROFILE NULL, and the profile is not applied.
For more information about the password management policy, refer to CREATE PROFILE.

PASSWORD EXPIRE

It expires the user's password.
It is used when a user attempts to change the password by force before login.

ACCOUNT { LOCK | UNLOCK }

DEFAULT TABLESPACE tablespace_name

It specifies the default TABLESPACE to store objects such as the table created by the user, the indexes (with NOLOGGING option).
If DEFAULT TABLESPACE clause is omitted, default data tablespace(MEM_DATA_TBS) is specified, which was defined when creating DATABASE.

TEMPORARY TABLESPACE tablespace_name

It specifies the TABLESPACE which stores the temporary tables created by a user, indexes (NO LOGGING), and the intermediate results generated by the query processing.
If TEMPORARY TABLESPACE clause is omitted, default temporary tablespace (MEM_TEMP_TBS) is specified, which was defined when creating DATABASE.

INDEX TABLESPACE { tablespace_name | NULL }

It specifies the default TABLESPACE which stores the index objects created by a user.

If INDEX TABLESPACE clause is omitted, then it is INDEX TABLESPACE NULL.

<schema clause>

It creates a schema which a user uses by default.
The schema name should be unique in the database.
If <schema clause> is not specified, the default value is WITH SCHEMA and the schema is created whose name is as same as user_identifier.
The schema to be owned by the user can be additionally created by using CREATE SCHEMA statement.

Description

A user is an authorization object which consists of a set of privileges.
When <user definition> statement is executed for the first time, a user without any privilege is created, and the appropriate privileges should be granted as follows.
In GOLDILOCKS, the relationship between user and schema is 1 : N.
In other words, a user does not own any schema, or a user can own multiple schemas.
The SQL standard does not explicitly define the relationship of the non-schema objects such as a user, a schema, or a database. Each DBMS defines the relationship of non-schema objects in different concept as follows.

The relationship between user and schema in other DBMS.





Examples

At least the following privileges should be granted to create a user, and for the created user to create the objects, manipulate data.

The following is an example of creating a user and granting privileges.

• Create a user.

gSQL> CREATE USER u1 IDENTIFIED BY u1_password
             DEFAULT   TABLESPACE mem_data_tbs
             TEMPORARY TABLESPACE mem_temp_tbs
             INDEX TABLESPACE NULL;

User created.

gSQL> COMMIT;

Commit complete.

• Grant database privileges.

gSQL> GRANT CREATE SESSION ON DATABASE TO u1;

Grant succeeded.

COMMIT;

Commit complete.

• Grant schema privileges.

GRANT CREATE TABLE, CREATE VIEW, CREATE INDEX, CREATE SEQUENCE, ADD CONSTRAINT 
      ON SCHEMA u1 TO u1;

Grant succeeded.

COMMIT;

Commit complete.

• Grant tablespace privileges.

GRANT CREATE OBJECT ON TABLESPACE mem_data_tbs TO u1;

Grant succeeded.

GRANT CREATE OBJECT ON TABLESPACE mem_temp_tbs TO u1;

Grant succeeded.

COMMIT;

Commit complete.

The following is an example of creating objects by the user.

• It needs CREATE SESSION ON DATABASE.
gSQL> \connect u1 u1_password
• It needs CREATE TABLE ON SCHEMA u1. 
• It needs CREATE OBJECT ON TABLESPACE mem_data_tbs.
gSQL> CREATE TABLE u1.t1 ( c1 INTEGER, c2 INTEGER ) TABLESPACE mem_data_tbs;

Table created.

gSQL> COMMIT;
• It needs CREATE INDEX ON SCHEMA u1. 
• It needs CREATE OBJECT ON TABLESPACE mem_temp_tbs.
gSQL> CREATE INDEX u1.idx ON t1 (c2) TABLESPACE mem_temp_tbs;

Index created.

gSQL> COMMIT;
• It needs ADD CONSTRAINT ON SCHEMA u1.
gSQL> ALTER TABLE t1 ADD CONSTRAINT u1.t1_pk PRIMARY KEY (c1) ;

Table altered.

gSQL> COMMIT;
• It needs CREATE SEQUENCE ON SCHEMA u1.
gSQL> CREATE SEQUENCE u1.seq;

Sequence created.

gSQL> COMMIT;

gSQL> INSERT INTO u1.t1 VALUES ( u1.seq.NEXTVAL, u1.seq.NEXTVAL );

1 row created

gSQL> COMMIT;

Compatibility

The SQL standard covers the concepts of the user, but it does not define the SQL statements associated with the creation and deletion of user.

For More Information

Refer to the followings.

CREATE VIEW

Function

It defines a view.

Syntax

<view definition> ::=
    CREATE [ OR REPLACE ] [ FORCE | NO FORCE ] 
        VIEW view_name [ ( column_name [, ...] ) ]
        AS <query expression>
    ;

Invocation and Access Rules

The user should satisfy the following conditions to perform <view definition> statement.

Syntax Rules and Parameters

[ OR REPLACE ]

It replaces the existing view when a view already exists.

[ FORCE | NO FORCE ]

view_name

It is the view name to be created, and it should be a unique name within the schema.
The schema to which the view belongs, such as schema_name.view_name, can be defined. If schema_name is omitted, the default schema name of the user performing the statement is used.
The length of the view name must be shorter than 128 bytes.

[ ( column_name [, ...] ) ]

It defines a column name which will configure the view.
Each column name should be unique within the view.
The number of columns should be as same as the number of result columns in SELECT clause.
If the list of column names is omitted, the column names of SELECT clause in <query expression> are used.

AS <query expression>

It is the SELECT query which will create a view.

<query expression> can not include the following variables.

Description

A view is the object which gave a name to the query, and it is used in the similar way of a table.

When executing a query including the view, that view is interpreted as the query included in the view definition. If the table referenced by the view is altered, as the following example, the asterisk (*) included in the view definition is automatically interpreted based on the altered table information.
gSQL> CREATE VIEW v1 AS SELECT * FROM t1;
gSQL> COMMIT;
gSQL> SELECT * FROM v1;

ID NAME     
-- ---------
 1 leekmo   
 2 mkkim    
 3 egonspace

3 rows selected.

gSQL> ALTER TABLE t1 ADD COLUMN ( dept_id  INTEGER,  addr  VARCHAR(1024) );
gSQL> COMMIT;

gSQL> select * from v1;

ID NAME      DEPT_ID ADDR
-- --------- ------- ----
 1 leekmo       null null
 2 mkkim        null null
 3 egonspace    null null

3 rows selected.

The view is affected if the view is created on the query including errors by using FORCE option, the tables referred by the view, or views are altered or deleted.

This information can be retrieved from INFORMATION_SCHEMA.VIEWS information.

The maximum number of creating views and the maximum number of columns to be created within a view is not limited. Therefore, they can be created as many as the storage space is available.

Examples

The following is an example of creating a view.

gSQL> CREATE VIEW v1 AS SELECT * FROM t1 WHERE dept_id = 101;

View created.

The following is an example of defining the column names when defining a view.

gSQL> CREATE VIEW v1 ( v_id, v_name )
          AS SELECT id, name FROM t1 WHERE dept_id = 101;

View created.

The following is an example of removing the existing view and creating a new view by using REPLACE option.

gSQL> CREATE OR REPLACE VIEW v1(id, name) 
             AS SELECT id, name FROM t1;

View created.

The following is an example of forcing to create a view by using FORCE option even when the referenced object by the view does not exist.

gSQL> CREATE FORCE VIEW v1 
          AS SELECT * FROM t1 WHERE dept_id = 101;

ERR-01000(16243): Warning: View created with compilation errors
ERR-42000(16040): table or view does not exist : 
    AS SELECT * FROM t1 WHERE dept_id = 101
                     *
ERROR at line 2:

View created.

Compatibility

The SQL standard does not define the following clauses.

SQL standard compatibility

Feature ID

Description

Compatibility

T131

Recursive query

X

F751

View CHECK enhancements

X

S043

Enhanced reference types

X

T111

Updatable joins, unions, and columns

X

F852

Top-level <order by clause> in views

O

F864

Top-level <result offset clause> in views

O

F859

Top-level <fetch first clause> in views

O

S081

Subtables

X

For More Information

Refer to the followings.

DECLARE cursor_name

Function

It declares a cursor.

Syntax

<declare cursor> ::=
    DECLARE cursor_name <cursor properties> { FOR | IS } <cursor specification>
    ;

<cursor properties> ::=
      [ <cursor sensitivity> ] [ <cursor scrollability>] ] CURSOR [ <cursor holdability> ] 
    | [ <odbc cursor type] CURSOR [ <cursor holdability> ] 

<cursor sensitivity> ::=
      INSENSITIVE
    | SENSITIVE
    | ASENSITIVE

<cursor scrollability> ::=
      NO SCROLL
    | SCROLL

<cursor holdability> ::=
      WITH HOLD
    | WITHOUT HOLD

<odbc cursor type> ::=
      STATIC
    | KEYSET

<cursor specification> ::=
      statement_name
    | <cursor query>  [ <updatability clause> ]

<cursor query> ::=
      <select statement>
    | <insert returning query statement>
    | <update returning query statement>
    | <delete returning query statement>

<updatability clause> ::=
      FOR READ ONLY 
    | FOR UPDATE [ OF <column name list> ] [ <lock wait mode> ]

<lock wait mode> ::=
    | WAIT
    | WAIT second
    | NOWAIT

Invocation and Access Rules

The dynamic cursor which uses statement_name can be used in an embedded SQL.

An appropriate access privilege is required depending on <cursor query> types.
For more information about the access privileges, refer to the followings.

Syntax Rules and Parameters

cursor_name

It is the cursor name to be declared.
It should be a unique name within the session.
The length of cursor name should be shorter than 128 bytes.

{ FOR | IS }

Either FOR or IS is used as a syntax keyword in SQL standard.

<cursor properties>

It defines the cursor properties.

updatable query

To use a cursor property such as SENSITIVE or FOR UPDATE, a query of the cursor should identify changes in rows of the base table, or it should be the updatable query which can acquire a lock on the row.

The updatable query should satisfy all of the following conditions.

<cursor sensitivity>

It determines whether the following data changes that affect the query results can be queried when operating the cursor.

<cursor scrollability>

It specifies whether the result set of the cursor can be fetched sequentially or non-sequentially.

<cursor holdability>

It determines whether the cursor is maintained after the cursor is OPEN and the transaction is committed.

<odbc cursor type>

It is the cursor type in the ODBC standard, and it has the SCROLL property.

Sensitivity according to FOR [UPDATE / READ ONLY] statement and the query type

Updatability

Query type

Sensitivity

FOR UPDATE

Updatable query

SENSITIVE

FOR UPDATE

Non-updatable query

Query error

FOR READ ONLY

Any query

INSENSITIVE

N/A

Updatable query

SENSITIVE

N/A

Non-updatable query

INSENSITIVE

<cursor specification>

It defines a query which is a target of the cursor.
If statement_name is used, a dynamic cursor whose query has not been defined is declared.
If <cursor query> is used, a standing cursor whose query is defined is declared.

statement_name

It is a statement_name to be referenced by the cursor, and it can be used in an embedded SQL.
statement_name should exist before performing <declare cursor> statement, and the SQL statement referenced by statement_name should be the query prepared by PREPARE statement_name statement.
If it is not a query, an error occurs when executing OPEN cursor_name statement.

<cursor query>

For more information about available query types in the cursor, refer to the followings.

<updatability clause>

It specifies whether to change rows by using the cursor.

FOR UPDATE OF …

It lists the columns associated with the lock obtaining when OPENing the cursor.

<lock wait mode>

It is used together with FOR UPDATE clause, and it specifies the lock acquisition method.

Description

When controlling the query property, using DECLARE CURSOR, OPEN, FETCH, CLOSE statements have the performance burden compared to using the cursor with the ODBC or JDBC statements. It is because using DECLARE CURSOR, OPEN, FETCH, CLOSE statements control the cursor of the server.

Before executing the query, the cursor property can be controlled by ODBC statement and JDBC statement. The SQL cursor property control method by DECLARE CURSOR statement, and cursor property control method by the ODBC standard and the JDBC standard are as follows.
Controlling the cursor property of ODBC/ JDBC

Property

GOLDILOCKS

cursor property

ODBC standard cursor property

JDBC standard cursor property

Sensitivity

INSENSITIVE

SQLSetStmtAttr(stmt, SQL_ATTR_CURSOR_SENSITIVITY, SQL_INSENSITIVE, len)

It can not be set.

SENSITIVE

SQLSetStmtAttr(stmt, SQL_ATTR_CURSOR_SENSITIVITY, SQL_SENSITIVE, len)

It can not be set.

ASENSITIVE

SQLSetStmtAttr(stmt, SQL_ATTR_CURSOR_SENSITIVITY, SQL_UNSPECIFIED, len)

It can not be set.

Scrollability

NO SCROLL

SQLSetStmtAttr(stmt, SQL_ATTR_CURSOR_SCROLLABLE, SQL_NONSCROLLABLE, len)

It can not be set.

SCROLL

SQLSetStmtAttr(stmt, SQL_ATTR_CURSOR_SCROLLABLE, SQL_SCROLLABLE, len)

It can not be set.

Holdability

WITHOUT HOLD

It can not be set.

java.sql.Connection::prepareStatement( query, type, conc, ResultSet.CLOSE_CURSORS_AT_COMMIT )

WITH HOLD

It can not be set.

java.sql.Connection::prepareStatement( query, type, conc, ResultSet.HOLD_CURSORS_OVER_COMMIT )

SQL cursor declaration corresponding to ODBC cursor type is as follows.

SQL cursor declaration corresponding to ODBC cursor type

ODBC cursor type

SQL cursor declaration

SQLSetStmtAttr(stmt, SQL_ATTR_CURSOR_TYPE, SQL_CURSOR_FORWARD_ONLY, len)

NO SCROLL CURSOR

SQLSetStmtAttr(stmt, SQL_ATTR_CURSOR_TYPE, SQL_CURSOR_STATIC, len)

STATIC CURSOR

SQLSetStmtAttr(stmt, SQL_ATTR_CURSOR_TYPE, SQL_CURSOR_KEYSET_DRIVEN, len)

KEYSET CURSOR

SQL cursor declaration corresponding to JDBC cursor type is as follows.

SQL cursor declaration corresponding to JDBC cursor type

JDBC cursor type

SQL cursor declaration

java.sql.Connection::prepareStatement( query, ResultSet.TYPE_FORWARD_ONLY, conc, hold )

INSENSITIVE NO SCROLL CURSOR

java.sql.Connection::prepareStatement( query, ResultSet.TYPE_SCROLL_INSENSITIVE, conc, hold )

INSENSITIVE SCROLL CURSOR

java.sql.Connection::prepareStatement( query, ResultSet.TYPE_SCROLL_SENSITIVE, conc, hold )

KEYSET CURSOR

Examples

The following is an example of declaring the cursor by using interactive SQL (gsql), and using it.

gSQL> DECLARE cur1 CURSOR FOR SELECT id, data FROM t1;

Cursor declared.

gSQL> OPEN cur1;

Cursor is open.

gSQL> \var v_id   INTEGER
gSQL> \var v_data VARCHAR(128)

gSQL> FETCH cur1 INTO :v_id, :v_data;

V_ID V_DATA
---- ------
   1 data_1

1 row fetched.

gSQL> FETCH cur1 INTO :v_id, :v_data;

V_ID V_DATA
---- ------
   2 data_2

1 row fetched.

gSQL> FETCH cur1 INTO :v_id, :v_data;

V_ID V_DATA
---- ------
   3 data_3

1 row fetched.

gSQL> FETCH cur1 INTO :v_id, :v_data;

V_ID V_DATA
---- ------
   4 data_4

1 row fetched.

gSQL> FETCH cur1 INTO :v_id, :v_data;

V_ID V_DATA
---- ------
   5 data_5

1 row fetched.

gSQL> FETCH cur1 INTO :v_id, :v_data;

no rows fetched.

gSQL> CLOSE cur1;

Cursor closed.

The following is an example of declaring KEYSET cursor, sequentially searching, then completing the transaction of UPDATE, DELETE statements, and searching for it in the reverse direction.

gSQL> DECLARE cur_keyset KEYSET CURSOR FOR SELECT id, data FROM t1;

Cursor declared.

gSQL> OPEN cur_keyset;

Cursor is open.

gSQL> \var v_id   INTEGER
gSQL> \var v_data VARCHAR(128)

gSQL> FETCH NEXT cur_keyset INTO :v_id, :v_data;

V_ID V_DATA
---- ------
   1 data_1

1 row fetched.


gSQL> FETCH NEXT cur_keyset INTO :v_id, :v_data;

V_ID V_DATA
---- ------
   2 data_2

1 row fetched.

gSQL> FETCH NEXT cur_keyset INTO :v_id, :v_data;

V_ID V_DATA
---- ------
   3 data_3

1 row fetched.

gSQL> FETCH NEXT cur_keyset INTO :v_id, :v_data;

V_ID V_DATA
---- ------
   4 data_4

1 row fetched.

gSQL> FETCH NEXT cur_keyset INTO :v_id, :v_data;

V_ID V_DATA
---- ------
   5 data_5

1 row fetched.

gSQL> FETCH NEXT cur_keyset INTO :v_id, :v_data;

no rows fetched.

gSQL> UPDATE t1 SET data = 'new data_2' WHERE id = 2;

1 row updated.

gSQL> COMMIT;

Commit complete.

gSQL> DELETE FROM t1 WHERE id = 4;

1 row deleted.

gSQL> COMMIT;

Commit complete.

gSQL> FETCH PRIOR cur_keyset INTO :v_id, :v_data;

V_ID V_DATA
---- ------
   5 data_5

1 row fetched.


gSQL> FETCH PRIOR cur_keyset INTO :v_id, :v_data;

no rows fetched.


gSQL> FETCH PRIOR cur_keyset INTO :v_id, :v_data;

V_ID V_DATA
---- ------
   3 data_3

1 row fetched.

gSQL> FETCH PRIOR cur_keyset INTO :v_id, :v_data;

V_ID V_DATA    
---- ----------
   2 new data_2

1 row fetched.

gSQL> FETCH PRIOR cur_keyset INTO :v_id, :v_data;

V_ID V_DATA
---- ------
   1 data_1

1 row fetched.

gSQL> CLOSE cur_keyset;

Cursor closed.

The following is an example of declaring SCROLL cursor, and using the cursor through the fetch orientation.

gSQL> DECLARE cur_scroll SCROLL CURSOR FOR SELECT id, data FROM t1;

Cursor declared.

gSQL> OPEN cur_scroll;

Cursor is open.

gSQL> \var v_id   INTEGER
gSQL> \var v_data VARCHAR(128)

gSQL> FETCH LAST cur_scroll INTO :v_id, :v_data;
V_ID V_DATA
---- ------
   5 data_5

1 row fetched.


gSQL> FETCH PRIOR cur_scroll INTO :v_id, :v_data;

V_ID V_DATA
---- ------
   4 data_4

1 row fetched.


gSQL> FETCH FIRST cur_scroll INTO :v_id, :v_data;

V_ID V_DATA
---- ------
   1 data_1

1 row fetched.


gSQL> FETCH ABSOLUTE 3 cur_scroll INTO :v_id, :v_data;

V_ID V_DATA
---- ------
   3 data_3

1 row fetched.


gSQL> FETCH RELATIVE -1 cur_scroll INTO :v_id, :v_data;

V_ID V_DATA
---- ------
   2 data_2

1 row fetched.


gSQL> FETCH ABSOLUTE 3 cur_scroll INTO :v_id, :v_data;

V_ID V_DATA
---- ------
   3 data_3

1 row fetched.

gSQL> CLOSE cur_scroll;

Cursor closed.

Compatibility

<declare cursor> statement has the following differences compared to the SQL standard.

SQL standard compatibility

Feature ID

Description

Compatibility

F831

Full cursor update

O

T231

Sensitive cursors

O

F791

Insensitive cursors

O

F431

Read-only scrollable cursors

O

T471

Result sets return value

X

T551

Optional key words for default syntax

O

T111

Updatable joins, unions, and columns

X

B031

Basic dynamic SQL

O

For More Information

Refer to the followings.

DELETE FROM

Function

It deletes rows in a table.

Syntax

<delete statement: searched> ::=
    DELETE [ FROM ] table_name [ [ AS ] alias_name ]
        [ WHERE <search condition> ]
        [ <result offset clause> ]
        [ <fetch limit clause> ]
    ;

<result offset clause> ::=
    OFFSET skip_count [ ROW | ROWS ]

<fetch limit clause> ::=
      <fetch first clause>
    | <limit clause>

<fetch first clause> ::=
    FETCH [ FIRST | NEXT ] [ row_count ] [ ROW ONLY | ROWS ONLY ]

<limit clause>
    LIMIT { fetch_row_count | offset_row_count, fetch_row_count | ALL }

Invocation and Access Rules

One of the following privileges is required to perform <delete statement: searched>.

Syntax Rules and Parameters

table_name

It is the name of a target table whose rows are to be deleted.
It defines the schema to which the table belongs such as schema_name.table_name. 
If schema_name is omitted, the default schema name of the user performing the statement is used.

[ AS alias_name ]

It is the alias of table_name.

WHERE <search condition>

It deletes the rows which satisfy WHERE condition.
If WHERE condition is omitted, it deletes all rows.
For more information about WHERE condition refer to where clause of SELECT statement.

<result offset clause>

It specifies the number of rows to be skipped among the query result.
For more information, refer to offset limit clause of SELECT statement.

<fetch limit clause>

The following two ways are used to specify the number of rows to be fetched.

Description

Differences among DELETE-related Statements

Examples

The following is an example of DELETE statement.

gSQL> DELETE FROM t1 WHERE id > 3;

2 rows deleted.

The following is an example of skipping some rows (two rows) and deleting some rows (two rows) among the rows which satisfy the conditions by using <result offset clause> and <fetch first clause> clauses.

gSQL> DELETE FROM t1 OFFSET 2 FETCH 2;

2 rows deleted.


gSQL> SELECT * FROM t1 ORDER BY 1;

ID DATA  
-- ------
 1 data_1
 2 data_2
 5 data_5

3 rows selected.

Compatibility

The SQL standard does not define the following clauses of DELETE statement.

SQL standard compatibility

Feature ID

Description

Compatibility

F781

Self-referencing operations

X

T111

Updatable joins, unions, and columns

X

For More Information

Refer to the followings.

DELETE FROM name RETURNING

Function

It deletes rows of the table, and retrieves the deleted rows.

Syntax

<delete returning query statement> ::=
    DELETE [ FROM ] table_name [ [ AS ] alias_name ]
        [ WHERE <search condition> ]
        [ <result offset clause> ]
        [ <fetch limit clause> ]
        <returning clause>
    ;

<result offset clause> ::=
    OFFSET skip_count [ ROW | ROWS ]

<fetch limit clause> ::=
      <fetch first clause>
    | <limit clause>

<fetch first clause> ::=
    FETCH [ FIRST | NEXT ] [ row_count ] [ ROW ONLY | ROWS ONLY ]

<limit clause>
    LIMIT { fetch_row_count | offset_row_count, fetch_row_count | ALL }

<returning clause> ::=
    { RETURN | RETURNING } { * | { <value expression> [ [AS] alias_name] } [, ...] }

Invocation and Access Rules

The user should satisfy the following conditions to perform <delete returning query statement>.

Syntax Rules and Parameters

table_name

It is the name of a target table whose rows are to be deleted.

[ AS alias_name ]

It is the alias of table_name.

WHERE <search condition>

It deletes the rows which satisfy WHERE condition.
For more information, refer to DELETE FROM statement.

<result offset clause>

It specifies the number of rows to be skipped among the query result.
For more information, refer to DELETE FROM statement.

<fetch first clause>

It specifies the number of rows to be fetched.
For more information, refer to DELETE FROM statement.

<limit clause>

It specifies the number of rows to be fetched, or it simultaneously specifies both the number of rows to be skipped and the number of rows to be fetched.
For more information, refer to DELETE FROM statement.

<returning clause>

It sets the deleted rows as a result set, and it specifies the columns to be searched from the set.

The keywords RETURNING and RETURN have the same meaning.

Description

For more information, refer to Differences among DELETE-related Statements.

Examples

The following is an example of deleting rows which satisfy the condition, and searching for the deleted rows.

gSQL> DELETE FROM t1 WHERE id > 3 RETURNING *;

ID DATA  
-- ------
 4 data_4
 5 data_5

2 rows deleted.

The following is an example of querying information of the deleted rows by using operation in RETURNING clause.

gSQL> DELETE FROM t1 
             WHERE id > 3 
             RETURNING 'ID: ' || id || ', DATA: ' || data AS id_data;

ID_DATA            
-------------------
ID: 4, DATA: data_4
ID: 5, DATA: data_5

2 rows deleted.

Compatibility

The SQL standard does not cover <delete returning query statement>.

For More Information

Refer to the followings.

DELETE FROM name RETURNING .. INTO

Function

It deletes a single row from the table, and the value of the deleted row is obtained into the host variable.

Syntax

<delete returning query statement> ::=
    DELETE [ FROM ] table_name [ [ AS ] alias_name ]
        [ WHERE <search condition> ]
        [ <result offset clause> ]
        [ <fetch limit clause> ]
        <returning into clause>
    ;

<result offset clause> ::=
    OFFSET skip_count [ ROW | ROWS ]


<fetch limit clause> ::=
      <fetch first clause>
    | <limit clause>


<fetch first clause> ::=
    FETCH [ FIRST | NEXT ] [ row_count ] [ ROW ONLY | ROWS ONLY ]


<limit clause>
    LIMIT { fetch_row_count | offset_row_count, fetch_row_count | ALL }


<returning into clause> ::=
    { RETURN | RETURNING } { * | { <value expression> [ [AS] alias_name] } [, ...] } INTO variable_name [, ...]

Invocation and Access Rules

The user should satisfy the following conditions to perform <delete returning into statement>.

Syntax Rules and Parameters

table_name

It is the name of a target table whose rows are to be deleted.

[ AS alias_name ]

It is the alias of table_name.

WHERE <search condition>

It deletes the rows which satisfy WHERE condition.
For more information, refer to DELETE FROM statement.

<result offset clause>

It specifies the number of rows to be skipped among the query result.
For more information, refer to DELETE FROM statement.

<fetch first clause>

It specifies the number of rows to be fetched.
For more information, refer to DELETE FROM statement.

<limit clause>

It specifies the number of rows to be fetched, or it simultaneously specifies both the number of rows to be skipped and the number of rows to be fetched.
For more information, refer to DELETE FROM statement.

<returning into clause>

Description

The number of rows to be deleted should be equal to or less than one.
If two or more rows are deleted, then an error occurs.
For more information, refer to Differences among DELETE-related Statements.

Example

The following is an example of deleting rows and obtaining the value of deleted rows into the host variable in an interactive SQL (gsql).

gSQL> \var v_id    INTEGER
gSQL> \var v_data  VARCHAR(128)

gSQL> DELETE FROM t1 WHERE id = 3 RETURNING id, data INTO :v_id, :v_data;

V_ID V_DATA
---- ------
   3 data_3

1 row deleted.

Compatibility

The SQL standard does not cover <delete returning into statement>.

For More Information

Refer to the followings.

DELETE FROM name WHERE CURRENT OF cursor_name

Function

It deletes a single row which the cursor indicates.

Syntax

<delete statement: positioned> ::=
    DELETE [ FROM ] table_name [ [ AS ] alias_name ]
        WHERE CURRENT OF cursor_name
    ;

Invocation and Access Rules

The privilege to perform DELETE FROM statement is required to perform <delete statement: positioned>.

Syntax Rules and Parameters

table_name

It is the name of a target table whose rows are to be deleted.

[ AS alias_name ]

It is the alias of table_name.

cursor_name

The cursor corresponding to cursor_name should satisfy the following conditions.

Description

For more information, refer to Differences among DELETE-related Statements.

Example

The following is an example of declaring the FOR UPDATE cursor, and deleting rows by using the cursor in interactive SQL (gsql).

gSQL> DECLARE cur1 CURSOR FOR SELECT id, data FROM t1 FOR UPDATE;

Cursor declared.


gSQL> OPEN cur1;

Cursor is open.


gSQL> \var v_id   INTEGER
gSQL> \var v_data VARCHAR(128)

gSQL> FETCH cur1 INTO :v_id, :v_data;

V_ID V_DATA
---- ------
   1 data_1

1 row fetched.

gSQL> FETCH cur1 INTO :v_id, :v_data;

V_ID V_DATA
---- ------
   2 data_2

1 row fetched.

gSQL> DELETE FROM t1 WHERE CURRENT OF cur1;

1 row deleted.

gSQL> FETCH cur1 INTO :v_id, :v_data;

V_ID V_DATA
---- ------
   3 data_3

1 row fetched.

gSQL> FETCH cur1 INTO :v_id, :v_data;

V_ID V_DATA
---- ------
   4 data_4

1 row fetched.

gSQL> DELETE FROM t1 WHERE CURRENT OF cur1;

1 row deleted.

gSQL> FETCH cur1 INTO :v_id, :v_data;

V_ID V_DATA
---- ------
   5 data_5

1 row fetched.

gSQL> FETCH cur1 INTO :v_id, :v_data;

no rows fetched.

gSQL> CLOSE cur1;

Cursor closed.

gSQL> SELECT id, data FROM t1 ORDER BY 1;

ID DATA  
-- ------
 1 data_1
 3 data_3
 5 data_5

3 rows selected.

Compatibility

SQL standard compatibility

Feature ID

Description

Compatibility

S111

ONLY in query expressions

X

B031

Basic dynamic SQL

O

For More Information

Refer to the followings.

DROP AUDIT POLICY

Function

It drops an audit policy.

Syntax

<drop audit policy statement> ::= 
    DROP AUDIT POLICY [ IF EXISTS ] policy_name
;

Invocation and Access Rules

AUDIT SYSTEM ON DATABASE privilege is required to perform <drop audit policy statement>.

Syntax Rules and Parameters

IF EXISTS

An error does not occur even when a policy_name does not exist.

policy_name

It is the name of an audit policy object to be dropped.

Description

The audit policy object which is already activated can not be dropped. In this case, the audit policy should be deactivated by using NOAUDIT POLICY statement.

Examples

The following is an example of dropping an audit policy.

DROP AUDIT POLICY policy_table;

Compatibility

In the SQL standard, an audit policy does not exist.

For More Information

Refer to the followings.

DROP CLUSTER GROUP

Function

It drops a cluster group from a cluster system.

Syntax

<drop cluster group statement> ::=
    DROP CLUSTER GROUP [IF EXISTS] group_name
    ;

Invocation and Access Rules

It can be performed in a cluster system.
ADMINISTRATION ON DATABASE privilege is required to perform <drop cluster group statement>.

Syntax Rules and Parameters

[IF EXISTS]

An error does not occur even when a cluster group does not exist.

group_name

It is the name of a cluster group.
A cluster group without any shard can be dropped.

Description

A cluster group can be dropped only when dropping the cluster group does not cause the data loss.
However, an error may occur when trying to drop a group including the global coordinator.

Examples

The following is an example of dropping a cluster group.

gSQL> DROP CLUSTER GROUP g3;

Cluster Group dropped.

Compatibility

The SQL standard does not define the concepts of the cluster.

For More Information

Refer to CREATE CLUSTER GROUP.

DROP CLUSTER LOCATION

Function

It drops the access information of a cluster member.

Syntax

<drop cluster location statement> ::=
    DROP CLUSTER LOCATION member_name 
    ;

Invocation and Access Rules

It can be performed in a cluster system.
ADMINISTRATION ON DATABASE privilege is required to perform <drop cluster location statement>.

Syntax Rules and Parameters

member_name

It is the name of a cluster member.
The same cluster member name should exist in a registered cluster location information.
The length of the name should be shorter than 128 bytes.

Description

Generally, the information of the cluster location is automatically created by using the connection information provided when creating the cluster group or adding the cluster member. The created information is deleted together when deleting the cluster member and the cluster group.

If the access information of the cluster location is modified, then the connection information can be modified by using ALTER CLUSTER LOCATION without deleting or recreating the cluster member.

Example

gSQL> 
DROP CLUSTER LOCATION g1n2
;

Created

Compatibility

The SQL standard does not define the concepts of the cluster.

For More Information

Refer to the followings.

DROP INDEX

Function

It drops an index.

Syntax

<drop index statement> ::=
    DROP INDEX [ IF EXISTS ] index_name
    ;

Invocation and Access Rules

One of the following privileges is required to perform <drop index statement>.

Syntax Rules and Parameters

IF EXISTS

Even when the index does not exist, an error does not occur.

index_name

It is the index name to be dropped.
It can define schema to which the index belongs such as schema_name.index_name and if schema_name is omitted, the default schema name of the user performing the statement is used.
The indexes created for UNIQUE constraint, PRIMARY KEY constraint can not be dropped.
To drop the indexes created for the constraints above, the constraints should be removed through ALTER TABLE name DROP CONSTRAINT statement.

Description

Data Definition Language (DDL) statement such as DROP INDEX can be rolled back if it is before when the transaction is committed.

Examples

The following is an example of dropping an index.

gSQL> DROP INDEX idx_t1_id;

Index dropped.

The following is an example of preventing an error even when the index does not exist by using IF EXISTS statement.

gSQL> DROP INDEX IF EXISTS not_exist_index;

Index dropped.

Compatibility

The SQL standard does not cover the concepts of the index.

For More Information

Refer to the followings.

DROP PROFILE

Function

It drops a profile.

Syntax

<drop profile statement> ::= 
    DROP PROFILE [ IF EXISTS ] profile_name [ CASCADE ] ;

Invocation and Access Rules

DROP PROFILE ON DATABASE privilege is required to perform <drop profile statement>.

Syntax Rules and Parameters

IF EXISTS

Even when the profile does not exist, an error does not occur.

profile_name

It specifies the profile name to be dropped.
It can not drop the DEFAULT profile.

CASCADE

If the profile has already been assigned to users, CASCADE clause should be explicitly specified to drop the profile.
The profile which is assigned to users and to be dropped is changed to DEFAULT profile.

Example

The following is an example of dropping a profile by using CASCADE statement.

gSQL> DROP PROFILE prof CASCADE;

Profile dropped.

gSQL> COMMIT;

Commit complete.

Compatibility

The SQL standard does not cover the concepts of the profile.

For More Information

Refer to the followings.

DROP SCHEMA

Function

It drops a schema.

Syntax

<drop schema statement> ::=
    DROP SCHEMA [ IF EXISTS ] schema_name
        [ <drop behavior> ]
    ;

<drop behavior> ::=
      RESTRICT
    | CASCADE

Invocation and Access Rules

One of the following privileges is required to perform <drop schema statement>.

Syntax Rules and Parameters

IF EXISTS

Even when the schema does not exist, an error does not occur.

schema_name

It is the schema name to be dropped.
However, it can not drop the built-in schema such as "DICTIONARY_SCHEMA", "INFORMATION_SCHEMA" and "PUBLIC" which are automatically created when creating the database.

<drop behavior>

Description

Data Definition Language (DDL) statement such as DROP SCHEMA can be rolled back if it is before when the transaction is committed. In this case, recycle bin objects which are included in the schema to be dropped are also dropped.

Examples

The following is an example of dropping a schema and all objects which exist within the schema.

gSQL> DROP SCHEMA s1 CASCADE;

Schema dropped.

The following is an example of preventing an error even when the schema does not exist by using IF EXISTS statement.

gSQL> DROP SCHEMA IF EXISTS not_exist_schema;

Schema dropped.

Compatibility

The SQL standard does not define IF EXISTS clause.

SQL standard compatibility

Feature ID

Description

Compatibility

F032

CASCADE drop behavior

O

F381

Extended schema manipulation

O

For More Information

Refer to CREATE SCHEMA.

DROP SEQUENCE

Function

It drops a sequence.

Syntax

<drop sequence generator statement> ::=
    DROP SEQUENCE [ IF EXISTS ] [schema_name.] sequence_name 
    ;

Invocation and Access Rules

One of the following privileges is required to perform <drop sequence generator statement>.

Syntax Rules and Parameters

IF EXISTS

Even when the sequence does not exist, an error does not occur.

sequence_name

It is the sequence name to be dropped.
It can define schema to which the sequence belongs such as schema_name.sequence_name and if schema_name is omitted, the default schema name of the user performing the statement is used.

Description

Data Definition Language (DDL) statement such as DROP SEQUENCE can be rolled back if it is before when the transaction is committed.

Examples

The following is an example of dropping a sequence.

gSQL> DROP SEQUENCE seq1;

Sequence dropped.

The following is an example of preventing an error even when the sequence does not exist by using IF EXISTS statement.

gSQL> DROP SEQUENCE invalid_sequence;

ERR-42000(16044): sequence does not exist : 
DROP SEQUENCE invalid_sequence
              *
ERROR at line 1:


gSQL> DROP SEQUENCE IF EXISTS invalid_sequence;

Sequence dropped.

Compatibility

The SQL standard does not define IF EXISTS clause.

SQL standard compatibility

Feature ID

Description

Compatibility

T176

Sequence generator support

O

For More Information

Refer to the followings.

DROP SYNONYM

Function

It drops a synonym.

Syntax

<drop synonym statement> ::=
    DROP [ PUBLIC ] SYNONYM [ IF EXISTS ] [schema_name.]synonym_name
    ;

Invocation and Access Rules

DROP PUBLIC SYNONYM ON DATABASE privilege is required to drop a public synonym by specifying PUBLIC.

One of the following privileges is required to drop a private synonym.

Syntax Rules and Parameters

[ PUBLIC ]

It is specified when dropping the public synonym.
If this clause is omitted, the private synonym is dropped.

IF EXISTS

Even when the synonym does not exist, an error does not occur.

synonym_name

It is the synonym name to be dropped.
It can define schema to which the synonym belongs such as schema_name.synonym_name and if schema_name is omitted, the default schema name of the user performing the statement is used.
If PUBLIC is explicitly specified, the schema name can not be specified.

Description

Data Definition Language (DDL) statement such as DROP SYNONYM can be rolled back if it is before when the transaction is committed.

Examples

The following is an example of dropping a private synonym.

gSQL> DROP SYNONYM MyEmp;

Synonym dropped.

The following is an example of dropping a public synonym.

gSQL> DROP PUBLIC SYNONYM MainEmp;

Synonym dropped.

Compatibility

The SQL standard does not define DROP SYNONYM statement.

For More Information

Refer to CREATE SYNONYM.

DROP TABLE

Function

It drops a table.

If the recycle bin feature is activated, the table is not completely dropped but it is stored in the recycle bin.

Syntax

<drop table statement> ::=
    DROP TABLE [ IF EXISTS ] table_name
    [ <drop behavior> ]
    [ PURGE ]
    ;

<drop behavior> ::=
      RESTRICT
    | CASCADE
    | CASCADE CONSTRAINTS

Invocation and Access Rules

One of the following privileges is required to perform <drop table statement>.

Syntax Rules and Parameters

IF EXISTS

Even when the table does not exist, an error does not occur.

table_name

It is the table name to be dropped.
It can define schema to which the table belongs such as schema_name.table_name and if schema_name is omitted, the default schema name of the user performing the statement is used.

The following tables which are automatically created during creating the database, can not be dropped.

It also drops constraints and indexes created in the table.

drop behavior

Currently, both RESTRICT and CASCADE are operated same.
When it is omitted, the default value is RESTRICT.

purge

It immediately drops a table instead of storing it in the recyclebin even when the recyclebin feature is activated.

Description

Data Definition Language (DDL) statement such as DROP TABLE can be rolled back if it is before when the transaction is committed.

Examples

The following is an example of dropping an ordinary table.

gSQL> DROP TABLE region;

Table dropped.

The following is an example of preventing an error even when the table does not exist by using IF EXISTS statement.

gSQL> DROP TABLE IF EXISTS invalid_table;

Table dropped.

The following is an example of rolling back the dropped table.

gSQL> SELECT r_regionkey, r_name FROM region;

R_REGIONKEY R_NAME                   
----------- -------------------------
          0 AFRICA                   
          1 AMERICA                  
          2 ASIA                     
          3 EUROPE                   
          4 MIDDLE EAST              

5 rows selected.


gSQL> DROP TABLE region;

Table dropped.


gSQL> SELECT r_regionkey, r_name FROM region;

ERR-42000(16040): table or view does not exist : 
SELECT r_regionkey, r_name FROM region
                                *
ERROR at line 1:


gSQL> ROLLBACK;

Rollback complete.


gSQL> SELECT r_regionkey, r_name FROM region;

R_REGIONKEY R_NAME                   
----------- -------------------------
          0 AFRICA                   
          1 AMERICA                  
          2 ASIA                     
          3 EUROPE                   
          4 MIDDLE EAST              

5 rows selected.

Compatibility

The SQL standard does not define the following clauses.

SQL standard compatibility

Feature ID

Description

Compatibility

F032

CASCADE drop behavior

O

For More Information

Refer to CREATE TABLE.

DROP TABLESPACE

Function

It drops a tablespace.

Syntax

<drop tablespace statement> ::=
    DROP TABLESPACE [ IF EXISTS ] tablespace_name
        [ INCLUDING CONTENTS ]
        [ { AND | KEEP } DATAFILES ]
        [ <drop behavior> ]
    ;

<drop behavior> ::=
      RESTRICT
    | CASCADE
    | CASCADE CONSTRAINTS

Invocation and Access Rules

DROP TABLESPACE ON DATABASE privilege is required to perform <drop tablespace definition>.

Syntax Rules and Parameters

IF EXISTS

Even when the tablespace does not exist, an error does not occur.

tablespace_name

It is the tablespace name to be dropped.

The following system tablespaces which are automatically created during creating the database, can not be dropped.

If tablespace_name was used as a default tablespace of a user, the space for the objects can not be allocated after dropping the tablespace.

After dropping the tablespace, the default tablespace should be changed by using ALTER USER statement.

INCLUDING CONTENTS

It drops objects (table, index, key constraint) which belong to the tablespace. If the index or key constraint which refers to the table which belongs to the tablespace exists outside of the tablespace, then it is also dropped.
If INCLUDING CONTENTS clause is not used, then any object which belongs to the tablespace should not exist.

[ { AND | KEEP } DATAFILES ]

It specifies whether to drop the datafiles which configure the tablespace together.
The datafiles are not in the memory temporary tablespace, so the clause is ignored.

drop behavior

Currently, both RESTRICT and CASCADE are operated same.
When it is omitted, the default value is RESTRICT.

Description

Unlike other Data Definition Language (DDL), DROP TABLESPACE statement can not be rolled back and the executed transaction is automatically committed. In this case, recycle bin objects which are included in the tablespace to be dropped are also dropped.

Examples

The following is an example of dropping a tablespace together with all objects in the tablespace and datafiles which configure the tablespace.

gSQL> DROP TABLESPACE space1 INCLUDING CONTENTS AND DATAFILES CASCADE CONSTRAINTS;

Tablespace dropped.

The following is an example of preventing an error even when the tablespace does not exist by using IF EXISTS statement.

gSQL> DROP TABLESPACE IF EXISTS not_exist_tablespace;

Tablespace dropped.

Compatibility

The SQL standard does not cover the concepts of the tablespace.

For More Information

Refer to the followings.

DROP USER

Function

It drops a database user.

Syntax

<drop user statement> ::=
    DROP USER [ IF EXISTS ] user_identifier [ <drop behavior> ]
    ;

<drop behavior> ::=
      RESTRICT
    | CASCADE

Invocation and Access Rules

DROP USER ON DATABASE privilege is required to perform <drop user statement>.

The schema owned by user_identifier should not exist.

For more information about dropping the schema, refer to DROP SCHEMA.

Syntax Rules and Parameters

IF EXISTS

Even when the user does not exist, an error does not occur.

user_identifier

It is the database username to be dropped.
However, the user which is automatically created during creating the database such as "SYS", can not be dropped.

It does not drop the object which is created by user_identifier but is not an owner as follows.

<drop behavior>

The relationship between user and schema in other DBMS





Description

In GOLDILOCKS, relationship between the user and the schema is 1 : N. A user does not own a schema, or the user can have multiple schemas.
To drop a user, all schema owned by the user should be dropped. In this case, recycle bin objects of the user to be dropped are also dropped.

Examples

The following is an example of dropping all schema owned by the user and then dropping the user.

gSQL> DROP SCHEMA u1 CASCADE;

Schema dropped.

gSQL> DROP USER u1 CASCADE;

User dropped.

The following is an example of preventing an error even when the user does not exist by using IF EXISTS statement.

gSQL> DROP USER IF EXISTS not_exist_user;

User dropped.

Compatibility

SQL standard cover the concepts of the user, but they do not define the SQL statements related to creating or dropping a user.

For More Information

Refer to the followings.

DROP VIEW

Function

It drops a view.

Syntax

<drop view statement> ::=
    DROP VIEW [ IF EXISTS ] view_name
    ;

Invocation and Access Rules

One of the following privileges is required to perform <drop view statement>.

Syntax Rules and Parameters

IF EXISTS

Even when the view does not exist, an error does not occur.

view_name

It is the view name to be dropped.
The schema to which the table belongs, such as schema_name.view_name, can be defined. If schema_name is omitted, the default schema name of the user performing the statement is used.

Description

Data Definition Language (DDL) statement such as DROP VIEW can be rolled back if it is before when the transaction is committed.

Examples

The following is an example of dropping a view.

gSQL> DROP VIEW v1;

View dropped.

The following is an example of preventing an error even when the view does not exist by using IF EXISTS statement.

gSQL> DROP VIEW IF EXISTS not_exist_view;

View dropped.

Compatibility

The SQL standard does not define IF EXISTS clause.

SQL standard compatibility

Feature ID

Description

Compatibility

F032

CASCADE drop behavior

X

For More Information

Refer to the followings.

EXECUTE IMMEDIATE 'sql_string'

Function

It executes a dynamic SQL statement which was not defined when writing a program.

Syntax

<execute immediate statement> ::=
    EXECUTE IMMEDIATE <SQL statement variable>
    ;

<SQL statement variable> ::=
      variable_name
    | 'sql statement'
    | "sql statement"
    | sql statement

Invocation and Access Rules

It can be used in an embedded SQL.
An appropriate privilege according to the type of a dynamic SQL statement is required.

Syntax Rules and Parameters

<SQL statement variable>

The dynamic SQL statement referenced by <SQL statement variable> can not use a host variable (:var) or parameter marker (?).
The following four types of <SQL statement variable> can be used.

The single quote (') is used twice as follows to represent string data within a single-quoted string.

{
    ...
    EXEC SQL EXECUTE IMMEDIATE 'INSERT INTO t1 VALUES ( ''literal data'' )'; 
    ...
}

If the SQL statement is a query including a query result, it is successfully executed, but the result can not be obtained.

variable_name

The type corresponding to the variable_name should be a character string.
The dynamic SQL statement defined in the variable_name should be valid.

sql statement

The dynamic SQL statement defined in the sql statement should be valid.

Description

EXECUTE IMMEDIATE 'sql_string' statement can be used as the non-query SQL without a host variable in dynamic embedded SQL application. It is appropriate to execute DDL, DML as one-off because it does not require separate preparation procedure.
For more information, refer to  Embedded Dynamic SQL.

Example

The following is an example of using EXECUTE IMMEDIATE 'sql_string' in the embedded SQL source code.

{
    ...
    sprintf(sSqlStmt, "INSERT INTO EMP_RND\n"
            "SELECT *\n"
            "FROM   EMP\n"
            "WHERE  JOB = 'RND'\n" );
    EXEC SQL EXECUTE IMMEDIATE :sSqlStmt;
    if(sqlca.sqlcode != 0)
    {
        goto fail_exit;
    }
    ...
}

The full source code in which EXECUTE IMMEDIATE 'sql_string' was used can be viewed in Dynamic Embedded SQL Example Program.

Compatibility

SQL standard compatibility

Feature ID

Description

Compatibility

B031

Basic Dynamic SQL

O

For More Information

Refer to the followings.

EXECUTE statement_name

Function

It executes the prepared statement.

Syntax

<execute statement> ::=
    EXECUTE statement_name [ <parameter using clause> ] [ <result into clause> ]
    ;

<parameter using clause> ::=
      <using parameter arguments>

<using parameter arguments> ::=
    USING variable_name [, ...]

<result into clause> ::=
      <into result arguments>

<into result arguments> ::=
    INTO variable_name [, ...]

Invocation and Access Rules

It can be used in an embedded SQL.
An appropriate privilege according to the type of a dynamic SQL statement is required.

Syntax Rules and Parameters

statement_name

It is the name of a prepared statement.
Statement_name should be prepared by using PREPARE statement_name.
If the dynamic SQL statement referenced by statement_name contains a dynamic parameter, <parameter using clause> should explicitly be specified.
{
    ...
    EXEC SQL PREPARE stmt1 FROM 'DELETE FROM t1 WHERE c1 > ?';
    EXEC SQL EXECUTE stmt1 USING :sValue;
    ...
}
{

    ...
    EXEC SQL PREPARE stmt1 FROM 'SELECT COUNT(*) INTO :v1 FROM t1';
    EXEC SQL EXECUTE stmt1 USING :sValue;
    ...
}

If the dynamic SQL statement referenced by statement_name is a query or a stored function including the result, <result into clause> should explicitly be specified.

{
    ...
    EXEC SQL PREPARE stmt1 FROM 'SELECT COUNT(*) FROM t1';
    EXEC SQL EXECUTE stmt1 INTO :sValue;
    ...
}
If there are multiple queries they are normally executed, but only the first query can get the result.
To get multiple results, the following statements related to the cursor should be used.

If there is not any query result, it is completed as NO DATA.

[ <parameter using clause> ] [ <result into clause> ]

<parameter using clause> and <result into clause> can be specified in any order, but they should not be repeated.

<parameter using clause>

If any parameter exists in a dynamic SQL statement referenced by statement_name, the parameter information is specified with <using parameter arguments> clause.

<using parameter arguments>

If <using parameter arguments> statement is used, the number of variable_name should be equal to the number of the parameter included in the dynamic SQL statement referenced by statement_name.

The listed variable_name corresponds to the dynamic parameter in an order of its description.

{

    ...
    EXEC SQL PREPARE stmt1 FROM 'DELETE FROM t1 WHERE c1 IN ( ?, ?, ? )';
    EXEC SQL EXECUTE stmt1 USING :sValue1, :sValue2, :sValue3;
    ... 
}

<result into clause>

If the dynamic SQL statement referenced by statement_name is a query, the information about the result columns is specified with <into result arguments> clause.
If the result is null and INDICATOR is not specified, [DATA EXCEPTION, NULL VALUE, NO INDICATOR PARAMETER] error occurs.

<into result arguments>

If <into result arguments> clause is used, the number of variable_name should be equal to the number of the result column in the dynamic SQL statement referenced by statement_name.
The listed variable_name corresponds to the dynamic parameter in an order of its description.
{

    ...
    EXEC SQL PREPARE stmt1 FROM 'SELECT MIN(salary), MAX(salary), AVG(salary) FROM employee';
    EXEC SQL EXECUTE stmt1 INTO :sMinValue, :sMaxValue, :sAvgValue;
    ... 
}

Description

Statement_name is an identifier which informs the precompiler the statement in an embedded SQL source code.
A separate type or declaration is not required because statement_name is not a host variable. EXECUTE statement_name should be written after PREPARE statement_name.
For more information, refer to Embedded Dynamic SQL.

Example

The following is an example of using EXECUTE statement_name in an embedded SQL source code.

{
    ...
    sprintf( sUpdateSql, "UPDATE EMP SET sal = sal * :v1 WHERE JOB = 'SALES'");
    EXEC SQL PREPARE UPDATE_STMT FROM :sUpdateSql;
    if(sqlca.sqlcode != 0)
    {
        goto fail_exit;
    }

    sRatio = 1.1;
    EXEC SQL EXECUTE UPDATE_STMT USING :sRatio;
    if(sqlca.sqlcode != 0)
    {
        goto fail_exit;
    }
    ...
}

The full source code in which EXECUTE statement_name was used can be viewed in Dynamic Embedded SQL Example Program.

Compatibility

SQL standard compatibility

Feature ID

Description

Compatibility

B031

Basic Dynamic SQL

O

B032

Extended dynamic SQL

X

For More Information

Refer to the followings.

FETCH cursor_name

Function

It locates the cursor on a specific row of result set, and obtains the value of that row to a host variable.

Syntax

<fetch statement> ::=
    FETCH [ <fetch orientation> ] [ FROM ] cursor_name 
        <result into clause>
    ;

<fetch orientation> ::=
      NEXT
    | PRIOR
    | FIRST
    | LAST
    | CURRENT
    | ABSOLUTE position
    | RELATIVE position

<result into clause> ::=
      <into result arguments>

<into result arguments> ::=
    INTO variable_name [, ...]

Syntax Rules and Parameters

[ FROM ] cursor_name

It should be an open cursor in a session.
FROM can be omitted.

<fetch orientation>

To use <fetch orientation> other than FETCH NEXT, a scrollable cursor should be used.
If <fetch orientation> is omitted, the default value is NEXT.
The open cursor has the cursor position information for the result set as follows.

The position of cursor

The position of cursor

The position of cursor

Cursor position

Description

BEFORE THE FIRST ROW

The cursor is positioned before the first row of the result set. It is also the cursor position when opening it.

ON A CERTAIN ROW

The cursor is positioned on a certain row of the result set through FETCH.

AFTER THE LAST ROW

The cursor is positioned after the last row of the result set.

Each <fetch orientation> operates based on the cursor position as follows.

<result into clause>

The variable information to obtain the result column is specified by using <into result arguments>.
If the result is null and INDICATOR is not specified, [DATA EXCEPTION, NULL VALUE, NO INDICATOR PARAMETER] error occurs.

<into result arguments>

The number of variables in INTO clause should be as same as the number of columns in the result set of the cursor.

Description

If the cursor is BEFORE THE FIRST ROW or AFTER THE LAST ROW after performing FETCH, it is positioned at the same position regardless of the entered position in <fetch orientation>.

Example

The following is an example of declaring SCROLL cursor by using the interactive SQL (gsql), then operating the various <fetch orientation>.

gSQL> DECLARE cur_scroll SCROLL CURSOR FOR SELECT id, data FROM t1;

Cursor declared.

gSQL> OPEN cur_scroll;

Cursor is open.

gSQL> \var v_id   INTEGER
gSQL> \var v_data VARCHAR(128)

gSQL> FETCH NEXT cur_scroll INTO :v_id, :v_data;

V_ID V_DATA
---- ------
   1 data_1

1 row fetched.

gSQL> FETCH NEXT cur_scroll INTO :v_id, :v_data;

V_ID V_DATA
---- ------
   2 data_2

1 row fetched.

gSQL> FETCH PRIOR cur_scroll INTO :v_id, :v_data;

V_ID V_DATA
---- ------
   1 data_1

1 row fetched.

gSQL> FETCH PRIOR cur_scroll INTO :v_id, :v_data;

no rows fetched.

gSQL> FETCH FIRST cur_scroll INTO :v_id, :v_data;

V_ID V_DATA
---- ------
   1 data_1

1 row fetched.

gSQL> FETCH FIRST cur_scroll INTO :v_id, :v_data;

V_ID V_DATA
---- ------
   1 data_1

1 row fetched.

gSQL> FETCH LAST cur_scroll INTO :v_id, :v_data;

V_ID V_DATA
---- ------
   5 data_5

1 row fetched.

gSQL> FETCH LAST cur_scroll INTO :v_id, :v_data;

V_ID V_DATA
---- ------
   5 data_5

1 row fetched.

gSQL> FETCH FIRST cur_scroll INTO :v_id, :v_data;

V_ID V_DATA
---- ------
   1 data_1

1 row fetched.

gSQL> FETCH CURRENT cur_scroll INTO :v_id, :v_data;

V_ID V_DATA
---- ------
   1 data_1

1 row fetched.

gSQL> FETCH LAST cur_scroll INTO :v_id, :v_data;

V_ID V_DATA
---- ------
   5 data_5

1 row fetched.

gSQL> FETCH CURRENT cur_scroll INTO :v_id, :v_data;

V_ID V_DATA
---- ------
   5 data_5

1 row fetched.

gSQL> FETCH ABSOLUTE 3 cur_scroll INTO :v_id, :v_data;

V_ID V_DATA
---- ------
   3 data_3

1 row fetched.

gSQL> FETCH CURRENT cur_scroll INTO :v_id, :v_data;

V_ID V_DATA
---- ------
   3 data_3

1 row fetched.

gSQL> FETCH ABSOLUTE 1 cur_scroll INTO :v_id, :v_data;

V_ID V_DATA
---- ------
   1 data_1

1 row fetched.

gSQL> FETCH ABSOLUTE -1 cur_scroll INTO :v_id, :v_data;

V_ID V_DATA
---- ------
   5 data_5

1 row fetched.

gSQL> FETCH ABSOLUTE 6 cur_scroll INTO :v_id, :v_data;

no rows fetched.

gSQL> FETCH ABSOLUTE -6 cur_scroll INTO :v_id, :v_data;

no rows fetched.

gSQL> FETCH ABSOLUTE 3 cur_scroll INTO :v_id, :v_data;

V_ID V_DATA
---- ------
   3 data_3

1 row fetched.

gSQL> FETCH ABSOLUTE -3 cur_scroll INTO :v_id, :v_data;

V_ID V_DATA
---- ------
   3 data_3

1 row fetched.

gSQL> FETCH RELATIVE 1 cur_scroll INTO :v_id, :v_data;

V_ID V_DATA
---- ------
   4 data_4

1 row fetched.

gSQL> FETCH RELATIVE -1 cur_scroll INTO :v_id, :v_data;

V_ID V_DATA
---- ------
   3 data_3

1 row fetched.

gSQL> FETCH RELATIVE 5 cur_scroll INTO :v_id, :v_data;

no rows fetched.

gSQL> FETCH RELATIVE -5 cur_scroll INTO :v_id, :v_data;

V_ID V_DATA
---- ------
   1 data_1

1 row fetched.

gSQL> CLOSE cur_scroll;

Cursor closed.

Compatibility

The SQL standard does not define CURRENT among <fetch orientation>.

SQL standard compatibility

Feature ID

Description

Compatibility

F431

Read-only scrollable cursors

O

B031

Basic dynamic SQL

O

For More Information

Refer to the followings.

FLASHBACK TABLE

Function

It restores the table object which is stored in the recycle bin.

Syntax

<flashback table statement> ::=
    FLASHBACK TABLE table_name
    TO BEFORE DROP [ RENAME TO new_table_name ]
    ;

Invocation and Access Rules

One of the following privileges is required to perform <flashback table statement>.

Syntax Rules and Parameters

table_name

It is the name of the object stored or of the dropped table in the recycle bin.
It can define the schema to which the table belongs in the dropped table name, such as schema_name.table_name. If schema_name is omitted, the default schema name of the user performing the statement is used.

new_table_name

It is a new name of the table to be restored.
The duplicate table name should not exist within a single schema.

Description

It restores the table object which is stored in the recycle bin by using the object name or the dropped table name stored in the recycle bin. If the name which is as same as that of the dropped table exists, then the newest table object is restored.
If the name which is as same as that of the table object to be restored exists, then an error occurs, but it can be restored with the new name by using RENAME TO clause. The constraints and the indexes of the restored tables are restored in its name of when before they were dropped. However, if their names of when before the constraints and the indexes were dropped already exist, then the object is restored in the name of when it is stored in the recycle bin.
Unlike other Data Definition Language (DDL), FLASHBACK TABLE statement can not be rolled back and the executed transaction is automatically committed.

Example

The following is an example of restoring a table with the name of the object stored in the recycle bin.

gSQL> SELECT SCHEMA_NAME, OBJECT_NAME, ORIGINAL_NAME, OBJECT_TYPE FROM USER_RECYCLEBIN;

SCHEMA_NAME OBJECT_NAME                          ORIGINAL_NAME OBJECT_TYPE
----------- ------------------------------------ ------------- -----------
PUBLIC      BIN$106A4F90165D11EA9C5C835D3E4BBBF7 T1            TABLE      

1 row selected.

gSQL> FLASHBACK TABLE "BIN$106A4F90165D11EA9C5C835D3E4BBBF7" TO BEFORE DROP;

Flashback complete.

The following is an example of restoring the table from the recycle bin in the name of when before it is dropped.

gSQL> SELECT SCHEMA_NAME, OBJECT_NAME, ORIGINAL_NAME, OBJECT_TYPE FROM USER_RECYCLEBIN;

SCHEMA_NAME OBJECT_NAME                          ORIGINAL_NAME OBJECT_TYPE
----------- ------------------------------------ ------------- -----------
PUBLIC      BIN$106A4F90165D11EA9C5C835D3E4BBBF7 T1            TABLE      

gSQL> FLASHBACK TABLE T1 TO BEFORE DROP;

Flashback complete.

Compatibility

The SQL standard does not define <flashback table statement>.

For More Information

Refer to the followings.

GRANT privileges TO

Function

It grants privileges to a user.

Syntax

<grant privilege statement> ::=
    GRANT <privilege> TO <grantee> [, ...]
        [ WITH GRANT OPTION ]
    ;

<grantee> ::=
      PUBLIC
    | user_identifier
    ;
    
<privilege> ::=
      <database privilege>
    | <tablespace privilege>
    | <schema privilege>
    | <table privilege>
    | <sequence privilege>
    | <procedure privilege>

<database privilege> ::=
      ALL [ PRIVILEGES ] [ON DATABASE]
    | <database action> [, ...] [ON DATABASE]

<database action> ::=
      ADMINISTRATION
    | ANALYZE ANY 
    | ALTER DATABASE
    | ALTER SYSTEM
    | AUDIT SYSTEM
    | ACCESS CONTROL
    | CREATE SESSION
    | CREATE PROFILE
    | ALTER PROFILE
    | DROP PROFILE 
    | CREATE USER
    | ALTER USER
    | DROP USER 
    | CREATE ROLE
    | ALTER ROLE
    | DROP ROLE
    | CREATE TABLESPACE
    | ALTER TABLESPACE
    | DROP TABLESPACE
    | USAGE TABLESPACE
    | CREATE SCHEMA
    | ALTER SCHEMA
    | DROP SCHEMA
    | CREATE PUBLIC SYNONYM
    | DROP PUBLIC SYNONYM
    | CREATE ANY TABLE
    | ALTER ANY TABLE
    | DROP ANY TABLE
    | SELECT ANY TABLE
    | INSERT ANY TABLE
    | DELETE ANY TABLE
    | UPDATE ANY TABLE
    | LOCK ANY TABLE
    | CREATE ANY VIEW
    | DROP ANY VIEW
    | CREATE ANY SEQUENCE
    | ALTER ANY SEQUENCE
    | DROP ANY SEQUENCE
    | USAGE ANY SEQUENCE
    | CREATE ANY INDEX
    | ALTER ANY INDEX
    | DROP ANY INDEX
    | CREATE ANY SYNONYM
    | DROP ANY SYNONYM
    | CREATE ANY PROCEDURE
    | ALTER ANY PROCEDURE
    | DROP ANY PROCEDURE
    | EXECUTE ANY PROCEDURE
    | PURGE DBA_RECYCLEBIN

<tablespace privilege> ::=
      ALL [ PRIVILEGES ] ON TABLESPACE tablespace_name
    | <tablespace action> [, ...] ON TABLESPACE tablespace_name

<tablespace action> ::=
    CREATE OBJECT

<schema privilege> ::=
      ALL [ PRIVILEGES ] ON SCHEMA schema_name
    | <schema action> [, ...] [ON SCHEMA schema_name]

<schema action> ::=
      CONTROL SCHEMA
    | CREATE TABLE
    | ALTER TABLE 
    | DROP TABLE
    | SELECT TABLE
    | INSERT TABLE
    | DELETE TABLE
    | UPDATE TABLE
    | LOCK TABLE
    | CREATE VIEW
    | DROP VIEW
    | CREATE SEQUENCE
    | ALTER SEQUENCE
    | DROP SEQUENCE
    | USAGE SEQUENCE
    | CREATE INDEX
    | ALTER INDEX
    | DROP INDEX
    | ADD CONSTRAINT
    | CREATE SYNONYM
    | DROP SYNONYM
    | CREATE PROCEDURE
    | ALTER PROCEDURE
    | DROP PROCEDURE
    | EXECUTE PROCEDURE

<table privilege> ::=
      ALL [ PRIVILEGES ] ON [TABLE] table_name
    | { <table action> | <column action> } [, ...] ON [TABLE] table_name

<table action> ::=
      CONTROL TABLE
    | SELECT
    | INSERT
    | UPDATE
    | DELETE
    | REFERENCES
    | LOCK
    | INDEX
    | ALTER

<column action> ::=
      SELECT ( column_name [, ...] )
    | INSERT ( column_name [, ...] )
    | UPDATE ( column_name [, ...] )
    | REFERENCES ( column_name [, ...] )

<sequence privilege> ::=
      ALL [ PRIVILEGES ] ON SEQUENCE sequence_name
    | <sequence action> ON SEQUENCE sequence_name

<sequence action> ::=
    USAGE

<procedure privilege> ::=
      ALL [ PRIVILEGES ] ON PROCEDURE procedure_name
    | <procedure action> ON PROCEDURE procedure_name

<procedure action> ::=
    EXECUTE

Syntax Rules and Parameters

<grantee>

It is the user to be granted the privileges.

WITH GRANT OPTION

It allows the grantee to grant the privilege to other users.
When the same <privilege> is granted as follows, WITH GRANT OPTION is maintained.

<privilege>

It is a privilege which is to be granted to a grantee (the user to be granted the privilege).
The grantor (the user to perform the statement) should satisfy one of the following conditions.

<database privilege>

It is the privilege for the database objects.
[ON DATABASE] statement can be omitted.
The database action which can be defined with the database privilege is as follows.
Database privilege

<database action>

Description

ADMINISTRATION

Privilege for starting or terminating the server

ALTER DATABASE

Privilege for executing ALTER DATABASE

ALTER SYSTEM

Privilege for executing ALTER SYSTEM

AUDIT SYSTEM

Privilege for controlling the audit policy

ACCESS CONTROL

Privilege for controlling all the privileges

CREATE SESSION

Privilege for connecting to the database

CREATE PROFILE

Privilege for creating profiles in the database

ALTER PROFILE

Privilege for altering any profile in the database

DROP PROFILE

Privilege for dropping any profile in the database

CREATE USER

Privilege for creating users in the database

ALTER USER

Privilege for altering any user in the database

DROP USER

Privilege for dropping any user in the database

CREATE ROLE

Privilege for creating roles in the database

ALTER ROLE

Privilege for altering any role in the database

DROP ROLE

Privilege for dropping any role in the database

CREATE TABLESPACE

Privilege for creating tablespaces in the database

ALTER TABLESPACE

Privilege for altering any tablespace in the database

DROP TABLESPACE

Privilege for dropping any tablespace in the database

USAGE TABLESPACE

Privilege for using any tablespace in the database

CREATE SCHEMA

Privilege for creating schemas in the database

ALTER SCHEMA

Privilege for altering any schema in the database

DROP SCHEMA

Privilege for dropping any schema in the database

CREATE PUBLIC SYNONYM

Privilege for creating public synonyms in the database

DROP PUBLIC SYNONYM

Privilege for dropping any public synonym in the database

CREATE ANY TABLE

Privilege for creating tables in any schema of the database

ALTER ANY TABLE

Privilege for altering any table in the database

DROP ANY TABLE

Privilege for dropping any table in the database

SELECT ANY TABLE

Privilege for querying rows of any table in the database

INSERT ANY TABLE

Privilege for creating rows of any table in the database

DELETE ANY TABLE

Privilege for deleting rows of any table in the database

UPDATE ANY TABLE

Privilege for updating rows of any table in the database

LOCK ANY TABLE

Privilege for locking any table in the database

CREATE ANY VIEW

Privilege for creating views in any schema of the database

DROP ANY VIEW

Privilege for dropping any view in the database

CREATE ANY SEQUENCE

Privilege for creating sequences in any schema of the database

ALTER ANY SEQUENCE

Privilege for altering any sequence of the database

DROP ANY SEQUENCE

Privilege for dropping any sequence of the database

USAGE ANY SEQUENCE

Privilege for using any sequence of the database

CREATE ANY INDEX

Privilege for creating indexes in any schema of the database

ALTER ANY INDEX

Privilege for altering any index in the database

DROP ANY INDEX

Privilege for dropping any index in the database

CREATE ANY SYNONYM

Privilege for creating synonyms in the database

DROP ANY SYNONYM

Privilege for dropping any synonym in the database

CREATE ANY PROCEDURE

Privilege for creating any procedure/function in any schema of the database

ALTER ANY PROCEDURE

Privilege for altering any procedure/function in the database

DROP ANY PROCEDURE

Privilege for dropping any procedure/function in the database

EXECUTE ANY PROCEDURE

Privilege for executing any procedure/function in the database

PURGE DBA_RECYCLEBIN

Privilege for dropping any recycle bin in the database

<tablespace privilege>

It is the privilege for the tablespace objects.
The tablespace action which can be defined with the tablespace privilege is as follows.
Tablespace privilege

<tablespace action>

Description

CREATE OBJECT

Privilege for creating objects in the tablespace

<schema privilege>

It is the privilege for the schema objects.

The schema action which can be defined with the schema privilege is as follows.

Schema privilege

<schema action>

Description

CONTROL SCHEMA

All privileges for that schema

CREATE TABLE

Privilege for creating tables in the schema

ALTER TABLE

Privilege for altering any table in the schema

DROP TABLE

Privilege for dropping any table in the schema

SELECT TABLE

Privilege for querying rows of any table in the schema

INSERT TABLE

Privilege for creating rows of any table in the schema

DELETE TABLE

Privilege for deleting rows of any table in the schema

UPDATE TABLE

Privilege for updating rows of any table in the schema

LOCK TABLE

Privilege for locking any table of the schema

CREATE VIEW

Privilege for creating views in the schema

DROP VIEW

Privilege for dropping any view of the schema

CREATE SEQUENCE

Privilege for creating sequences in the schema

ALTER SEQUENCE

Privilege for altering any sequence of the schema

DROP SEQUENCE

Privilege for dropping any sequence of the schema

USAGE SEQUENCE

Privilege for using any sequence of the schema

CREATE INDEX

Privilege for creating indexes in the schema

ALTER INDEX

Privilege for altering any index in the schema

DROP INDEX

Privilege for dropping any index in the schema

ADD CONSTRAINT

Privilege for creating constraints in the schema

CREATE SYNONYM

Privilege for creating synonyms in the schema

DROP SYNONYM

Privilege for dropping any synonym of the schema

CREATE PROCEDURE

Privilege for creating any procedure/function in the schema

ALTER PROCEDURE

Privilege for altering any procedure/function in the schema

DROP PROCEDURE

Privilege for dropping any procedure/function in the schema

EXECUTE PROCEDURE

Privilege for executing any procedure/function in the schema

<table privilege>

It is the privilege for the table object or the view object.
[TABLE] statement can be omitted.
The table action which can be defined with the table privilege is as follows.
Table privilege

<table action>

Description

CONTROL TABLE

All privileges for that table

SELECT

Privilege for querying rows of the table

INSERT

Privilege for creating rows into the table

UPDATE

Privilege for updating rows in the table

DELETE

Privilege for deleting rows from the table

REFERENCES

Privilege for creating referential constraints which refers to the table

LOCK

Privilege for locking the table

INDEX

Privilege for creating indexes in the table

ALTER

Privilege for altering the table

For SELECT, INSERT, UPDATE, REFERENCES, additional privileges are granted to all columns of the table.
The column action which can be defined with the table privilege is as follows. However, the column action is applicable only to the base table.
Column privilege

<column action>

Description

SELECT (columns)

Privilege for querying that columns

INSERT (columns)

Privilege for creating rows including that columns

UPDATE (columns)

Privilege for updating that columns

REFERENCES (columns)

Privilege for creating referential constraints which refers to that columns

<sequence privilege>

It is the privilege for the sequence object.
The sequence action which can be defined with the sequence privilege is as follows.
Sequence privilege

<sequence action>

Description

USAGE

Privilege for using the sequence

<procedure privilege>

It is the privilege for the procedure/ function object.
The action which can be defined with the procedure privilege is as follows.
Procedure privilege

<procedure action>

Description

EXECUTE

Privilege for executing the procedure/function

Description

Data Definition Language (DDL) such as GRANT privilege can be rolled back if it is before when the transaction is committed.
The owner who created SQL schema object, such as table, sequence, has certain privileges without being granted any separate privilege for the object.  
For more information, refer to the following CREATE statements.
The owner who created non-schema object such as schema, tablespace, does not automatically have any privilege for the object. Therefore, the privilege should be separately granted. 
For more information, refer to the following CREATE statements.

Examples

The following is an example of granting SELECT ON TABLE t1 privilege to the user u1.

gSQL> GRANT SELECT ON t1 TO u1;

Grant succeeded.

The following is an example of granting SELECT ON TABLE t1 privilege to the PUBLIC account (all users).

gSQL> GRANT SELECT ON t1 TO PUBLIC;

Grant succeeded.

The following is an example that the user u1 grants the privilege to the other user by using WITH GRANT OPTION.

gSQL> GRANT SELECT ON t1 TO u1 WITH GRANT OPTION;

Grant succeeded.

The following is the example that the user executing the statement grants all privileges on the TABLE t1 to user u1 by using WITH GRANT OPTION.

gSQL> GRANT ALL PRIVILEGES ON TABLE t1 TO u1;

Grant succeeded.

The following is an example of granting CREATE SESSION ON DATABASE privilege which is a privilege for connecting to the database.

gSQL> GRANT CREATE SESSION ON DATABASE TO u1;

Grant succeeded.

The following is an example of granting multiple privileges for creating objects such as the table, view, index, sequence, constraint in the SCHEMA s1 to the user u1.

gSQL> GRANT CREATE TABLE, CREATE VIEW, CREATE INDEX, CREATE SEQUENCE, ADD CONSTRAINT ON SCHEMA s1 TO u1;

Grant succeeded.

The following is an example of granting the privileges for creating objects in TABLESPACE mem_data_tbs to the user u1.

gSQL> GRANT CREATE OBJECT ON TABLESPACE mem_data_tbs TO u1;

Grant succeeded.

The following is an example of granting the privilege for querying some columns in the TABLE t1 to the user u1.

gSQL> GRANT SELECT( id, name ) ON TABLE t1 TO u1;

Grant succeeded.

The following is an example of granting the privilege to the user u1 for using NEXTVAL(), CURRVAL() functions in the SEQUENCE seq1.

gSQL> GRANT USAGE ON SEQUENCE seq1 TO u1;
Grant succeeded.

Compatibility

The SQL standard does not define the following privileges.

SQL standard compatibility

Feature ID

Description

Compatibility

S023

Basic structured types

X

S024

Enhanced structured types

X

S081

Subtables

X

T211

Basic trigger capability

X

T281

SELECT privilege with column granularity

O

T332

Extended Roles

X

F731

INSERT column privileges

O

For More Information

Refer to the followings.

INSERT INTO

Function

It creates new rows in a table.

Syntax

<insert statement> ::=
    INSERT INTO table_name [ ( column_name [, ...] ) ]
        <insert source>
    ;

<insert source> ::=
      <values clause>
    | <from subquery>
    | <from default>

<values clause> ::=
    VALUES { ( { <value expression> | DEFAULT } [, ...] ) } [, ...]

<from subquery> ::=
    <query expression>

<from default> ::=
    DEFAULT VALUES

Invocation and Access Rules

A user should satisfy the following conditions to perform <Insert statement>.

Syntax Rules and Parameters

table_name

It is the name of a target table in which the row is to be created.
It can define schema to which the table belongs such as schema_name.table_name and if schema_name is omitted, the default schema name of the user performing the statement is used.

[ ( column_name [, ...] ) ]

It is the column name of a table.
The column list can be omitted.
The number of columns and the number of  <insert source> values should be same, and DEFAULT value is assigned to the omitted column.

<values clause>

It is the list of values to be assigned to the corresponding columns.

Multiple rows can be created as follows.

INSERT INTO table_name VALUES ( 1, 'A' ), ( 2, 'B' ), ( 3, 'C' )

<from subquery>

It is the query to create rows.
For more information, refer to query expression clause of SELECT statement.

DEFAULT VALUES

It fills every column with default value.
DEFAULT VALUES clause means as same as the following.
VALUES ( DEFAULT, DEFAULT, ..., DEFAULT )

Description

Differences among INSERT-related Statements

Examples

The following is an example of creating a single row by using INSERT statement.

gSQL> INSERT INTO region VALUES ( 0, 'AFRICA' );

1 row created.

The following is an example of using the DEFAULT value or identity value of the column in INSERT statement.

gSQL> CREATE TABLE region
(
    r_regionkey   BIGINT    GENERATED BY DEFAULT AS IDENTITY
  , r_name        CHAR(25)  DEFAULT 'N/A'
);

Table created.

gSQL> COMMIT;

Commit complete.

• DEFAULT is inserted into all columns.

gSQL> INSERT INTO region DEFAULT VALUES;

1 row created.

• DEFAULT is inserted into all columns.

gSQL> INSERT INTO region VALUES (DEFAULT, DEFAULT);

1 row created.

• If a column is omitted, the DEFAULT value of r_name column is used.

gSQL> INSERT INTO region(r_regionkey) VALUES (-100);

1 row created.

• If a column is omitted, the identity value of r_regionkey column is used.

gSQL> INSERT INTO region(r_name) VALUES ('ASIA');

1 row created.


gSQL> SELECT * FROM region;

R_REGIONKEY R_NAME                   
----------- -------------------------
          1 N/A                      
          2 N/A                      
       -100 N/A                      
          3 ASIA                     

4 rows selected.

The following is an example of creating multiple rows by describing them in VALUES clause.

gSQL> INSERT INTO region
       VALUES ( 1, 'AFRICA' ),
              ( 2, 'ASIA'   ),
              ( 3, 'EUROPE' );

3 rows created.

The following is an example of creating multiple rows by using a subquery.

gSQL> INSERT INTO region SELECT r_regionkey, r_name FROM tmp_region WHERE r_regionkey < 3;

3 rows created.

Compatibility

SQL standard compatibility

Feature ID

Description

Compatibility

F781

Self-referencing operations

X

F222

INSERT statement: DEFAULT VALUES clause

O

S204

Enhanced structured types

X

S043

Enhanced reference types

X

T111

Updatable joins, unions, and columns

X

For More Information

Refer to the followings.

INSERT INTO name RETURNING

Function

It creates new rows in the table, and retrieves them.

Syntax

<insert statement> ::=
    INSERT INTO table_name [ ( column_name [, ...] ) ]
        <insert source>
        <returning clause>
    ;

<insert source> ::=
      <values clause>
    | <from subquery>
    | <from default>

<values clause> ::=
    VALUES { ( { <value expression> | DEFAULT } [, ...] ) } [, ...]

<from subquery> ::=
    <query expression>

<from default> ::=
    DEFAULT VALUES

<returning clause> ::=
      [ RETURN | RETURNING ] { * | { <value expression> [ [AS] alias_name ] } [, ...]

Invocation and Access Rules

A user should satisfy the following conditions to perform <insert returning query statement>.

Syntax Rules and Parameters

table_name

It is the name of a target table in which the row is to be created.

[ ( column_name [, ...] ) ]

It is the column name of a table.
For more information, refer to INSERT INTO.

<values clause>

It is the list of values to be assigned to the corresponding columns.
For more information, refer to INSERT INTO.

<from subquery>

It is the query to create rows.
For more information, refer to INSERT INTO.

DEFAULT VALUES

It fills every column with default value.
For more information, refer to INSERT INTO.

<returning clause>

It returns the inserted rows.

The keywords RETURNING and RETURN have the same meaning.

Description

For more information, refer to Differences among INSERT-related Statements.

Examples

The following is an example of retrieving the column values created by using INSERT statement.

gSQL> CREATE TABLE region
(
    r_regionkey   BIGINT    GENERATED BY DEFAULT AS IDENTITY
  , r_name        CHAR(25)  DEFAULT 'N/A'
);

Table created.

gSQL> COMMIT;

Commit complete.
gSQL> INSERT INTO region VALUES ( DEFAULT, DEFAULT ) RETURNING r_regionkey, r_name;

R_REGIONKEY R_NAME                   
----------- -------------------------
          1 N/A                      

1 row created.
gSQL> INSERT INTO region(r_name) VALUES ('ASIA') RETURNING r_regionkey;

R_REGIONKEY
-----------
          2

1 row created.

The following is an example of retrieving the rows created by using the subquery.

gSQL> INSERT INTO region 
      SELECT r_regionkey, r_name FROM tmp_region WHERE r_regionkey < 3 
      RETURNING r_regionkey, r_name;

R_REGIONKEY R_NAME                   
----------- -------------------------
          0 AFRICA                   
          1 AMERICA                  
          2 ASIA                     

3 rows created.

Compatibility

The SQL standard does not define <insert returning query statement>.

For More Information

Refer to the followings.

INSERT INTO name RETURNING .. INTO

Function

It creates a single row in a table, and obtains the value of the created row as a host variable.

Syntax

<insert statement> ::=
    INSERT INTO table_name [ ( column_name [, ...] ) ]
        <insert source>
        <returning into clause>
    ;

<insert source> ::=
      <values clause>
    | <from subquery>
    | <from default>

<values clause> ::=
    VALUES { ( { <value expression> | DEFAULT } [, ...] ) } [, ...]

<from subquery> ::=
    <query expression>

<from default> ::=
    DEFAULT VALUES

<returning into clause> ::=
      [ RETURN | RETURNING ] { * | { <value expression> [ [AS] alias_name ] } [, ...] INTO variable_name [, ...]

Invocation and Access Rules

A user should satisfy the following conditions to perform <insert returning into statement>.

Syntax Rules and Parameters

table_name

It is the name of a target table in which the row is to be created.

[ ( column_name [, ...] ) ]

It is the column name of a table.
For more information, refer to INSERT INTO.

<values clause>

It is the list of values to be assigned to the corresponding columns.
For more information, refer to INSERT INTO.

<from subquery>

It is the query to create rows.
For more information, refer to INSERT INTO.

DEFAULT VALUES

It fills every column with default value.
For more information, refer to INSERT INTO.

<returning clause>

It returns the inserted rows.
For more information, refer to <returning clause> in INSERT INTO name RETURNING statement.

INTO variable_name [, ...]

The number of variables in INTO clause should be equal to the number of the expressions in RETURNING clause.
The row to be created should be one or less. If two or more rows are created, an error occurs.

Description

For more information, refer to Differences among INSERT-related Statements.

Example

The following is an example of obtaining the value of the created row as a host variable.

gSQL> CREATE TABLE region
(
    r_regionkey   BIGINT    GENERATED BY DEFAULT AS IDENTITY
  , r_name        CHAR(25)  DEFAULT 'N/A'
);

Table created.

gSQL> COMMIT;

Commit complete.

• The host variables are declared.

\VAR v_key  BIGINT
\VAR v_name VARCHAR(128)

• The created DEFAULT values are obtained as the host variables.

gSQL> INSERT INTO region 
      VALUES ( DEFAULT, DEFAULT ) 
      RETURNING r_regionkey, r_name 
      INTO :v_key, :v_name;

V_KEY V_NAME                   
----- -------------------------
    1 N/A                      

1 row created.

• The omitted column value is obtained as the host variable.

gSQL> INSERT INTO region(r_name) 
      VALUES ('ASIA') 
      RETURNING r_regionkey 
      INTO :v_key;

V_KEY
-----
    2

1 row created.

Compatibility

The SQL standard does not define <insert returning into statement>.

For More Information

Refer to the followings.

LOCK TABLE

Function

It locks one or more tables.

Syntax

<lock table statement> ::=
    LOCK TABLE lock target [, ...] 
    IN <lock mode> MODE [<wait clause>]
    ;

<lock mode> ::=
    SHARE
    | EXCLUSIVE
    | ROW SHARE
    | ROW EXCLUSIVE
    | SHARE ROW EXCLUSIVE


<wait clause> ::=
    NOWAIT
    | WAIT time

Invocation and Access Rules

One of the following privileges is required to perform <lock table statement>.

Syntax Rules and Parameters

<lock target>

It specifies the target table to be locked.

<lock mode>

It specifies the LOCK mode.

<wait clause>

It specifies the waiting time to acquire the lock.

Description

If the transaction is committed or rolled back all acquired locks are automatically released. When using ROLLBACK TO SAVEPOINT statement, all locks acquired since that savepoint are released.

Examples

The following is an example of locking the TABLE t1 to prevent any updating operation by another transaction.

gSQL> LOCK TABLE t1 IN EXCLUSIVE MODE;

Table locked.

The following is an example of performing LOCK statement for multiple tables.

gSQL> LOCK TABLE t1, t2 IN EXCLUSIVE MODE;

Table locked.

The following is an example of acquiring SHARE ROW EXCLUSIVE lock for the TABLE t1.

gSQL> LOCK TABLE t1 IN SHARE ROW EXCLUSIVE MODE;

Table locked.

The following statement is performed only when the lock can be immediately acquired for the table. If the lock can not be acquired, an error occurs.

gSQL> LOCK TABLE t1 IN EXCLUSIVE MODE NOWAIT;

Table locked.

The following is an example of waiting 10 seconds to acquire the lock.

gSQL> LOCK TABLE t1 IN EXCLUSIVE MODE WAIT 10;

Table locked.

Compatibility

The SQL standard does not cover the concepts of the lock table.

For More Information

Refer to the followings.

NOAUDIT POLICY

Function

It deactivates the audit policy.

Syntax

<noaudit policy statement> ::= 
    NOAUDIT POLICY policy_name
    [ <specified_user_option> ]
    ;

<specified_user_option> ::=
      BY user_name [, ...]

Invocation and Access Rules

AUDIT SYSTEM ON DATABASE privilege is required to perform <noaudit policy statement>.

Syntax Rules and Parameters

policy_name

It is the name of the audit policy object to be deactivated.
The deactivated audit policy does not effect on the existing session, and it effects only on the newly created session.

<specified_user_option>

It specifies the user to be excluded from the auditing target.

Unlike AUDIT POLICY statement, NOAUDIT POLICY does not have EXCEPT option.

If AUDIT POLICY name BY clause is used, NOAUDIT POLICY name BY statement should be used to deactivate it.
If AUDIT POLICY name EXCEPT clause is used, NOAUDIT POLICY name statement without BY clause should be used to deactivate it.

NOAUDIT POLICY statement should be used as follows according to the usage of AUDIT POLICY statement to deactivate it.

Activating/ deactivating audit policy

Type

AUDIT POLICY statement

NOAUDIT POLICY statement

All users

AUDIT POLICY p1

NOAUDIT POLICY p1

Using BY

AUDIT POLICY p1 BY u1

NOAUDIT POLICY p1 BY u1

Using EXCEPT

AUDIT POLICY p1 EXCEPT u1

NOAUDIT POLICY p1

When deactivating all activated users, the audit policy object is completely deactivated.

Description

The activation information of an audit policy object can be queried as follows.

SELECT policy_name
     , enabled_opt
     , user_name
  FROM audit_policy_enabled
 WHERE policy_name = 'P1';
NOAUDIT POLICY statement deletes each created information about activationaccording to the AUDIT POLICY specifying method.
If the information activated through the query above does not exist, then the audit policy is completely deactivated.

If all users are activated as follows, NOAUDIT POLICY BY clause does not does not affect it.

AUDIT POLICY p1;
NOAUDIT POLICY p1 BY u1;
NOAUDIT POLICY p1;

If one or more users are separately activated, use NOAUDIT POLICY statement according to the AUDIT POLICY specifying method.

When Activated by Using BY

If the audit policy is activated as follows,

AUDIT POLICY p1 WHENEVER NOT SUCCESSFUL;
AUDIT POLICY p1 BY u1;
AUDIT POLICY p1 BY u2;

the information about activation is as follows.

SELECT policy_name
     , enabled_opt
     , user_name
     , when_success
     , when_failure
  FROM audit_policy_enabled
 WHERE policy_name = 'P1';

POLICY_NAME  ENABLED_OPT  USER_NAME    WHEN_SUCCESS  WHEN_FAILURE
-----------  -----------  ---------    ------------  ------------
P1           BY           ALL USERS    NO            YES
P1           BY           U1           YES           YES
P1           BY           U2           YES           YES

The following is an example of performing NOAUDIT statement and the information about activation.

NOAUDIT POLICY p1;

SELECT policy_name
     , enabled_opt
     , user_name
     , when_success
     , when_failure
  FROM audit_policy_enabled
 WHERE policy_name = 'P1';

POLICY_NAME  ENABLED_OPT  USER_NAME    WHEN_SUCCESS    WHEN_FAILURE
-----------  -----------  ---------    ------------    ------------
P1           BY           U1           YES             YES
P1           BY           U2           YES             YES
The auditing for a failure for ALL USERS is deactivated, but the auditing for user u1, u2 is still activated.

If NOAUDIT POLICY statement is additionally used through BY option as follows, then audit policy p1 is completely deactivated.

NOAUDIT POLICY p1 BY u1, u2;

SELECT policy_name
     , enabled_opt
     , user_name
     , when_success
     , when_failure
  FROM audit_policy_enabled
 WHERE policy_name = 'P1';

no rows selected.

When Activated by Using EXCEPT

If the audit policy is activated as follows,

AUDIT POLICY p1 EXCEPT u1, sys;

the information about activation is as follows.

SELECT policy_name
     , enabled_opt
     , user_name
     , when_success
     , when_failure
  FROM audit_policy_enabled
 WHERE policy_name = 'P1';

POLICY_NAME  ENABLED_OPT  USER_NAME    WHEN_SUCCESS    WHEN_FAILURE
-----------  -----------  ---------    ------------    ------------
P1           EXCEPT       U1           YES             YES
P1           EXCEPT       SYS          YES             YES
Unlike AUDIT POLICY statement, NOAUDIT POLICY does not have EXCEPT option, so execute the statement without an option as follows.
NOAUDIT POLICY p1;

SELECT policy_name
     , enabled_opt
     , user_name
     , when_success
     , when_failure
  FROM audit_policy_enabled
 WHERE policy_name = 'P1';

no rows selected.
In other words, if the audit policy is activated by using EXCEPT option, each user can not be deactivated again by using NOAUDIT POLICY statement.

Examples

The following is an example of deactivating all users.

NOAUDIT POLICY table_pol;

The following is an example of deactivating a specific activated user by using BY.

NOAUDIT POLICY table_pol BY u1;

Compatibility

The SQL standard does not have the audit policy.

For More Information

Refer to the followings.

OPEN cursor_name

Function

It opens a cursor.

Syntax

<open statement> ::=
    OPEN cursor_name [ <parameter using clause> ]
    ;

<parameter using clause> ::=
      <using parameter arguments>

<using parameter arguments> ::=
    USING variable_name [, ...]

Invocation and Access Rules

If cursor_name is a dynamic cursor which is declared by using PREPARE statement_name and DECLARE cursor_name, it can be used in an embedded SQL.
It is same with the privilege of <cursor query> included in DECLARE cursor_name which declared cursor_name.

Syntax Rules and Parameters

cursor_name

It should be a cursor declared with DECLARE cursor_name within the session.

<parameter using clause>

It can be used in an embedded SQL.
When <parameter using clause> is used, cursor_name should be a dynamic cursor declared by using PREPARE statement_name and DECLARE cursor_name.

<using parameter arguments>

When <using parameter arguments> is used, the number of variable_name should be equal to the number of the parameter included in a query which is referenced by PREPARE statement_name.
The listed variable_name corresponds to the dynamic parameter in an order of its description.
{
    ...
    EXEC SQL PREPARE stmt1 FROM 'SELECT c1, c2 FROM t1 WHERE c1 IN ( ?, ?, ? )';
    EXEC SQL DECLARE cur1 CURSOR FOR stmt1;
    EXEC SQL OPEN cur1 USING :sValue1, :sValue2, :sValue3;
    ...
    EXEC SQL WHENEVER NOT FOUND DO break;
    for(;;)
    {
        EXEC SQL FETCH cur1 INTO :sC1, :sC2;    
    }
    EXEC SQL WHENEVER NOT FOUND CONTINUE;
    ...
    EXEC SQL CLOSE cur1;    
    ... 
}

Description

The cursor is a distinguishable object in a session. The cursor being used in the current session has nothing to do with the cursor being used in another session.
To use OPEN cursor_name statement, it should be a cursor declared with DECLARE cursor_name, and it should be a closed cursor.

Examples

The following is an example of declaring a cursor and using OPEN cursor statement in an interactive SQL (gsql).

gSQL> DECLARE cur1 CURSOR FOR SELECT id, data FROM t1;

Cursor declared.

gSQL> OPEN cur1;

Cursor is open.

gSQL> \var v_id   INTEGER
gSQL> \var v_data VARCHAR(128)

gSQL> FETCH cur1 INTO :v_id, :v_data;

V_ID V_DATA
---- ------
   1 data_1

1 row fetched.

gSQL> FETCH cur1 INTO :v_id, :v_data;

V_ID V_DATA
---- ------
   2 data_2

1 row fetched.

gSQL> FETCH cur1 INTO :v_id, :v_data;

V_ID V_DATA
---- ------
   3 data_3

1 row fetched.

gSQL> FETCH cur1 INTO :v_id, :v_data;

V_ID V_DATA
---- ------
   4 data_4

1 row fetched.

gSQL> FETCH cur1 INTO :v_id, :v_data;

V_ID V_DATA
---- ------
   5 data_5

1 row fetched.

gSQL> FETCH cur1 INTO :v_id, :v_data;

no rows fetched.

gSQL> CLOSE cur1;

Cursor closed.

Compatibility

SQL standard compatibility

Feature ID

Description

Compatibility

B031

Basic Dynamic SQL

O

For More Information

Refer to the followings.

PREPARE statement_name

Function

It prepares a dynamic SQL statement for a repeated execution.

Syntax

<prepare statement> ::=
    PREPARE statement_name FROM <SQL statement variable>
    ;

<SQL statement variable> ::=
      variable_name
    | 'sql statement'
    | "sql statement"
    | sql statement

Invocation and Access Rules

It can be used in an embedded SQL.
An appropriate privilege according to the type of a dynamic SQL statement is required.

Syntax Rules and Parameters

statement_name

It is the name of the statement to be prepared.
The length of the statement name should be shorter than 128 bytes.
EXECUTE statement_name and DECLARE cursor_name, which are to be performed later, refers to the statement_name.
If the same statement_name exists, the previously prepared dynamic SQL is dropped.
{
    ...

    EXEC SQL PREPARE stmt1 FROM 'DELETE FROM t1';
    ...
    EXEC SQL PREPARE stmt1 FROM 'UPDATE t1 SET c1 = c1 + 10';
    ...
}

<SQL statement variable>

<SQL statement variable> can be used as following four types.

The single quote (') is used twice as follows to represent string data within single-quoted string.

{
    ...
    PREPARE stmt_name FROM 'INSERT INTO t1 VALUES ( ''literal data'' )'; 
    ...
}
The dynamic SQL statement referenced by <SQL statement variable> can use a host variable (:var) or parameter marker (?). 
However, if the unquoted SQL statement is used, the parameter marker (?) can not be used.
Depending on the characteristics of the referenced dynamic SQL statements, the variable can be either input or output dynamic parameter. 
The dynamic parameter described in the dynamic SQL statement does not have a meaning for the variable name, and it is identified by the specified order regardless of its type.
{
    ...
    int sValue1;
    int sValue2;
    ...
    EXEC SQL PREPARE stmt1 FROM 'DELETE FROM t1 WHERE c1 BETWEEN ? AND ?';
    EXEC SQL EXECUTE stmt1 USING :sValue1, :sValue2;   
    ...
}
{
    ...
    int sValue1;
    int sValue2;
    ...
    EXEC SQL PREPARE stmt1 FROM 'SELECT SUM(c2) INTO :v1 FROM t1 WHERE c1 > :v2';
    EXEC SQL EXECUTE stmt1 USING :sValue1, :sValue2;
    ...
}

variable_name

The type corresponding to variable_name should be a character string.
The dynamic SQL statement defined in variable_name should be valid.

sql statement

The dynamic SQL statement defined in the sql statement should be valid.

Description

PREPARE statement_name FROM sql_string statement analyzes SQL statement to use EXECUTE or cursor statement. Statement_name is an identifier which informs the precompiler the statement in an embedded SQL source code. A separate type or declaration is not required because statement_name is not a host variable.
For more information, refer to Embedded Dynamic SQL.

Example

The following is an example of using PREPARE statement_name in an embedded SQL source code.

{
    ...
    sprintf( sUpdateSql, "UPDATE EMP SET sal = sal * :v1 WHERE JOB = 'SALES'");
    EXEC SQL PREPARE UPDATE_STMT FROM :sUpdateSql;
    if(sqlca.sqlcode != 0)
    {
        goto fail_exit;
    }

    sRatio = 1.1;
    EXEC SQL EXECUTE UPDATE_STMT USING :sRatio;
    if(sqlca.sqlcode != 0)
    {
        goto fail_exit;
    }
    ...
}

The full source code in which PREPARE statement_name was used can be viewed in Dynamic Embedded SQL Example Program.

Compatibility

SQL standard compatibility

Feature ID

Description

Compatibility

B031

Basic Dynamic SQL

O

B034

Dynamic specification of cursor attributes

X

For More Information

Refer to the followings.

PURGE

Function

It permanently drops objects stored in the recycle bin.

Syntax

<purge statement> :==
    PURGE <purge action>
    ;

<purge action> :==
     TABLE table_name
   | INDEX index_name
   | CONSTRAINT constraint_name
   | TABLESPACE tablespace_name [ USER user_name ]
   | RECYCLEBIN 
   | USER_RECYCLEBIN
   | DBA_RECYCLEBIN

Invocation and Access Rules

One of the following privileges is required for a user to perform <purge statement>.

Syntax Rules and Parameters

table_name

It is the name of the object stored or of the dropped table in the recycle bin.
It can define the schema to which the table belongs in the dropped table name, such as schema_name.table_name. If schema_name is omitted, the default schema name of the user performing the statement is used. In this case, indexes and constraints which are related to the table are also dropped.

index_name

It is the name of the object stored or of the dropped index in the recycle bin. 
It can define the schema to which the index belongs such as schema_name.index_name. 
If schema_name is omitted, the default schema name of the user performing the statement is used. 
The key index which is created with a constraint should be dropped with the constraint.

constraint_name

It is the name of the object stored or of the dropped constraint in the recycle bin.

tablespace_name

It is the name of the tablespace. 
When assigning USER, DROP ANY TABLE ON DATABASE privilege is required.

user_name

It is the name of the user.

recyclebin

It is the alias of user_recyclebin.

user_recyclebin

It drops all recycle bins owned by a user.

dba_recyclebin

It drops all recycle bins in the database. 
PURGE DBA_RECYCLEBIN ON DATABASE privilege is required.

Description

It permanently drops objects stored in the recycle bin by using the object name or the dropped table name stored in the recycle bin. If the name which is as same as that of the dropped table exists, then the oldest table object is dropped.
When specifying a tablespace in the recycle bin object owned by a user, then only the objects included in the tablespace are dropped. In this case, if a user is assigned, then only the objects included in the specified tablespace owned by the user are dropped.
PURGE TABLE, INDEX, CONSTRAINT statements  can be rolled back if it is before when the transaction is committed. However, PURGE TABLESPACE, RECYCLEBIN, DBA_RECYCLEBIN statements can not be rolled back, and the transaction which performed the statement is automatically committed.

Example

The following is an example of dropping a table stored in the recycle bin.

gSQL> SELECT OBJECT_NAME, ORIGINAL_NAME, OBJECT_TYPE FROM USER_RECYCLEBIN;

OBJECT_NAME                          ORIGINAL_NAME        OBJECT_TYPE
------------------------------------ -------------------- -----------
BIN$135B9908166111EA9C5C835D3E4BBBF7 T1                   TABLE      
BIN$135B993A166111EA9C5C835D3E4BBBF7 T1_PRIMARY_KEY       CONSTRAINT 
BIN$135B991C166111EA9C5C835D3E4BBBF7 T1_PRIMARY_KEY_INDEX INDEX      
BIN$135B9926166111EA9C5C835D3E4BBBF7 T1_IDX1              INDEX      

4 rows selected.

gSQL> PURGE TABLE t1;

Table purged.

The following is an example of dropping an index stored in the recycle bin.

gSQL> SELECT OBJECT_NAME, ORIGINAL_NAME, OBJECT_TYPE FROM USER_RECYCLEBIN;

OBJECT_NAME                          ORIGINAL_NAME        OBJECT_TYPE
------------------------------------ -------------------- -----------
BIN$135B9908166111EA9C5C835D3E4BBBF7 T1                   TABLE      
BIN$135B993A166111EA9C5C835D3E4BBBF7 T1_PRIMARY_KEY       CONSTRAINT 
BIN$135B991C166111EA9C5C835D3E4BBBF7 T1_PRIMARY_KEY_INDEX INDEX      
BIN$135B9926166111EA9C5C835D3E4BBBF7 T1_IDX1              INDEX      

4 rows selected.

gSQL> PURGE INDEX t1_idx1;

Index purged.

The following is an example of dropping constraints stored in the recycle bin.

gSQL> SELECT OBJECT_NAME, ORIGINAL_NAME, OBJECT_TYPE FROM USER_RECYCLEBIN;

OBJECT_NAME                          ORIGINAL_NAME        OBJECT_TYPE
------------------------------------ -------------------- -----------
BIN$135B9908166111EA9C5C835D3E4BBBF7 T1                   TABLE      
BIN$135B993A166111EA9C5C835D3E4BBBF7 T1_PRIMARY_KEY       CONSTRAINT 
BIN$135B991C166111EA9C5C835D3E4BBBF7 T1_PRIMARY_KEY_INDEX INDEX      

3 rows selected.

gSQL> PURGE CONSTRAINT t1_primary_key;

Constraints purged.

The following is an example of dropping objects included in the tablespace stored in the recycle bin.

gSQL> SELECT OBJECT_NAME, ORIGINAL_NAME, OBJECT_TYPE, TABLESPACE_NAME FROM USER_RECYCLEBIN;

OBJECT_NAME                          ORIGINAL_NAME OBJECT_TYPE TABLESPACE_NAME
------------------------------------ ------------- ----------- ---------------
BIN$02C76B24166311EA9C5C835D3E4BBBF7 T1            TABLE       MEM_DATA_TBS   

1 row selected.

gSQL> PURGE TABLESPACE MEM_DATA_TBS;

Tablespace purged.

The following is an example of dropping all recycle bins owned by a user.

gSQL> SELECT OBJECT_NAME, ORIGINAL_NAME, OBJECT_TYPE FROM USER_RECYCLEBIN;

OBJECT_NAME                          ORIGINAL_NAME        OBJECT_TYPE
------------------------------------ -------------------- -----------
BIN$64F6BFFC166311EA9C5C835D3E4BBBF7 T1                   TABLE      
BIN$64F6C042166311EA9C5C835D3E4BBBF7 T1_PRIMARY_KEY       CONSTRAINT 
BIN$64F6C010166311EA9C5C835D3E4BBBF7 T1_PRIMARY_KEY_INDEX INDEX      
BIN$64F6C024166311EA9C5C835D3E4BBBF7 T1_IDX1              INDEX      

4 rows selected.

gSQL> PURGE USER_RECYCLEBIN;

Recyclebin purged.

The following is an example of dropping all recycle bins in the system.

gSQL> SELECT OWNER, OBJECT_NAME, ORIGINAL_NAME, OBJECT_TYPE FROM USER_RECYCLEBIN;

OWNER OBJECT_NAME                          ORIGINAL_NAME        OBJECT_TYPE
----- ------------------------------------ -------------------- -----------
TEST  BIN$F0FB26F0166311EAA7C5D51B86D72AB6 T1                   TABLE      
TEST  BIN$F0FB272C166311EAA7C5D51B86D72AB6 T1_PRIMARY_KEY       CONSTRAINT 
TEST  BIN$F0FB2704166311EAA7C5D51B86D72AB6 T1_PRIMARY_KEY_INDEX INDEX      
TEST  BIN$F0FB2718166311EAA7C5D51B86D72AB6 T1_IDX1              INDEX      

4 rows selected.

gSQL> PURGE DBA_RECYCLEBIN;

DBA Recyclebin purged.

Compatibility

The SQL standard does not define <purge statement>.

For More Information

Refer to the followings.

RELEASE SAVEPOINT savepoint_specifier

Function

It releases a savepoint.

Syntax

<release savepoint statement> ::=
    RELEASE SAVEPOINT savepoint_name 
    ;

Syntax Rules and Parameters

savepoint_name

It is a name of the savepoint, and it should exist. 
The length of the savepoint name should be shorter than 128 bytes.

Description

If multiple savepoints are defined and RELEASE SAVEPOINT savepoint_name statement is performed, all savepoints defined since the savepoint_name are also released.

Example

The following is an example of releasing a savepoint.

gSQL> RELEASE SAVEPOINT sp2;

Savepoint dropped.

Compatibility

SQL standard compatibility

Feature ID

Description

Compatibility

T271

Savepoints

O

For More Information

Refer to the followings.

REVOKE privileges FROM

Function

It revokes the granted privilege from a user.

Syntax

<revoke privilege statement> ::=
    REVOKE [ <revoke option extention> ] <privilege>
      FROM <grantee> [, ...]
      [ <revoke behavior> ]
    ;

<revoke option extention> ::=
      GRANT OPTION FOR

<revoke behavior> ::=
      RESTRICT
    | CASCADE
    | CASCADE CONSTRAINTS

Syntax Rules and Parameters

<privilege>

It is a privilege which is to be revoked from the revokee (the user whose privilege is to be revoked).
The revoker (the user who performs the statement) should satisfy one of the following conditions.
When using ALL [PRIVILEGES], it succeeds even when the satisfying <privilege> does not exist.
For more information about the types of <privilege>, refer to <privilege> clause of GRANT privileges TO statement.

<grantee>

It is a user whose privilege is to be revoked.

GRANT OPTION FOR

It revokes WITH GRANT OPTION included in the privilege. 
It also revokes WITH GRANT OPTION of the dependent privilege.
The privilege is maintained.

<revoke behavior>

Description

Data Definition Language (DDL) such as REVOKE privilege can be rolled back if it is before when the transaction is committed.
When performing the following DROP statement, all privilege information related to the object is revoked even without performing any separate REVOKE statement.

Examples

The following is an example of revoking multiple privileges for the table t1.

gSQL> REVOKE INSERT, UPDATE, DELETE, LOCK, ALTER, INDEX ON t1 FROM u1;

Revoke succeeded.

The following is an example of revoking SELECT ON TABLE t1 privilege granted to the PUBLIC account, which means all users. However, only the privilege for PUBLIC account is revoked, and SELECT ON TABLE t1 privilege which was explicitly granted to a specific user is not revoked.

gSQL> REVOKE SELECT ON t1 FROM PUBLIC;

Revoke succeeded.

The following is an example that SELECT ON TABLE t1 privilege granted to user u1 is remained, and only REVOKE GRANT OPTION which can grant the privilege to another user is revoked.

gSQL> REVOKE GRANT OPTION FOR SELECT ON t1 FROM u1;

Revoke succeeded.

The following is an example that an error occurs when the privilege granted to the user u1 is revoked by using RESTRICT option and the user u1 grants it to another user. CASCADE option is used to revoke these dependent privileges as well.

gSQL> REVOKE SELECT ON t1 FROM u1 RESTRICT;

ERR-2B000(16235): dependent privilege descriptors still exist

gSQL> REVOKE SELECT ON t1 FROM u1 CASCADE;

Revoke succeeded.

Compatibility

The SQL standard does not define the following privileges.

<revoke behavior> of the SQL standard has the following differences.

SQL standard compatibility

Feature ID

Description

Compatibility

T311

Basic roles

X

F034

Extended REVOKE statement

X

S081

Subtables

X

For More Information

Refer to the followings.

ROLLBACK

Function

It rolls back a transaction, or the operation after the savepoint.

Syntax

<rollback statement> ::=
    ROLLBACK [ WORK ] [ <rollback force clause> | <savepoint clause> ]
    ;

<rollback force clause> ::=
    FORCE 'xid_string' [ COMMENT 'comment_string' ]

<savepoint clause> ::=
    TO SAVEPOINT savepoint_name

Syntax Rules and Parameters

WORK

It is a reserved word which does not affect the operation.

<rollback force clause>

It is used to manually rollback the distributed transaction.

<savepoint clause>

It specifies the rollback scope of the current transaction.

Description

ROLLBACK statement undoes the following statements performed in the transaction.

Exceptionally, the following statements of DDL which deals with OS resources or alters the DATA TYPE can not be rolled back, but are automatically committed when executing the statement.

Examples

The following is an example of rolling back the INSERT statement.

gSQL> INSERT INTO t1 VALUES ( 1, 'anonymous' );

1 row created.

gSQL> SELECT * FROM t1;

ID DATA     
-- ---------
 1 anonymous

1 row selected.

gSQL> ROLLBACK;

Rollback complete.

gSQL> SELECT * FROM t1;

no rows selected.

The following is an example of ROLLBACK after performing the DROP TABLE statement.

gSQL> DROP TABLE t1;

Table dropped.

gSQL> SELECT * FROM t1;

ERR-42000(16040): table or view does not exist : 
SELECT * FROM t1
              *
ERROR at line 1:

gSQL> ROLLBACK;

Rollback complete.

gSQL> SELECT * FROM t1;

ID DATA     
-- ---------
 1 anonymous

1 row selected.

Compatibility

SQL standard compatibility

Feature ID

Description

Compatibility

T271

Savepoints

O

T261

Chained transactions

X

For More Information

Refer to the followings.

SAVEPOINT savepoint_specifier

Function

It defines a savepoint.

Syntax

<savepoint statement> ::=
    SAVEPOINT savepoint_name 
    ;

Syntax Rules and Parameters

savepoint_name

It is a name of the savepoint.
If the savepoint name is as same as the existing savepoint name, then the existing savepoint is deleted.
The length of the savepoint name should be shorter than 128 bytes.

Description

The defined savepoint is used by ROLLBACK TO SAVEPOINT statement (refer to ROLLBACK.), and DML or DDL statement which has been performed up to the savepoint is rolled back. Then the locks acquired by using that statement are released, too.

The defined savepoint is automatically deleted when the transaction is committed or rolled back, or it can be explicitly deleted by using RELEASE SAVEPOINT savepoint_specifier.

Example

The following is an example of defining the savepoint and using ROLLBACK TO SAVEPOINT statement.

gSQL> SAVEPOINT sp1;

Savepoint created.

gSQL> INSERT INTO t1 VALUES ( 1, 'anonymous' );

1 row created.

gSQL> SAVEPOINT sp2;

Savepoint created.

gSQL> INSERT INTO t1 VALUES ( 2, 'someone' );

1 row created.

gSQL> SAVEPOINT sp3;

Savepoint created.

gSQL> INSERT INTO t1 VALUES ( 3, 'anyone' );

1 row created.

gSQL> SELECT * FROM t1;

ID DATA     
-- ---------
 1 anonymous
 2 someone  
 3 anyone   

3 rows selected.

gSQL> ROLLBACK TO SAVEPOINT sp3;

Rollback complete.

gSQL> SELECT * FROM t1;

ID DATA     
-- ---------
 1 anonymous
 2 someone  

2 rows selected.

gSQL> ROLLBACK TO SAVEPOINT sp2;

Rollback complete.

gSQL> SELECT * FROM t1;

ID DATA     
-- ---------
 1 anonymous

1 row selected.

gSQL> ROLLBACK TO SAVEPOINT sp1;

Rollback complete.

gSQL> SELECT * FROM t1;

no rows selected.

Compatibility

SQL standard compatibility

Feature ID

Description

Compatibility

T271

Savepoints

O

For More Information

Refer to the followings.

SELECT

query expression

Function

It retrieves desired rows from one or more tables or views.

Syntax

<query expression> ::=
    <query expression body> [ <order by clause> ] [ <offset limit clause> ]

<query expression body> ::=
      <query term>
    | <set operator>

<query term> ::=
      <query specification>
    | <left paren> <query expression body> [ <order by clause> ] [ <offset limit clause> ] <right paren>

Invocation and Access Rules

One of the following privileges for all tables used in the statement is required for a user to perform <query expression>.

Syntax Rules and Parameters

<set operator>

It performs a set operation among the subqueries.
For more information, refer to set operator.

<query specification>

It specifies a single subquery. 
For more information, refer to <query specification>.

<order by clause>

It specifies sorting information of a query result. 
For more information, refer to order by clause.

<offset limit clause>

It specifies the number of rows to skip and the number of rows to fetch from the query result set. 
For more information, refer to offset limit clause.

Description

It specifies a query with SELECT statement. 
<order by clause>, <offset limit clause> can be omitted.
Two or more subqueries can be specified by using <set operator>.

Examples

The following is an example of SELECT statement.

gSQL> SELECT s_name, s_nation FROM supplier;

S_NAME                    S_NATION     
------------------------- -------------
Supplier#1                FRANCE       
Supplier#2                KOREA        
Supplier#3                GERMANY      
Supplier#4                UNITED STATES
Supplier#5                CANADA       

5 rows selected.

The following is an example of the SELECT statement which uses <order by clause>.

gSQL> SELECT s_name, s_nation FROM supplier ORDER BY s_name DESC;

S_NAME                    S_NATION
------------------------- -------------
Supplier#5                CANADA
Supplier#4                UNITED STATES
Supplier#3                GERMANY
Supplier#2                KOREA
Supplier#1                FRANCE

5 rows selected.

The following is an example of the SELECT statement which uses <offset limit clause>.

gSQL> SELECT s_name, s_nation FROM supplier OFFSET 1;

S_NAME                    S_NATION
------------------------- -------------
Supplier#2                KOREA
Supplier#3                GERMANY
Supplier#4                UNITED STATES
Supplier#5                CANADA

4 rows selected.

gSQL> SELECT s_name, s_nation FROM supplier LIMIT 1; 

S_NAME                    S_NATION
------------------------- --------
Supplier#1                FRANCE  

1 row selected.

The following is an example of the SELECT statement which uses <order by clause> and <offset limit clause>.

gSQL> SELECT s_name, s_nation FROM supplier ORDER BY s_name DESC OFFSET 3 LIMIT 1; 

S_NAME                    S_NATION
------------------------- --------
Supplier#2                KOREA   

1 row selected.

Compatibility

SQL standard compatibility

Feature ID

Description

Compatibility

T121

WITH(excluding RECURSIVE) in query expression

X

T122

WITH(excluding RECURSIVE) in subquery

X

T131

Recursive query

X

T132

Recursive query in subquery

X

F661

Simple tables

O

F302

INTERSECT table operator

O

F301

CORRESPONDING in query expressions

X

T551

Optional key words for default syntax

O

F304

EXCEPT ALL table operator

O

F850

Top-level <order by clause> in <query expression>

X

F851

<order by clause> in subqueries

O

F855

Nested <order by clause> in <query expression>

O

F856

Nested <fetch first clause> in <query expression>

X

F857

Top-level <fetch first clause> in <query expression>

X

F858

<fetch first clause> in subqueries

X

F860

dynamic <fetch first row count> in <fetch first clause>

X

F861

Top-level <result offset clause> in <query expression>

O

F862

<result offset clause> in subqueries

O

F863

Nested <result offset clause> in <query expression>

O

F865

dynamic <offset row count> in <result offset clause>

X

F866

FETCH FIRST clause: PERCENT option

X

F867

FETCH FIRST clause: WITH TIES option

X

query specification

Function

It specifies the table which is derived from the result of <table expression>.

Syntax

<query specification> ::=
    SELECT [ <hint clause> ] [ <set quantifier> ] <select list> <table expression>

<set quantifier> ::=
      ALL
    | DISTINCT

<table expression> ::=
      <from clause> [ <where clause> ] [ <group by clause> ] [ <having clause> ]

Invocation and Access Rules

The user should satisfy one of the following conditions to perform <query specification>.

Syntax Rules and Parameters

<hint clause>

It specifies the hint for query execution. 
For more information, refer to SQL Hint.

<set quantifier>

It specifies whether to remove a duplicate of the query result. 
If it is omitted, it operates in the same way as ALL.

<select list>

It specifies the column to be retrieved among query results. 
For more information, refer to select list.

<from clause>

It specifies the tables to be retrieved.
For more information, refer to from clause.

<where clause>

It specifies conditions for retrieving.
For more information, refer to where clause.

<group by clause>

It specifies grouping of the query result. 
For more information, refer to group by clause.

<having clause>

It specifies conditions for the grouping result.
For more information, refer to having clause.

Description

<hint clause>

<hint clause> is a comment which the user uses to directly command an optimizer how to execute SQL statement.

The optimizer of GOLDILOCKS preferentially applies <hint clause> specified by a user. 
If it is not applicable, the optimizer selects the best execution plan through the cost calculation.

Even when a syntactic error occurs in <hint clause>, GOLDILOCKS is set to ignore and perform it by default. Set HINT_ERROR property to on, then execute the query to check if a syntactic error exist in <hint clause>.

<set quantifier>

<set quantifier> sets whether to remove duplicates from the result set  consisting of the <select list> expressions.

<select list>

It specifies columns to be retrieved from the query result. 
They are listed by separating by a comma (,). 
An asterisk (*) is used to specify all columns in <from clause>.

<from clause>

<from clause> specifies the tables or views to be retrieved.

<where clause>

<where clause> specifies the conditions to get only the desired results from the result obtained from <from clause>.

<group by clause>

<group by clause> specifies the method of grouping the result set to which <where clause> was applied.
When <group by clause> is specified, the following expressions can be used in <select list>.

<having clause>

<having clause> specifies the retrieving condition for the grouped result set.
It is generally used together with <group by clause>.

Examples

The following is an example of SELECT statement which uses <hint clause>.

gSQL> SELECT /*+ INDEX_DESC(supplier, supplier_pk_index) */ s_name, s_nation FROM supplier;

S_NAME                    S_NATION
------------------------- -------------
Supplier#5                CANADA
Supplier#4                UNITED STATES
Supplier#3                GERMANY
Supplier#2                KOREA
Supplier#1                FRANCE

5 rows selected.

The following is an example of SELECT statement which uses <set quantifier>.

gSQL> SELECT ALL p_type FROM part;

P_TYPE
------
COPPER
NICKEL
STEEL
NICKEL
STEEL

5 rows selected.

gSQL> SELECT DISTINCT p_type FROM part;

P_TYPE
------
COPPER
STEEL
NICKEL

3 rows selected.

The following is an example of SELECT statement which uses <where clause>.

gSQL> SELECT p_name, p_brand, p_type, p_size FROM part where p_size < 10;

P_NAME P_BRAND    P_TYPE P_SIZE
------ ---------- ------ ------
Part#1 Brand#1    COPPER      7
Part#2 Brand#1    NICKEL      1

2 rows selected.

The following is an example of SELECT statement which uses <group by clause>.

gSQL> SELECT ps_partkey, SUM(ps_availqty) FROM partsupp GROUP BY ps_partkey;

PS_PARTKEY SUM(PS_AVAILQTY)
---------- ----------------
         1            11401
         2             8025
         3            13864
         4            11564
         5             8744

5 rows selected.

The following is an example of SELECT statement which uses <having clause>.

gSQL> SELECT ps_partkey, SUM(ps_availqty) FROM partsupp GROUP BY ps_partkey having SUM(ps_availqty) > 10000;

PS_PARTKEY SUM(PS_AVAILQTY)
---------- ----------------
         1            11401
         3            13864
         4            11564

3 rows selected.

Compatibility

SQL standard compatibility

Feature ID

Description

Compatibility

F801

Full set function

X

T051

Row types

X

T301

Functional dependencies

X

T325

Qualified SQL parameter references

X

T053

Explicit aliases for all-fields reference

O

T285

Enhanced derived column names

O

For More Information

Refer to query expression.

select list

Function

It specifies the columns to be retrieved from the query result.

Syntax

<select list> ::=
      <asterisk>
    | <select sublist> [ { <comma> <select sublist> } ... ]

<select sublist> ::=
      <derived column>
    | <qualified asterisk>

<qualified asterisk> ::=
      <asterisked identifier chain> <period> <asterisk>

<asterisked identifier chain> ::=
    <asterisked identifier> [ { <period> <asterisked identifier> } ... ]

<derived column> ::=
    <value expression> [ <as clause> ]

<as clause> ::=
    [ AS ] <column name>

Invocation and Access Rules

If columns or subqueries exist in <select list> statement, the user should satisfy the followings.

Syntax Rules and Parameters

<select list>

It has <asterisk> or <select sublist>.

<asterisk>

<select sublist>

Description

<select list>

<select list> specifies the columns to be included in the result set.

<asterisk>

<asterisk> sets all columns in <from clause> as a select list.

<select sublist>

<select sublist> has <derived column> or <qualified asterisk>.

If two or more <select sublist> are specified, each <select sublist> should be separated by a comma (',').

Names to Be Set in select list

Examples

The following is an example of SELECT statement which uses <asterisk>.

gSQL> SELECT * FROM supplier;

S_SUPPKEY S_NAME                    S_NATION      S_PHONE
--------- ------------------------- ------------- ---------------
        1 Supplier#1                FRANCE        27-918-335-1736
        2 Supplier#2                KOREA         15-679-861-2259
        3 Supplier#3                GERMANY       11-383-516-1199
        4 Supplier#4                UNITED STATES 25-843-787-7479
        5 Supplier#5                CANADA        21-151-690-3663

5 rows selected.

The following is an example of SELECT statement which uses <select sublist>.

gSQL> SELECT revenue.* FROM revenue;

SUPPLIER_NO TOTAL_REVENUE
----------- -------------
          1      11978.64
          2       20321.5
          3      41844.68

3 rows selected.

gSQL> SELECT supplier_no suppno, total_revenue AS TOTAL FROM revenue;

SUPPNO    TOTAL
------ --------
     1 11978.64
     2  20321.5
     3 41844.68

3 rows selected.

gSQL> SELECT 1, revenue.*, CAST( total_revenue AS NATIVE_INTEGER ) TOTAL FROM revenue;

1 SUPPLIER_NO TOTAL_REVENUE TOTAL
- ----------- ------------- -----
1           1      11978.64 11979
1           2       20321.5 20322
1           3      41844.68 41845

3 rows selected.

For More Information

Refer to query specification.

from clause

Function

It specifies the table which is derived from one or more tables.

Syntax

<from clause> ::=
    FROM <table reference list>

<table reference list> ::=
    <table reference> [ { , <table reference> } ... ]

<table reference> ::=
      <table factor>
    | <joined table>

<table factor> ::=
    <table primary>

<table primary> ::=
      <table name> [ <cluster domain> ] [ [ AS ] <correlation name> ]
    | <derived table> [ <cluster domain> ] [ [ AS ] <correlation name> [ <left paren> <derived column list> <right paren> ] ]
    | <parenthesized joined table>

<derived table> ::=
    <table subquery>

<parenthesized joined table> ::=
      <left paren> <parenthesized joined table> <right paren>
    | <left paren> <joined table> <right paren>

<derived column list> ::=
    <column name list>

<cluster domain> ::=
    @ <cluster domain name>

<cluster domain name> ::=
      GLOBAL
    | LOCAL
    | LOCAL_OFFLINE
    | <identifier>

Invocation and Access Rules

The access privilege for the table or view specified in <table reference list> is required.

Syntax Rules and Parameters

<table reference list>

<table primary>

SELECT col1, col2 
FROM ( SELECT i1, i2 FROM t1 ) AS a( col1, col2 ) 
WHERE col1 = 1 AND col2 = 1;

<correlation name>

<derived column list>

The same <column name> should not exist two or more in <derived column list>.

<cluster domain>

<cluster domain name>

Only a cluster group name or a cluster member name can be <identifier> of <cluster domain name>.

Description

<table reference list>

Two or more tables can be specified in <table reference list> by using a comma (,).

<table reference>

A single table, or view, table subquery, joined table can be <table reference>. Others except for the joined table can have a correlation name.
For more information about joined table, refer to joined table.

<table primary>

The tables, views, table subqueries and <parenthesized joined table> can be <table primary>.

The table, view, table subquery can have a correlation name, and AS can be omitted. If the correlation name is specified, it should be used in everywhere referring to the table, view, table subquery such as <select list>, <where clause>.

The table subquery can specify <derived column list>. The name specified in <derived column list> should be used in everywhere referring to table subquery column as like correlation name. To use <derived column list> in the table subquery, the correlation name should be specified.

<parenthesized joined table> specifies the logical join order for the table participating in the join operation. At this time, if all join operations for the tables enclosed with parentheses are cross join, inner join, the join order can be changed by an optimizer.

<cluster domain>

When <cluster domain> is omitted, it means the same as using GLOBAL as <cluster domain name>.
For more information, refer to Cluster Domain.

<cluster domain name>

The reserved words defined in <cluster domain name> mean as follows.

If <identifier> is specified in <cluster domain name>, a cluster group or a cluster member with the corresponding name is selected as Cluster Domain.

Examples

The following is an example of SELECT statement to query a single table by using <table name>.

gSQL> SELECT c_name, c_nation FROM customer;

C_NAME     C_NATION
---------- -------------
Customer#1 KOREA
Customer#2 CANADA
Customer#3 KOREA
Customer#4 GERMANY
Customer#5 UNITED STATES

5 rows selected.

The following is an example of SELECT statement which uses <derived table>.

gSQL> SELECT * FROM (SELECT c_name, c_nation FROM customer);

C_NAME     C_NATION
---------- -------------
Customer#1 KOREA
Customer#2 CANADA
Customer#3 KOREA
Customer#4 GERMANY
Customer#5 UNITED STATES

5 rows selected.


gSQL> SELECT * FROM (SELECT c_name, c_nation FROM customer) AS CUST ("CUSTOMER_NAME", "CUSTOMER_NATION");

CUSTOMER_NAME CUSTOMER_NATION
------------- ---------------
Customer#1    KOREA          
Customer#2    CANADA         
Customer#3    KOREA          
Customer#4    GERMANY        
Customer#5    UNITED STATES  

5 rows selected.

The following is an example of SELECT statement for a joined table which uses parentheses.

gSQL> SELECT customer.c_name, o_totalprice FROM (customer INNER JOIN orders ON customer.c_custkey = orders.o_custkey);

C_NAME     O_TOTALPRICE
---------- ------------
Customer#1    173665.47
Customer#2     46929.18
Customer#4    193846.25
Customer#3     32151.78
Customer#5     144659.2

5 rows selected.

The following is an example of SELECT statement which uses two table separated by a comma (,).

gSQL> SELECT c_name, o_totalprice FROM customer, orders;

C_NAME     O_TOTALPRICE
---------- ------------
Customer#1    173665.47
Customer#1     46929.18
Customer#1    193846.25
Customer#1     32151.78
Customer#1     144659.2
Customer#2    173665.47
Customer#2     46929.18
Customer#2    193846.25
Customer#2     32151.78
Customer#2     144659.2
Customer#3    173665.47
Customer#3     46929.18
Customer#3    193846.25
Customer#3     32151.78
Customer#3     144659.2
Customer#4    173665.47
Customer#4     46929.18
Customer#4    193846.25
Customer#4     32151.78
Customer#4     144659.2

C_NAME     O_TOTALPRICE
---------- ------------
Customer#5    173665.47
Customer#5     46929.18
Customer#5    193846.25
Customer#5     32151.78
Customer#5     144659.2

25 rows selected.

The following is an example of SELECT statement which uses <cluster domain>.

gSQL> SELECT * FROM (SELECT c_name, c_nation FROM customer@GLOBAL);

C_NAME     C_NATION
---------- -------------
Customer#1 KOREA
Customer#2 CANADA
Customer#3 KOREA
Customer#4 GERMANY
Customer#5 UNITED STATES

5 rows selected.
gSQL> SELECT * FROM (SELECT c_name, c_nation FROM customer)@LOCAL;

C_NAME     C_NATION
---------- -------------
Customer#1 KOREA
Customer#2 CANADA

2 rows selected.
gSQL> SELECT * FROM (SELECT c_name, c_nation FROM customer@G1);

C_NAME     C_NATION
---------- -------------
Customer#1 KOREA
Customer#2 CANADA

2 rows selected.
gSQL> SELECT * FROM (SELECT c_name, c_nation FROM customer@G2N1);

C_NAME     C_NATION
---------- -------------
Customer#3 KOREA
Customer#4 GERMANY

2 rows selected.

For More Information

Refer to subquery.

joined table

Function

It specifies the table derived from a cartesian product, inner join, outer join.

Syntax

<joined table> ::=
      <cross join>
    | <qualified join>
    | <natural join>

<cross join> ::=
    <table reference> CROSS JOIN <table factor>

<qualified join> ::=
    <table reference> [ <join type> ] JOIN <table reference> <join specification>

<natural join> ::=
    <table reference> NATURAL [ <join type> ] JOIN <table factor>

<join specification> ::=
      <join condition>
    | <named columns join>

<join condition> ::=
    ON <search condition>

<named columns join> ::=
    USING ( <join column list> )

<join type> ::=
      INNER
    | { LEFT | RIGHT | FULL } [ OUTER ]

<join column list> ::=
    <column name list>

Invocation and Access Rules

The access privilege for all tables and views specified in a joined table is required.

Syntax Rules and Parameters

<cross join>

<join specification> specifying the join condition does not appear at the location of <cross join>.
A single table, <table subquery> or <parenthesized joined table> can appear on the right of <cross join>.

<qualified join>

<natural join>

<join specification>

Description

<cross join>

<cross join> returns a result which combines each left row with all right rows.
T1 ( 1, 1 ), ( 2, 2 )
T2 ( 2, 2 ), ( 3, 3 )

gSQL> SELECT * FROM t1 CROSS JOIN t2;
C1 C2 C1 C2
-- -- -- --
 1  1  2  2
 1  1  3  3
 2  2  2  2
 2  2  3  3
4 rows selected.
The explicit join condition can not be specified in <cross join>, but the join condition for the two tables can be specified in <where clause>. In this case, it performs inner join.
• SELECT * FROM t1 CROSS JOIN t2 WHERE t1.c1 = t2.c1;
• <=> SELECT * FROM t1 INNER JOIN t2 ON t1.c1 = t2.c1;
T1 ( 1, 1 ), ( 2, 2 )
T2 ( 2, 2 ), ( 3, 3 )

gSQL> SELECT * FROM t1 CROSS JOIN t2 WHERE t1.c1 = t2.c1;
C1 C2 C1 C2
-- -- -- --
 2  2  2  2
1 row selected.

<qualified join>

<qualified join> combines each left row with all right rows, then returns only the rows satisfying the join condition as a result.

If <where clause> exists in <table expression>, then conditions in <where clause> are applied to the result set of <qualified join>.

The result is same, even when inner join processes the conditions in <where clause> as join conditions. But result differs when outer join processes the conditions in <where clause> as join conditions.

INNER JOIN
t1 ( 1, 1 ), ( 2, 2 ), ( 3, 3 ), ( 4, 4 ), ( 5, 5 )
t2 ( 2, 2 ), ( 3, 3 )
gSQL> SELECT * FROM t1 INNER JOIN t2 ON t1.c1 = t2.c1 AND t1.c2 = t2.c2;
C1 C2 C1 C2
-- -- -- --
 2  2  2  2
 3  3  3  3
2 rows selected.
gSQL> SELECT * FROM t1 INNER JOIN t2 ON t1.c1 = t2.c1 WHERE t1.c2 = t2.c2;
C1 C2 C1 C2
-- -- -- --
 2  2  2  2
 3  3  3  3
2 rows selected.
( 2,  2,    2,    2 )                        ( 2,  2,    2,    2 )
  ( 3,  3,    3,    3 )                   →   ( 3,  3,    3,    3 )
OUTER JOIN
t1 ( 1, 1 ), ( 2, 2 ), ( 3, 3 ), ( 4, 4 ), ( 5, 5 )
t2 ( 2, 2 ), ( 3, 3 )
gSQL> SELECT * FROM t1 LEFT OUTER JOIN t2 ON t1.c1 = t2.c1 AND t1.c2 = t2.c2;
C1 C2   C1   C2
-- -- ---- ----
 1  1 null null
 2  2    2    2
 3  3    3    3
 4  4 null null
 5  5 null null
5 rows selected.
gSQL> SELECT * FROM t1 LEFT OUTER JOIN t2 ON t1.c1 = t2.c1 WHERE t1.c2 = t2.c2;
C1 C2 C1 C2
-- -- -- --
 2  2  2  2
 3  3  3  3
2 rows selected.
( 1,  1, null, null )
  ( 2,  2,    2,    2 )                        ( 2,  2,    2,    2 )
  ( 3,  3,    3,    3 )                   →   ( 3,  3,    3,    3 ) 
  ( 4,  4, null, null )
  ( 5,  5, null, null )

Left outer join combines right rows satisfying the join condition for the left rows, then returns the combined rows as a result. If right rows satisfying the join condition does not exist, then it returns the result whose left row values are as they are and whose right row values are filled with NULL.

LEFT OUTER JOIN
t1 ( 1, 1 ), ( 2, 2 )
t2 ( 2, 2 ), ( 3, 3 )

gSQL> SELECT * FROM t1 LEFT OUTER JOIN t2 ON t1.c1 = t2.c1;
C1 C2   C1   C2
-- -- ---- ----
 1  1 null null
 2  2    2    2
2 rows selected.

Right outer join is operated in an opposite way of left outer join.

RIGHT OUTER JOIN

t1 ( 1, 1 ), ( 2, 2 )
t2 ( 2, 2 ), ( 3, 3 )

gSQL> SELECT * FROM t1 RIGHT OUTER JOIN t2 ON t1.c1 = t2.c1;
  C1   C2 C1 C2
---- ---- -- --
   2    2  2  2
null null  3  3
2 rows selected.

Full outer join returns the left rows filled with NULL for all right rows which do not satisfy the join condition together with left outer join results.

FULL OUTER JOIN

t1 ( 1, 1 ), ( 2, 2 )
t2 ( 2, 2 ), ( 3, 3 )

gSQL> SELECT * FROM t1 FULL OUTER JOIN t2 ON t1.c1 = t2.c1;
  C1   C2   C1   C2
---- ---- ---- ----
   1    1 null null
   2    2    2    2
null null    3    3
3 rows selected.

<natural join>

<natural join> joins all columns with same names in two tables participating in join as equal. In other words, it is as same as specifying all columns with same names of two tables participating in join in USING clause of inner join.

t1 ( C1 INTEGER, C2 INTEGER )
t2 ( C1 INTEGER, C3 INTEGER )

t1 ( 1, 10 ), ( 2, 20 ), ( 3, 30 )
t2 ( 1, 100 ), ( 2, 200 ), ( 3, 300 )

gSQL> SELECT * FROM t1 NATURAL JOIN t2; 
C1 C2  C3
-- -- ---
 1 10 100
 2 20 200
 3 30 300
3 rows selected.

gSQL> SELECT * FROM t1 INNER JOIN t2 USING ( c1 );
C1 C2  C3
-- -- ---
 1 10 100
 2 20 200
 3 30 300
3 rows selected.

<join specification>

It specifies the join condition.
<join condition> specifies the condition for joining left rows and right rows of a join statement.
<named columns join> specifies the join condition by listing that <column name>, if the same <column name> exist in left rows and right rows.
t1 ( C1 INTEGER, C2 INTEGER )
t2 ( C1 INTEGER, C3 INTEGER )

t1 ( 1, 10 ), ( 2, 20 ), ( 3, 30 )
t2 ( 1, 100 ), ( 2, 200 ), ( 3, 300 )

• <join condition>
gSQL> SELECT * FROM t1 INNER JOIN t2 ON t1.c1 = t2.c1;
C1 C2 C1  C3
-- -- -- ---
 1 10  1 100
 2 20  2 200
 3 30  3 300
3 rows selected.

• <named columns join>
gSQL> SELECT * FROM t1 INNER JOIN t2 USING ( c1 );
C1 C2  C3
-- -- ---
 1 10 100
 2 20 200
 3 30 300
3 rows selected.

Examples

The following is an example of SELECT statement which uses <cross join>.

gSQL> SELECT c_name, o_totalprice FROM customer CROSS JOIN orders;

C_NAME     O_TOTALPRICE
---------- ------------
Customer#1    173665.47
Customer#1     46929.18
Customer#1    193846.25
Customer#1     32151.78
Customer#1     144659.2
Customer#2    173665.47
Customer#2     46929.18
Customer#2    193846.25
Customer#2     32151.78
Customer#2     144659.2
Customer#3    173665.47
Customer#3     46929.18
Customer#3    193846.25
Customer#3     32151.78
Customer#3     144659.2
Customer#4    173665.47
Customer#4     46929.18
Customer#4    193846.25
Customer#4     32151.78
Customer#4     144659.2

C_NAME     O_TOTALPRICE
---------- ------------
Customer#5    173665.47
Customer#5     46929.18
Customer#5    193846.25
Customer#5     32151.78
Customer#5     144659.2

25 rows selected.

The following is an example of SELECT statement which uses inner join.

gSQL> SELECT c_name, o_totalprice FROM customer INNER JOIN orders ON c_custkey = o_custkey;

C_NAME     O_TOTALPRICE
---------- ------------
Customer#1    173665.47
Customer#2     46929.18
Customer#4    193846.25
Customer#3     32151.78
Customer#5     144659.2

5 rows selected.

The following is an example of SELECT statement which uses outer join.

gSQL> SELECT c_name, o_totalprice FROM customer LEFT OUTER JOIN orders ON c_custkey = o_custkey AND o_orderdate < '1996-01-01';

C_NAME     O_TOTALPRICE
---------- ------------
Customer#1         null
Customer#2         null
Customer#3     32151.78
Customer#4    193846.25
Customer#5     144659.2

5 rows selected.

gSQL> SELECT c_name, o_totalprice FROM customer RIGHT OUTER JOIN orders ON c_custkey = o_custkey AND c_nation = 'KOREA';

C_NAME     O_TOTALPRICE
---------- ------------
Customer#1    173665.47
null           46929.18
null          193846.25
Customer#3     32151.78
null           144659.2

5 rows selected.

gSQL> SELECT c_name, o_totalprice FROM customer FULL OUTER JOIN orders ON c_custkey = o_custkey AND c_nation = 'KOREA' AND o_orderdate < '1996-01-01';

C_NAME     O_TOTALPRICE
---------- ------------
Customer#1         null
Customer#2         null
Customer#3     32151.78
Customer#4         null
Customer#5         null
null          173665.47
null           46929.18
null          193846.25
null           144659.2

9 rows selected.

The following is an example of SELECT statement which uses natural join.

gSQL> SELECT c_name, o_totalprice FROM (SELECT c_custkey custkey, c_name FROM customer) NATURAL JOIN (SELECT o_custkey custkey, o_totalprice FROM orders);

C_NAME     O_TOTALPRICE
---------- ------------
Customer#1    173665.47
Customer#2     46929.18
Customer#4    193846.25
Customer#3     32151.78
Customer#5     144659.2

5 rows selected.

Compatibility

SQL standard compatibility

Feature ID

Description

Compatibility

F401

Extended joined table

O

F402

Named column joins for LOBs, arrays, and multisets

X

F403

Partitioned join tables

X

For More Information

Refer to from clause.

where clause

Function

It applies <search condition> to the result of <from clause>.

Syntax

<where clause> ::=
    WHERE <search condition>

Syntax Rules and Parameters

<where clause>

<search condition> which returns a boolean type is required after WHERE keyword.

Description

For more information about <where clause>, refer to Conditions.

Example

The following is an example of SELECT statement which uses <where clause>.

gSQL> SELECT s_name, s_nation FROM supplier WHERE s_nation = 'KOREA';

S_NAME                    S_NATION
------------------------- --------
Supplier#2                KOREA

1 row selected.

gSQL> SELECT s_name, ps_availqty, ps_supplycost FROM supplier, partsupp WHERE s_nation = 'KOREA' AND s_suppkey = ps_suppkey;

S_NAME                    PS_AVAILQTY PS_SUPPLYCOST
------------------------- ----------- -------------
Supplier#2                       8076        993.49
Supplier#2                       4069        357.84

2 rows selected.

Compatibility

SQL standard compatibility

Feature ID

Description

Compatibility

F441

Extended set function support

O

For More Information

Refer to query specification.

group by clause

Function

It specifies the grouped table of which <group by clause> was applied to the result processed by the previous statements.

Syntax

<group by clause> ::=
    GROUP BY <grouping element list>

<grouping element list> ::=
    <grouping element> [ { , <grouping element> } ... ]

<grouping element> ::=
      <ordinary grouping set>
    | <empty grouping set>

<ordinary grouping set> ::=
      <grouping column reference>

<grouping column reference> ::=
    <column reference>
    | <value_expression>

<empty grouping set> ::=
    <left paren> <right paren>

Invocation and Access Rules

Any separate access privilege is not required for a user to perform <group by clause>.

Syntax Rules and Parameters

<ordinary grouping set>

It consists of one or more <grouping column reference>.
It does not support LONG type (LONG VARCHAR, LONG VARBINARY).

• SELECT c1, sum(c2) FROM t1 GROUP BY c1;
• SELECT sum(c1) FROM t1 GROUP BY NULL;

<empty grouping set>

It can be specified by using only parentheses.

• SELECT sum(c1) FROM t1 GROUP BY ();

Description

<grouping element list>

It groups <grouping element list> specified in <group by clause> into a GROUPING SET. If all values of <grouping element> in GROUPING SET are matched, it is processed as the same group.

<grouping column reference>

<column reference> or <value expression> can appear in <grouping column reference>.

<empty grouping set>

All records in <empty grouping set> are configured into a single group.
• SELECT sum(c1), sum(c2) FROM t1 GROUP BY ();

Example

The following is an example of SELECT statement which uses GROUP BY clause.

gSQL> SELECT c_nation, COUNT(c_name) FROM customer GROUP BY c_nation;

C_NATION      COUNT(C_NAME)
------------- -------------
UNITED STATES             1
CANADA                    1
KOREA                     2
GERMANY                   1

4 rows selected.

gSQL> SELECT COUNT(c_name) FROM customer GROUP BY NULL;

COUNT(C_NAME)
-------------
            5

1 row selected.

gSQL> SELECT COUNT(c_name) FROM customer GROUP BY ();

COUNT(C_NAME)
-------------
            5

1 row selected.

Compatibility

SQL standard compatibility

Feature ID

Description

Compatibility

T431

Extended grouping capabilities

X

T432

Nested and concatenated GROUPING SETS

X

T434

GROUP BY DISTINCT

X

For More Information

Refer to the followings.

having clause

Function

It specifies grouped tables having removed groups which do not satisfy <search condition>.

Syntax

<having clause> ::=
    HAVING <search condition>

Invocation and Access Rules

Any separate access privilege is not required for a user to perform <having clause>.

Syntax Rules and Parameters

<having clause>

Description

<having clause>

<having clause> specifies search conditions for the grouped data.

Generally, it is used together with <group by clause>. When <having clause> is used without <group by clause>, it is considered as if <empty grouping set> exists.

<grouping column reference> specified in <group by clause> can be specified in <having clause>. 
The columns which are not specified in <group by clause> can be specified by using aggregate functions.

Example

The following is an example of SELECT statement which uses <having clause>.

gSQL> SELECT c_nation, COUNT(c_name) FROM customer GROUP BY c_nation HAVING COUNT(c_name) > 1;

C_NATION COUNT(C_NAME)
-------- -------------
KOREA                2

1 row selected.

gSQL> SELECT COUNT(c_name) FROM customer HAVING COUNT(c_name) > 1;

COUNT(C_NAME)
-------------
            5

1 row selected.

Compatibility

SQL standard compatibility

Feature ID

Description

Compatibility

T301

Functional dependencies

O

For More Information

Refer to the followings.

order by clause

Function

It specifies the sorting order of the query results.

Syntax

<order by clause> ::=
    ORDER BY <sort specification list>

<sort specification list> ::=
    <sort specification> [ { <comma> <sort specification> }... ]

<sort specification> ::=
    <sort key> [ <ordering specification> ] [ <null ordering> ]

<sort key> ::=
    <value expression>

<ordering specification> ::=
      ASC
    | DESC

<null ordering> ::=
      NULLS FIRST
    | NULLS LAST

Invocation and Access Rules

The access privilege for a column is required if the column exist in a sort key specified for sorting.

Syntax Rules and Parameters

<order by clause>

<sort specification list>

<sort key>

Description

<order by clause>

<order by clause> specifies a method to sort the query results.

<sort key> can be listed in <order by clause> by using a comma (,), and <sort key> of each records are compared and listed in order.

SELECT c1, c2 FROM t1 ORDER BY c1, c2;

<ordering specification> which specifies an ascending order or an descending order can be specified in <sort key>. If it is omitted, then they are sorted in an ascending order.

gSQL> SELECT c1 FROM t1;
C1
--
 2
 3
 1
3 rows selected.
gSQL> SELECT c1 FROM t1 ORDER BY c1;
C1
--
 1
 2
 3
3 rows selected.

gSQL> SELECT c1 FROM t1 ORDER BY c1 ASC;
C1
--
 1
 2
 3
3 rows selected.
gSQL> SELECT c1 FROM t1 ORDER BY c1 DESC;
C1
--
 3
 2
 1
3 rows selected.
<null ordering> specifies an order between the non-NULL values and NULL values in <sort key>. If it is omitted, then they are sorted as NULLS LAST.
gSQL> SELECT c1 FROM t1;
  C1
----
   2
null
   1
3 rows selected.
gSQL> SELECT c1 FROM t1 ORDER BY c1;    
  C1
----
   1
   2
null
3 rows selected.

gSQL> SELECT c1 FROM t1 ORDER BY c1 NULLS LAST;
  C1
----
   1
   2
null
3 rows selected.
gSQL> SELECT c1 FROM t1 ORDER BY c1 NULLS FIRST;
  C1
----
null
   1
   2
3 rows selected.

If a constant value is specified in <sort key>, the expression positioned in the location corresponding to the order of the corresponding value in <select list> is regarded as <sort key>. In this case, the constant is an integer bigger than 0, and it should be equal or smaller than the total number of expression in <select list>.

gSQL> SELECT c1 FROM t1 ORDER BY 1;
  C1
----
   1
   2
null
3 rows selected.

LONG (LONG VARCHAR, LONG VARBINARY) type can not be specified in <sort key>.

Comparison of Null Value

Sorting Rows Which Have Same Sort Key Value

Peers are rows which can not be distinguished by a sort key, and the peers are sorted according to the scan order.

<aggregation function> Which Is Used As <sort key>

If <aggregation function> is used in <query specification>, or <group by clause> is specified, <aggregation function> can be used as <sort key>.
However, the nested aggregation function can be used as <sort key> only when <group by clause> is specified.
gSQL> SELECT c1, c2 FROM t1;
C1 C2
-- --
 2  1
 3  5
 1  2
 2 10
 3 10
5 rows selected.

gSQL> SELECT sum(c1) FROM t1 ORDER BY sum(c1);
SUM(C1)
-------
     11
1 row selected.

gSQL> SELECT c1, sum(c2) FROM t1 GROUP BY c1 ORDER BY sum(c2);
C1 SUM(C2)
-- -------
 1       2
 2      11
 3      15
3 rows selected.

gSQL> SELECT sum(c1) FROM t1 GROUP BY c1 ORDER BY sum(sum(c1));
SUM(C1)
-------
      6
1 row selected.

Example

The following is an example of SELECT statement which uses ORDER BY clause.

gSQL> SELECT c_name, c_nation FROM customer ORDER BY c_nation;

C_NAME     C_NATION
---------- -------------
Customer#2 CANADA
Customer#4 GERMANY
Customer#1 KOREA
Customer#3 KOREA
Customer#5 UNITED STATES

5 rows selected.

gSQL> SELECT c_name, c_nation FROM customer ORDER BY c_nation DESC;

C_NAME     C_NATION
---------- -------------
Customer#5 UNITED STATES
Customer#1 KOREA
Customer#3 KOREA
Customer#4 GERMANY
Customer#2 CANADA

5 rows selected.

gSQL> SELECT c_name, c_nation FROM customer ORDER BY 2 DESC;

C_NAME     C_NATION     
---------- -------------
Customer#5 UNITED STATES
Customer#1 KOREA        
Customer#3 KOREA        
Customer#4 GERMANY      
Customer#2 CANADA       

5 rows selected.

Compatibility

SQL standard compatibility

Feature ID

Description

Compatibility

F850

Top-level <order by clause> in <query expression>

X

F851

<order by clause> in subqueries

O

F852

Top-level <order by clause> in views

O

F855

Nested <order by clause> in <query expression>

O

For More Information

Refer to query expression.

offset limit clause

Function

It specifies the number of rows to skip and the number of rows to fetch from the query results.

Syntax

<offset limit clause> ::=
      <result offset clause>
    | <fetch limit clause>
    | <result offset clause> <fetch limit clause>

<result offset clause> ::=
    OFFSET <offset row count> [ { ROW | ROWS } ]

<fetch limit clause> ::=
      <fetch first clause>
    | <limit clause>

<fetch first clause> ::=
    FETCH [ FIRST | NEXT ] [ <fetch row count> ] [ ROW ONLY | ROWS ONLY ]

<limit clause> ::=
    LIMIT { <fetch row count> | <offset row count> , <fetch row count> | ALL }

Invocation and Access Rules

The access privilege for <offset limit clause> is not required.

Syntax Rules and Parameters

<result offset clause>

<fetch limit clause>

<fetch first clause>

<limit clause>

Description

<result offset clause>

It fetches rows from the <offset row count>th of the query results. If the result which <offset row count> queried is equal to or greater than the number of rows, the number of fetch rows is 0.

gSQL> SELECT c1 FROM t1;
C1
--
 1
 2
 3
3 rows selected.

gSQL> SELECT c1 FROM t1 OFFSET 1;
C1
--
 2
 3
2 rows selected.

gSQL> SELECT c1 FROM t1 OFFSET 3;
no rows selected.

<fetch first clause>

It fetches the query results as many as the number of <fetch row count>.

gSQL> SELECT c1 FROM t1;
C1
--
 1
 2
 3
3 rows selected.

gSQL> SELECT c1 FROM t1 FETCH FIRST 2 ROWS ONLY;
C1
--
 1
 2
2 rows selected.

<limit clause>

When LIMIT <fetch_row_count> is used, it fetches the query results as many as the number of <fetch row count>.

When LIMIT <offset row count> is used, <fetch row count>, it fetches the query results as many as the number of <fetch row count> from the <offset row count>th row.

When LIMIT ALL is used, it returns the query results to a user without limit of the number.

gSQL> SELECT c1 FROM t1;
C1
--
 1
 2
 3
3 rows selected.

• LIMIT <fetch_row_count>
gSQL> SELECT c1 FROM t1 LIMIT 2;
C1
--
 1
 2
2 rows selected.

• LIMIT <offset row count>, <fetch_row_count>
gSQL> SELECT c1 FROM t1 LIMIT 1, 1;
C1
--
 2
1 row selected.

• LIMIT ALL
gSQL> SELECT c1 FROM t1 LIMIT ALL;
C1
--
 1
 2
 3
3 rows selected.

Examples

The following is an example of SELECT statement which uses <result offset clause>.

gSQL> SELECT c_name, c_nation FROM customer OFFSET 1;

C_NAME     C_NATION
---------- -------------
Customer#2 CANADA
Customer#3 KOREA
Customer#4 GERMANY
Customer#5 UNITED STATES

4 rows selected.

The following is an example of SELECT statement which uses <fetch first clause>.

gSQL> SELECT c_name, c_nation FROM customer FETCH FIRST ROW ONLY;

C_NAME     C_NATION
---------- --------
Customer#1 KOREA

1 row selected.

gSQL> SELECT c_name, c_nation FROM customer FETCH FIRST 2 ROW ONLY;

C_NAME     C_NATION
---------- --------
Customer#1 KOREA
Customer#2 CANADA

2 rows selected.

The following is an example of SELECT statement which uses <limit clause>.

gSQL> SELECT c_name, c_nation FROM customer LIMIT 1;

C_NAME     C_NATION
---------- --------
Customer#1 KOREA

1 row selected.

gSQL> SELECT c_name, c_nation FROM customer LIMIT 1, 2;

C_NAME     C_NATION
---------- --------
Customer#2 CANADA
Customer#3 KOREA

2 rows selected.

gSQL> SELECT c_name, c_nation FROM customer LIMIT ALL;

C_NAME     C_NATION
---------- -------------
Customer#1 KOREA
Customer#2 CANADA
Customer#3 KOREA
Customer#4 GERMANY
Customer#5 UNITED STATES

5 rows selected.

The following is an example of SELECT statement which uses <result offset clause> and <fetch limit clause>.

gSQL> SELECT c_name, c_nation FROM customer OFFSET 1 FETCH 2;

C_NAME     C_NATION
---------- --------
Customer#2 CANADA
Customer#3 KOREA

2 rows selected.

gSQL> SELECT c_name, c_nation FROM customer OFFSET 1 LIMIT 2;

C_NAME     C_NATION
---------- --------
Customer#2 CANADA
Customer#3 KOREA

2 rows selected.

Compatibility

SQL standard compatibility

Feature ID

Description

Compatibility

F861

Top-level <result offset clause> in <query expression>

O

F862

<result offset clause> in subqueries

O

F863

Nested <result offset clause> in <query expression>

O

F864

Top-level <result offset clause> in views

O

F865

dynamic <offset row count> in <result offset clause>

X

set operator

Function

It performs a set operation for results of the subquery.

Syntax

<set operator> ::=
      <set operator term>
    | <query expression body> UNION [ ALL | DISTINCT ] <set operator term>
    | <query expression body> EXCEPT [ ALL | DISTINCT ] <set operator term>
    | <query expression body> MINUS [ ALL | DISTINCT ] <set operator term>

<set operator term> ::=
      <query term>
    | <set operator term> INTERSECT [ ALL | DISTINCT ] <set operator term>

Invocation and Access Rules

All access privileges for the <query expression> in each <set operator term> are required for using <set operator> statement.

Syntax Rules and Parameters

<set operator>

<query term>

It specifies the single subquery.
For more information, refer to query expression.

Description

The Differences between ALL and DISTINCT in <set operator>

For example, if the data of the table R1 and R2 is given as follows, the result of each <set operator > is as follows.

SET operation results

SET operation results

Operator Precedence

The operator precedence of <set operator> is as follows.

Result Type of <set operator>

The i-th column of all subqueries in <set operator> should be a data type of the same family, and its result type is determined by  Result Type Combination Rule.
However, LONG VARCHAR and LONG VARBINARY types can only use UNION ALL.

ORDER BY Clause

When <set operator> is used together with ORDER BY, and the column names are different among subqueries, then it can be used as follows.

Examples

The following is an example of SELECT statement which uses UNION operator.

gSQL> SELECT s_nation nation FROM supplier UNION ALL SELECT c_nation FROM customer;

NATION
-------------
FRANCE
KOREA
GERMANY
UNITED STATES
CANADA
KOREA
CANADA
KOREA
GERMANY
UNITED STATES

10 rows selected.

gSQL> SELECT s_nation nation FROM supplier UNION DISTINCT SELECT c_nation FROM customer;

NATION
-------------
UNITED STATES
CANADA
KOREA
GERMANY
FRANCE

5 rows selected.

The following is an example of SELECT statement which uses EXCEPT operator.

gSQL> SELECT c_nation nation FROM customer EXCEPT ALL SELECT s_nation FROM supplier;

NATION
------
KOREA

1 row selected.

gSQL> SELECT c_nation nation FROM customer EXCEPT DISTINCT SELECT s_nation FROM supplier;

no rows selected.

The following is an example of SELECT statement which uses INTERSECT operator.

gSQL> SELECT c_nation nation FROM customer INTERSECT ALL SELECT s_nation FROM supplier;

NATION
-------------
UNITED STATES
CANADA
KOREA
GERMANY

4 rows selected.

gSQL> SELECT c_nation nation FROM customer INTERSECT DISTINCT SELECT s_nation FROM supplier;

NATION
-------------
UNITED STATES
CANADA
KOREA
GERMANY

4 rows selected.

Compatibility

SQL standard compatibility

Feature ID

Description

Compatibility

F302

INTERSECT table operator

O

F301

CORRESPONDING

X

T551

Optional key words for default syntax

O

F304

EXCEPT ALL table operator

O

For More Information

Refer to query expression.

subquery

Function

It specifies the scalar value, row, table which are derived from <query expression>.

Syntax

<scalar subquery> ::=
    <subquery>

<row subquery> ::=
    <subquery>

<table subquery> ::=
    <subquery>

<subquery> ::=
    ( <query expression> )

Invocation and Access Rules

The access privilege for <query expression> in <subquery> is required.

Syntax Rules and Parameters

<scalar subquery>

<row subquery>

<table subquery>

Description

<scalar subquery>

<scalar subquery> returns one row which has one column as a result. The target of <scalar subquery> should be only one, and the result data type depends on the data type of the target.

<scalar subquery> can be used alone in the target of <select list>, and it can be used in the operator which has a single column.

<row subquery>

<row subquery> returns one row which has two or more columns as a result. The targets of <row subquery> should be two or more, and the result data type depends on the data type of each target.

<row subquery> can not be used alone in the target of <select list>, and it can only be used in the row operator which has two or more columns.

<table subquery>

<table subquery> returns one or more rows which have one or more columns as a result. The targets of <table subquery> should be one or more, and the result data type depends on the data type of each target.

<table subquery> can not be used alone in the target of <select list>, but it can be used in the operators such as IN, NOT IN, EXISTS, NOT EXISTS, quantify operator.

Examples

The following is an example of SELECT statement which uses <scalar subquery>.

gSQL> SELECT (SELECT c_name FROM dual)  FROM customer;

(SELECT C_NAME FROM DUAL)
-------------------------
Customer#1
Customer#2
Customer#3
Customer#4
Customer#5

5 rows selected.

gSQL> SELECT c_name, c_nation FROM customer WHERE c_nation = (SELECT 'CANADA' FROM dual);

C_NAME     C_NATION
---------- --------
Customer#2 CANADA

1 row selected.

The following is an example of SELECT statement which uses <row subquery>.

gSQL> SELECT p_name, p_brand, p_type FROM part WHERE (p_brand, p_type) = (SELECT 'Brand#1', 'NICKEL' FROM dual);

P_NAME P_BRAND    P_TYPE
------ ---------- ------
Part#2 Brand#1    NICKEL

1 row selected.

The following is an example of SELECT statement which uses <table subquery>.

gSQL> SELECT s_name, s_nation FROM supplier WHERE s_nation IN (SELECT c_nation FROM customer);

S_NAME                    S_NATION
------------------------- -------------
Supplier#2                KOREA
Supplier#3                GERMANY
Supplier#4                UNITED STATES
Supplier#5                CANADA

4 rows selected.

gSQL> SELECT * FROM (SELECT s_name, s_nation FROM supplier);

S_NAME                    S_NATION
------------------------- -------------
Supplier#1                FRANCE
Supplier#2                KOREA
Supplier#3                GERMANY
Supplier#4                UNITED STATES
Supplier#5                CANADA

5 rows selected.

Compatibility

SQL standard compatibility

Feature ID

Description

Compatibility

F471

Scalar subquery values

O

F641

Row and table constructors

X

T501

Enhanced EXISTS predicate

O

E061-11

Subqueries in IN predicate

O

E061-12

Subqueries in quantified comparison predicate

O

E061-12

Correlated subqueries

O

For More Information

Refer to the followings.

hint clause

It specifies a hint to be used for a query execution.
For more information, refer to SQL Hint.

SELECT .. FOR UPDATE

Function

It sets whether or not to update the result set of SELECT statement.

Syntax

<select for update statement> ::=
    <query expression>  <updatability clause>
    ;

<updatability clause> ::=
      FOR READ ONLY 
    | FOR UPDATE [ OF <column name list> ] [ <lock wait mode> ]

<lock wait mode> ::=
    | WAIT
    | WAIT second
    | NOWAIT

Invocation and Access Rules

The user should satisfy the following conditions to perform <select for update statement>.

Syntax Rules and Parameters

<query expression>

INTO clause should not exist in SELECT statement.

To use FOR UPDATE, the query should identify the row updates of the base table, or it should be an updatable query which can acquire the lock into the row.

The updatable query should satisfy all of following conditions.

For more information about SELECT statement, refer to query expression.

<updatability clause>

It specifies whether or not to update the row for the result set.

FOR UPDATE OF …

It lists the columns relating to acquiring lock when executing the query.

<lock wait mode>

It is used together with FOR UPDATE statement, and it specifies the lock acquisition method.

Description

SELECT statement keep fetching the rows regardless of whether the transaction ends. However, SELECT .. FOR UPDATE statement can not fetch the rows when the transaction ends because the statement acquires the lock for the rows.

Cursor holdability



Examples

The following is an example of acquiring a lock for the row by using FOR UPDATE statement.

gSQL> SELECT id, data FROM t1 WHERE id = 3 FOR UPDATE;

ID DATA  
-- ------
 3 data_3

1 row selected.

The following uses join and ORDER BY clause but it is an updatable query, so FOR UPDATE statement can be used.

gSQL> SELECT t1.id, t1.name, t2.addr 
        FROM t1, t2
       WHERE t1.id = t2.id
       ORDER BY 1
         FOR UPDATE;

ID NAME    ADDR         
-- ------- -------------
 1 someone somewhere    
 2 anyone  anywhere     
 3 unknown N/A          
 4 leekmo  leekmo's home
 5 mkkim   seoul        

5 rows selected.

The following is a non-updatable query, so FOR UPDATE statement can not be used.

gSQL> SELECT id, COUNT(*)
        FROM t1
       GROUP BY id
         FOR UPDATE;

ERR-42000(16112): query expression is not updatable

Compatibility

In the SQL standard, <select for update statement> is not defined, but it can be defined by using DECLARE cursor_name statement.

SELECT .. INTO

Function

It retrieves a single row by using a query, then obtains the value of retrieved row into the host variable.

Syntax

<select statement: single row> ::=
    SELECT [ <hint clause> ] [ <set quantifier> ] <select list>
        INTO <select target list>
        <table expression>
    ;

<select target list> ::=
    variable_name [, ...]

Invocation and Access Rules

One of the following privileges for all tables used in the statement is required for a user to perform <select statement: single row>.

Syntax Rules and Parameters

<hint clause>

It specifies hints for query execution.
For more information, refer to hint clause of SELECT statement.

<set quantifier>

It specifies whether to remove duplicates from the query result.
For more information, refer to query specification clause.

<select list>

It specifies the columns to be retrieved from the query result.
For more information, refer to select list clause.

INTO <select target list>

The number of the variable specified in INTO clause should be equal to the number of the expression specified in <select list>.

<table expression>

It specifies the query information such as a search condition.
For more information, refer to query specification clause.

Description

The rows to be retrieved should be one or less.
If two or more rows are retrieved, an error occurs.

Differences among SELECT-related Statements

Example

The following is an example of obtaining the value into the host variable by using interactive SQL (gsql).

gSQL> \var v_id   INTEGER
gSLQ> \var v_data VARCHAR(128)

gSQL> SELECT id, data INTO :v_id, :v_data FROM t1 WHERE id = 3;

V_ID V_DATA
---- ------
   3 data_3

1 row selected.

SELECT .. INTO .. FOR UPDATE

Function

It sets whether to update the row by retrieving a single row through the query, then obtains the value of retrieved row into the host variable.

Syntax

<select for update statement: single row> ::=
    SELECT [ <hint clause> ] [ <set quantifier> ] <select list>
        INTO <select target list>
        <table expression>  <updatability clause>
    ;

<select target list> ::=
    variable_name [, ...]

<updatability clause> ::=
      FOR READ ONLY 
    | FOR UPDATE [ OF <column name list> ] [ <lock wait mode> ]

<lock wait mode> ::=
    | WAIT
    | WAIT second
    | NOWAIT

Invocation and Access Rules

One of the following privileges for all tables used in the statement is required for a user to perform <select statement: single row>.

If FOR UPDATE clause is used, one of the following privileges for the tables to be locked is required.

Syntax Rules and Parameters

<select for update statement: single row>

To use FOR UPDATE, the query should identify the row updates of the base table, or it should be an updatable query which can acquire the lock into the row.

The updatable query should satisfy all of following conditions.

<updatability clause>

It specifies whether or not to update the row for the result set.

FOR UPDATE OF …

It lists the columns relating to acquiring lock when executing the query.

<lock wait mode>

It is used together with FOR UPDATE statement, and it specifies the lock acquisition method.

<hint clause>

It specifies hints for query execution.
For more information, refer to hint clause of SELECT statement.

<set quantifier>

It specifies whether to remove duplicates from the query result.
For more information, refer to query specification clause.

<select list>

It specifies the columns to be retrieved from the query result.
For more information, refer to select list clause.

INTO <select target list>

The number of the variable specified in INTO clause should be equal to the number of the expression specified in <select list>.

<table expression>

It specifies the query information such as a search condition.
For more information, refer to query specification clause.

Description

The rows to be retrieved should be one or less.
If two or more rows are retrieved, an error occurs.

SELECT statement keep fetching the rows regardless of whether the transaction ends. However, SELECT .. FOR UPDATE statement can not fetch the rows when the transaction ends because the statement acquires the lock for the rows.

Cursor holdability



Differences among SELECT-related Statements

Examples

The following is an example of acquiring a lock for the row by using FOR UPDATE statement, and obtaining the value into the host variable by using interactive SQL (gsql).

gSQL> \var v_id   INTEGER
gSQL> \var v_data VARCHAR(128)

gSQL> SELECT id, data INTO :v_id, :v_data FROM t1 WHERE id = 3 FOR UPDATE;

V_ID V_DATA
---- ------
   3 data_3

1 row selected.

The following uses join and ORDER BY clause but it is an updatable query, so FOR UPDATE statement can be used.

gSQL> \var v_id   INTEGER
gSQL> \var v_name VARCHAR(128)
gSQL> \var v_addr VARCHAR(128)


gSQL> SELECT t1.id, t1.name, t2.addr 
        INTO :v_id, :v_name, :v_addr
        FROM t1, t2
       WHERE t1.id = t2.id
       ORDER BY 1
       LIMIT 1
         FOR UPDATE;

ID NAME    ADDR         
-- ------- -------------
 1 someone somewhere    

1 row selected.

The following is a non-updatable query, so FOR UPDATE statement can not be used.

gSQL> \var v_id    INTEGER
gSQL> \var v_count INTEGER

gSQL> SELECT id, COUNT(*)
        INTO :v_id, :v_count
        FROM t1
       GROUP BY id
         FOR UPDATE;

ERR-42000(16112): query expression is not updatable

For More Information

Refer to the followings.

SET CONSTRAINTS

Function

It sets the check point of deferrable constraint in a transaction to IMMEDIATE or DEFERRED.

Syntax

<set constraints mode statement> ::=
    SET { CONSTRAINT | CONSTRAINTS } <constraint name list> { DEFERRED | IMMEDIATE }
    ;

<constraint name list> ::=
      ALL
    | <constraint name> [, ...]

Invocation and Access Rules

Any separate access privilege is not required for a user to perform SET CONSTRAINTS.

It is not supported in the cluster system.

Syntax Rules and Parameters

CONSTRAINT | CONSTRAINTS

CONSTRAINT and CONSTRAINTS are the keywords of the same meaning, and the SQL standard uses CONSTRAINTS.

<constraint name list>

It specifies the list of constraint names, or specifies ALL to set all deferrable constraints.
When specifying <constraint name>, it should be the name of the deferrable constraint.
ALL means all deferrable constraints.

DEFERRED | IMMEDIATE

It sets the check point of specified deferrable constraints.

If the transaction is in progress, the check point of the constraint is set in the current transaction. If the transaction is not in progress, it is set in the next transaction.
After the transaction ends, it does not affect the next transaction.

Description

Deferrable Constraint

DEFERRABLE constraint can change its check point.
The following is an example of creating a table with a deferrable constraint, and inserting data to the table.
gSQL> CREATE TABLE t1 
( 
    id   INTEGER, 
    name VARCHAR(128) CONSTRAINT t1_uk UNIQUE 
                      DEFERRABLE INITIALLY IMMEDIATE
);

Table created.

gSQL> COMMIT;

Commit complete.

gSQL> INSERT INTO t1 VALUES ( 1, 'leekmo' );

1 row created.

gSQL> INSERT INTO t1 VALUES ( 2, 'mkkim' );

1 row created.

gSQL> COMMIT;

Commit complete.

In the example above, UNIQUE constraint which is deferrable is created on a name column, and the initial check point is set as INITIALLY IMMEDIATE. Therefore, the constraint is checked whenever DML statement is executed.

In this case, if the user tries to exchange the name value of two rows as follows, it violates the constraint because the check point is IMMEDIATE.

gSQL> UPDATE t1 SET name = 'mkkim' WHERE id = 1;

ERR-23000(16057): unique constraint (PUBLIC.T1_UK) violated

gSQL> UPDATE t1 SET name = 'leekmo' WHERE id = 2;

ERR-23000(16057): unique constraint (PUBLIC.T1_UK) violated

If the check point is changed to DEFERRED as follows, the operation as same as above succeeds because the constraint is checked when the transaction is committed.

gSQL> SET CONSTRAINTS t1_uk DEFERRED;

Constraints set.

gSQL> UPDATE t1 SET name = 'mkkim' WHERE id = 1;

1 row updated.

gSQL> UPDATE t1 SET name = 'leekmo' WHERE id = 2;

1 row updated.

gSQL> COMMIT;

Commit complete.

If the check point is set to DEFERRED, then the constraint is checked when the transaction is committed. Therefore, if the transaction is committed when the constraint is violated, then the transaction fails and it is rolled back as follows.

gSQL> SET CONSTRAINTS t1_uk DEFERRED;

Constraints set.

gSQL> INSERT INTO t1 VALUES ( 3, 'leekmo' );

1 row created.

gSQL> COMMIT;

ERR-40002(16291): transaction rollback: integrity constraint violation : PUBLIC.T1_UK(1)

Violation of a Deferred Constraint

Executing the following statements when the transaction violates the constraints set to DEFFFERED, then an error occurs as follows.

An unexpected ROLLBACK can occur when COMMIT, it is necessary to ensure whether the transaction violates the constraint by using SET CONSTRAINTS ALL IMMEDIATE statement.

gSQL> SET CONSTRAINTS t1_uk DEFERRED;

Constraints set.

gSQL> INSERT INTO t1 VALUES ( 3, 'leekmo' );

1 row created.

gSQL> SET CONSTRAINTS ALL IMMEDIATE;

ERR-23000(16038): integrity constraint violation : PUBLIC.T1_UK(1)

gSQL> SELECT * FROM t1 ORDER BY id;

ID NAME  
-- ------
 1 mkkim 
 2 leekmo
 3 leekmo

3 rows selected.

gSQL> UPDATE t1 SET name = 'xcom73' WHERE id = 3;

1 row updated.

gSQL> SET CONSTRAINTS ALL IMMEDIATE;

Constraints set.

gSQL> COMMIT;

Commit complete.

Transaction Control Language

SET CONSTRAINTS statement is a transaction control language which is used when the transaction is in progress such as SAVEPOINT savepoint_specifier.
The transaction control such as COMMIT, ROLLBACK, ROLLBACK TO SAVEPOINT statement is applied to SET CONSTRAINTS statement.
The following is an example of a table with multiple deferrable constraints.
CREATE TABLE t1
(
   id1 INTEGER CONSTRAINT t1_uk1 UNIQUE DEFERRABLE INITIALLY IMMEDIATE,
   id2 INTEGER CONSTRAINT t1_uk2 UNIQUE DEFERRABLE INITIALLY IMMEDIATE,
   id3 INTEGER CONSTRAINT t1_uk3 UNIQUE DEFERRABLE INITIALLY IMMEDIATE
);

If <set constraints mode statement> statement is performed when the transaction is in progress, the check point of deferrable constraints is changed depending on each point as follows.

INSERT INTO t1 VALUES ( 1, 1, 1 );

1 row created.

COMMIT;

Commit complete.
SAVEPOINT sp1;

Savepoint created.
SET CONSTRAINTS t1_uk1 DEFERRED;

Constraints set.
SAVEPOINT sp2;

Savepoint created.
SET CONSTRAINTS t1_uk2 DEFERRED;

Constraints set.
SAVEPOINT sp3;

Savepoint created.
SET CONSTRAINTS ALL DEFERRED;

Constraints set.
SAVEPOINT sp4;

Savepoint created.
SET CONSTRAINTS ALL IMMEDIATE;

Constraints set.

When the transaction is partially rolled back by using ROLLBACK TO SAVEPOINT statement as follows, SET CONSTRAINTS statement is also partially rolled back and the check point is changed.

INSERT INTO t1 VALUES ( 1, 2, 2 );

ERR-23000(16057): unique constraint (PUBLIC.T1_UK1) violated
INSERT INTO t1 VALUES ( 3, 1, 3 );

ERR-23000(16057): unique constraint (PUBLIC.T1_UK2) violated
INSERT INTO t1 VALUES ( 4, 4, 1 );

ERR-23000(16057): unique constraint (PUBLIC.T1_UK3) violated
ROLLBACK TO SAVEPOINT sp4;

Rollback complete.
INSERT INTO t1 VALUES ( 1, 2, 2 );

1 row created.
INSERT INTO t1 VALUES ( 3, 1, 3 );

1 row created.
INSERT INTO t1 VALUES ( 4, 4, 1 );

1 row created.
ROLLBACK TO SAVEPOINT sp3;

Rollback complete.
INSERT INTO t1 VALUES ( 1, 2, 2 );

1 row created.
INSERT INTO t1 VALUES ( 3, 1, 3 );

1 row created.
INSERT INTO t1 VALUES ( 4, 4, 1 );

ERR-23000(16057): unique constraint (PUBLIC.T1_UK3) violated
ROLLBACK TO SAVEPOINT sp2;

Rollback complete.
INSERT INTO t1 VALUES ( 1, 2, 2 );

1 row created.
INSERT INTO t1 VALUES ( 3, 1, 3 );

ERR-23000(16057): unique constraint (PUBLIC.T1_UK2) violated
INSERT INTO t1 VALUES ( 4, 4, 1 );

ERR-23000(16057): unique constraint (PUBLIC.T1_UK3) violated
ROLLBACK TO SAVEPOINT sp1;

Rollback complete.
INSERT INTO t1 VALUES ( 1, 2, 2 );

ERR-23000(16057): unique constraint (PUBLIC.T1_UK1) violated
INSERT INTO t1 VALUES ( 3, 1, 3 );

ERR-23000(16057): unique constraint (PUBLIC.T1_UK2) violated
INSERT INTO t1 VALUES ( 4, 4, 1 );

ERR-23000(16057): unique constraint (PUBLIC.T1_UK3) violated
SELECT * FROM t1;

ID1 ID2 ID3
--- --- ---
  1   1   1

1 row selected.

When the transaction is committed or rolled back, the effects of SET CONSTRAINTS statement is also terminated, and all deferrable constraints follows the constraints property which is INITIALLY IMMEDIATE or INITIALLY DEFERRED value.

Examples

The following is an example of changing the check point by specifying the constraint name.

gSQL> SET CONSTRAINTS t1_uk1 DEFERRED;

Constraints set.

The following is an example of changing the check point of all deferrable constraints.

gSQL> SET CONSTRAINTS ALL DEFERRED;

Constraints set.

Compatibility

The SQL standard does not define CONSTRAINT keyword clause.

SQL standard compatibility

Feature ID

Description

Compatibility

F721

Deferrable constraints

O

For More Information

Refer to the followings.

SET SESSION AUTHORIZATION user_identifier

Function

It sets the session user and current user.

Syntax

<set session user identifier statement> ::=
    SET SESSION AUTHORIZATION user_identifier
    ;

Invocation and Access Rules

ACCESS CONTROL ON DATABASE privilege is required for a logon user to perform <set session user identifier statement>.

The user information is managed in three types as follows.

Syntax Rules and Parameters

user_identifier

It is the username to be altered.

Description

After performing SET SESSION AUTHORIZATION statement, all statements is performed based on the session user. Therefore, the privilege for the session user is checked and the owner of when creating objects also is the session user.

Example

The following is an example that the user test with ACCESS CONTROL ON DATABASE privilege sets the user u1 to the session user.

gSQL> SET SESSION AUTHORIZATION u1;

Session set.

gSQL> SELECT LOGON_USER(), SESSION_USER(), CURRENT_USER FROM dual;

LOGON_USER() SESSION_USER() CURRENT_USER
------------ -------------- ------------
TEST         U1             U1          

1 row selected.

Compatibility

SQL standard compatibility

Feature ID

Description

Compatibility

F321

User authorization

O

SET SESSION CHARACTERISTICS AS transaction_mode

Function

It sets the transaction property of a session.

Syntax

<set session characteristics statement> ::=
    SET SESSION CHARACTERISTICS AS TRANSACTION <transaction_mode>
    ;

<transaction_mode> ::=
    { <transaction_access_mode> | ISOLATION LEVEL < isolation_level > }

<transaction_access_mode> ::=
    READ { ONLY | WRITE }

< isolation_level > ::=
    { READ COMMITTED | SERIALIZABLE }

Syntax Rules and Parameters

<transaction_access_mode>

It is ACCESS MODE of the following transactions.

<isolation_level>

It is ISOLATION LEVEL of the following transactions.

Description

SET SESSION CHARACTERISTICS sets the transaction property of a session. In other words, properties of all transactions created within the session follows these properties.
However, SET TRANSACTION transaction_mode statement sets only the property of a single transaction which is performed next.

Examples

The following is an example that all transactions to be created within the session are set to READ ONLY.

gSQL> SET SESSION CHARACTERISTICS AS TRANSACTION READ ONLY;

Session set.

The following is an example that the isolation level of all transactions to be created within the session is set to READ COMMITTED.

gSQL> SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL READ COMMITTED;

Session set.

Compatibility

SQL standard compatibility

Feature ID

Description

Compatibility

F761

Session management

O

For More Information

Refer to SET TRANSACTION transaction_mode.

SET TIME ZONE

Function

It sets the TIMEZONE of a session.

Syntax

<set local time zone statement> ::=
    SET TIME ZONE <set time zone value>
    ;

<set time zone value> ::= 
    { '[+|-]hh:mm' | LOCAL }

Syntax Rules and Parameters

<set time zone value>

It is the TIMEZONE value to be set.

Description

Altering the time zone of the session affects the result value of function such as CURRENT_TIME, CURRENT_TIMESTAMP.

Example

The following is an example of altering the session time zone to '+09: 00'.

gSQL> SET TIME ZONE '+09:00';

Session set.

Compatibility

SQL standard compatibility

Feature ID

Description

Compatibility

F411

Time zone specifications

O

SET TRANSACTION transaction_mode

Function

It sets the transaction property.

Syntax

<set transaction statement> ::=
    SET TRANSACTION <transaction_mode>
    ;

<transaction_mode> ::=
    { <transaction_access_mode> | ISOLATION LEVEL < isolation_level > }

<transaction_access_mode> ::=
    READ { ONLY | WRITE }

< isolation_level > ::=
    { READ COMMITTED | SERIALIZABLE }

Syntax Rules and Parameters

<transaction_access_mode>

It is ACCESS MODE of the following transactions.

<isolation_level>

It is ISOLATION LEVEL of the following transactions.

Description

SET TRANSACTION sets property of the next transaction, and the property is reset to the default value after the next transaction ends.

Example

The following is an example of setting the next transaction to READ ONLY.

gSQL> SET TRANSACTION READ ONLY;

Transaction set.

Compatibility

SQL standard compatibility

Feature ID

Description

Compatibility

T251

SET TRANSACTION statement: LOCAL option

X

For More Information

Refer to SET SESSION CHARACTERISTICS AS transaction_mode.

TRUNCATE TABLE

Function

It truncates all rows from a table.

Syntax

<truncate table statement> ::= 
    TRUNCATE TABLE table_name 
        [ RESTART IDENTITY | CONTINUE IDENTITY ] 
        [ DROP STORAGE | DROP ALL STORAGE ] 
    ;

Invocation and Access Rules

One of the following privileges is required for a user to perform <truncate table statement>.

Syntax Rules and Parameters

table_name

It is the name of a target table whose rows are to be truncated.
It can define schema to which the table belongs such as schema_name.table_name and if schema_name is omitted, the default schema name of the user performing the statement is used.

[ RESTART IDENTITY | CONTINUE IDENTITY ]

[ DROP STORAGE | DROP ALL STORAGE ]

Description

Data Definition Language (DDL) statement such as TRUNCATE TABLE can be rolled back if it is before when the transaction is committed.

Examples

The following is an example of performing TRUNCATE TABLE statement.

gSQL> TRUNCATE TABLE t1;

Table truncated.

The following is an example of restarting the value of the identity column when performing TRUNCATE TABLE.

TRUNCATE TABLE t1 RESTART IDENTITY;

Table truncated.

Compatibility

The SQL standard does not define [ DROP STORAGE | DROP ALL STORAGE ] clause.

SQL standard compatibility

Feature ID

Description

Compatibility

F200

TRUNCATE TABLE statement

O

F202

TRUNCATE TABLE: identity column restart option

O

UPDATE

Function

It updates rows in a table.

Syntax

<update statement: searched> ::=
    UPDATE table_name [ [ AS ] alias_name ]
        SET <set clause> [, ...]
        [ WHERE <search condition> ]
        [ <result offset clause> ]
        [ <fetch limit clause> ]
    ;

<set clause> ::=
      column_name = { <value expression> | DEFAULT }
    | ( column_name [, ...] ) = ( { <value expression> | DEFAULT } [, ...] )
    | ( column_name [, ...] ) = ( <query expression> )


<result offset clause> ::=
    OFFSET skip_count [ ROW | ROWS ]


<fetch limit clause> ::=
      <fetch first clause>
    | <limit clause>


<fetch first clause> ::=
    FETCH [ FIRST | NEXT ] [ row_count ] [ ROW ONLY | ROWS ONLY ]


<limit clause>
    LIMIT { fetch_row_count | offset_row_count, fetch_row_count | ALL }

Invocation and Access Rules

One of the following privileges is required for a user to perform <update statement: searched>.

Syntax Rules and Parameters

table_name

It is the name of a target table whose rows are to be updated.
It can define schema to which the table belongs such as schema_name.table_name and if schema_name is omitted, the default schema name of the user performing the statement is used.

[ AS alias_name ]

It is the alias of table_name.

<set clause>

It defines the columns to be updated and its values to be assigned. The number of columns in <set clause> should be as same as the number of values.
It can be defined as follows.
UPDATE table_name 
   SET column1 = value1, column2 = value2, column3 = value3
UPDATE table_name 
   SET ( column1, column2, column3 ) = ( value1, value2, value3 )
UPDATE table_name 
   SET column1 = ( SELECT max(value1) FROM other_table_name )
<query expression> should be a query which creates a single row.
If DEFAULT is defined as a column value, the default values (refer to <default clause>) defined when executing CREATE TABLE is used. If it is not defined, NULL value is assigned.

WHERE <search condition>

It updates the rows which satisfy WHERE condition.
If WHERE condition is not specified, all rows are updated.
For more information about WHERE condition, refer to where clause of SELECT.

<result offset clause>

It specifies the number of rows to skip from the query result.
For more information, refer to <result offset clause> of SELECT.

<fetch limit clause>

It specifies the number of rows to fetch in two ways, which are <fetch first clause> and <limit clause>.

Description

Differences among UPDATE-related Statements

Examples

The following is an example of updating multiple rows which satisfy the condition.

gSQL> UPDATE lineitem
         SET l_shipdate = CURRENT_DATE
       WHERE l_returnflag = 'R';

5 rows updated.

The following is an example of updating the value of multiple columns.

gSQL> UPDATE lineitem
         SET l_shipdate   = CURRENT_DATE
           , l_returnflag = 'A'
       WHERE l_returnflag = 'R';

5 rows updated.

The following is an example of updating multiple columns by enclosing them with parentheses.

gSQL> UPDATE lineitem
         SET ( l_shipdate  , l_returnflag )
           = ( CURRENT_DATE, 'A' )
       WHERE l_returnflag = 'R';

5 rows updated.

The following is an example of updating the column value by using the subquery.

gSQL> UPDATE lineitem
         SET l_discount = ( SELECT MAX(l_discount) + 0.01 FROM lineitem )
       WHERE l_returnflag = 'R';

5 rows updated.

The following is an example of updating part of the rows which satisfy the condition by using OFFSET and FETCH clauses.

gSQL> UPDATE lineitem
         SET l_discount = l_discount + 0.01
       WHERE l_returnflag = 'R'
      OFFSET 3
      FETCH 2;

2 rows updated.

Compatibility

The SQL standard does not define the following clauses in UPDATE statement.

SQL standard compatibility

Feature ID

Description

Compatibility

F781

Self-referencing operations

X

T111

Updatable joins, unions, and columns

X

UPDATE name RETURNING

Function

It updates rows in a table, and retrieves the rows of before or after the update.

Syntax

<update statement: searched> ::=
    UPDATE table_name [ [ AS ] alias_name ]
        SET <set clause> [, ...]
        [ WHERE <search condition> ]
        [ <result offset clause> ]
        [ <fetch limit clause> ]
        <returning clause>

<set clause> ::=
      column_name = { <value expression> | DEFAULT }
    | ( column_name [, ...] ) = ( { <value expression> | DEFAULT } [, ...] )
    | ( column_name [, ...] ) = ( <query expression> )


<result offset clause> ::=
    OFFSET skip_count [ ROW | ROWS ]


<fetch limit clause> ::=
      <fetch first clause>
    | <limit clause>


<fetch first clause> ::=
    FETCH [ FIRST | NEXT ] [ row_count ] [ ROW ONLY | ROWS ONLY ]


<limit clause>
    LIMIT { fetch_row_count | offset_row_count, fetch_row_count | ALL }


<returning clause> ::=
    { RETURN | RETURNING } [ NEW | OLD ] { * | { <value expression> [ [AS] alias_name] } [, ...] }

Invocation and Access Rules

The user should satisfy the following conditions to perform <update returning query statement>.

Syntax Rules and Parameters

table_name

It is the name of a target table whose rows are to be updated.

[ AS alias_name ]

It is the alias of table_name.

<set clause>

It defines the columns to be updated and its values to be assigned. The number of columns in <set clause> should be as same as the number of values.
For more information, refer to UPDATE.

WHERE <search condition>

It updates the rows which satisfy WHERE condition.
If WHERE condition is not specified, all rows are updated.
For more information about WHERE condition, refer to where clause of SELECT.

<result offset clause>

It specifies the number of rows to skip from the query result.
For more information, refer to <result offset clause> of SELECT.

<fetch limit clause>

It specifies the number of rows to fetch in two ways, which are <fetch first clause> and <limit clause>.

<returning clause>

It defines the updated rows as a result set, and specifies columns to be retrieved from the result set.

Description

For more information, refer to Differences among UPDATE-related Statements.

Examples

The following is an example of obtaining values of the updated rows by using RETURNING clause.

gSQL> UPDATE lineitem 
         SET l_discount = l_discount + 0.01
       WHERE l_returnflag = 'R'
   RETURNING l_orderkey, l_linenumber, l_discount;

L_ORDERKEY L_LINENUMBER L_DISCOUNT
---------- ------------ ----------
         8            1        .07
         9            2        .11
        12            5        .05
        15            1        .03
        16            2        .08

5 rows updated.

The following is an example of obtaining values before the update for the updated rows by using RETURNING OLD clause.

gSQL> UPDATE lineitem 
         SET l_discount = l_discount + 0.01
       WHERE l_returnflag = 'R'
   RETURNING OLD l_orderkey, l_linenumber, l_discount;

L_ORDERKEY L_LINENUMBER L_DISCOUNT
---------- ------------ ----------
         8            1        .06
         9            2         .1
        12            5        .04
        15            1        .02
        16            2        .07

5 rows updated.

Compatibility

The SQL standard does not define <update returning query statement>.

UPDATE name RETURNING .. INTO

Function

It updates a single row of a table, and the updated value is obtained into the host variable.

Syntax

<update statement: searched> ::=
    UPDATE table_name [ [ AS ] alias_name ]
        SET <set clause> [, ...]
        [ WHERE <search condition> ]
        [ <result offset clause> ]
        [ <fetch limit clause> ]
        <returning into clause>
    ;


<set clause> ::=
      column_name = { <value expression> | DEFAULT }
    | ( column_name [, ...] ) = ( { <value expression> | DEFAULT } [, ...] )
    | ( column_name [, ...] ) = ( <query expression> )


<result offset clause> ::=
    OFFSET skip_count [ ROW | ROWS ]


<fetch limit clause> ::=
      <fetch first clause>
    | <limit clause>


<fetch first clause> ::=
    FETCH [ FIRST | NEXT ] [ row_count ] [ ROW ONLY | ROWS ONLY ]


<limit clause>
    LIMIT { fetch_row_count | offset_row_count, fetch_row_count | ALL }


<returning into clause> ::=
    { RETURN | RETURNING } [ NEW | OLD ] { * | { <value expression> [ [AS] alias_name] } [, ...] } INTO variable_name [, ...]

Invocation and Access Rules

The user should satisfy the following conditions to perform <update returning query statement>.

Syntax Rules and Parameters

table_name

It is the name of a target table whose rows are to be updated.

[ AS alias_name ]

It is the alias of table_name.

<set clause>

It defines the columns to be updated and its values to be assigned. The number of columns in <set clause> should be as same as the number of values.
For more information, refer to UPDATE.

WHERE <search condition>

It updates the rows which satisfy WHERE condition.
If WHERE condition is not specified, all rows are updated.
For more information about WHERE condition, refer to where clause of SELECT.

<result offset clause>

It specifies the number of rows to skip in the query result.
For more information, refer to <result offset clause> of SELECT.

<fetch limit clause>

It specifies the number of rows to fetch in two ways, which are <fetch first clause> and <limit clause>.

RETURNING .. AS ..

It defines the updated rows as a result set, and specifies columns to be retrieved from the result set.
For more information, refer to <returning clause> of UPDATE name RETURNING.

INTO variable_name [, ...]

The number of variables specified in INTO clause should be equal to the number of the expressions specified in RETURNING clause.
The row to be updated should be one or less. If two or more rows are updated, an error occurs.

Description

For more information, refer to Differences among UPDATE-related Statements.

Example

The following is an example of obtaining column values of the updated rows into the host variables.
• Declare the host variable.
gSQL> \VAR v_discount NUMBER

gSQL> UPDATE lineitem 
         SET l_discount = l_discount + 0.01
       WHERE l_orderkey = 12 AND l_linenumber = 5
   RETURNING l_discount INTO :v_discount;

V_DISCOUNT
----------
       .05

1 row updated.

Compatibility

In the SQL standard, <update returning into statement> statement does not exist.

UPDATE name WHERE CURRENT OF cursor_name

Function

It updates a single row which the current cursor indicates.

Syntax

<update statement: positioned> ::=
    UPDATE table_name [ [ AS ] alias_name ]
        SET <set clause> [, ...]
        WHERE CURRENT OF cursor_name
    ;

Invocation and Access Rules

The user should satisfy the following conditions to perform <update statement: positioned>.

Syntax Rules and Parameters

table_name

It is the name of a table whose rows are to be updated.

[ AS alias_name ]

It is the alias of table_name.

<set clause>

It defines the columns to be updated and its values to be assigned. The number of columns in <set clause> should be as same as the number of values.
For more information, refer to UPDATE.

cursor_name

The cursor corresponding to cursor_name should satisfy the following conditions.

Description

For more information, refer to Differences among UPDATE-related Statements.

Examples

The following is an example that <update statement: positioned> is performed in interactive SQL (gsql) using the cursor.

gSQL> \VAR v_discount NUMBER
gSQL> DECLARE update_cursor CURSOR FOR 
        SELECT l_discount
          FROM lineitem
         WHERE l_orderkey = 8 AND l_linenumber = 1
           FOR UPDATE;

Cursor declared.
gSQL> OPEN update_cursor;

Cursor is open.
gSQL> FETCH update_cursor INTO :v_discount;

V_DISCOUNT
----------
       .06

1 row fetched.
gSQL> UPDATE lineitem 
         SET l_discount = l_discount + 0.01 
       WHERE CURRENT OF update_cursor;

1 row updated.
gSQL> CLOSE update_cursor;

Cursor closed.

gSQL> COMMIT;

Commit complete.

The following is an example of performing <update statement: positioned> by using the cursor in embedded SQL program.

{
    ...
    EXEC SQL BEGIN DECLARE SECTION;
        ...    
        double v_discount;  
        ...   
    EXEC SQL END DECLARE SECTION;
    ...
    EXEC SQL DECLARE update_cursor CURSOR FOR
              SELECT l_discount
                FROM lineitem
               WHERE l_orderkey = 8 AND l_linenumber = 1
                 FOR UPDATE;
    ...
    EXEC SQL OPEN update_cursor;
    ...
    EXEC SQL FETCH NEXT update_cursor INTO :v_discount;
    ...
    EXEC SQL UPDATE lineitem 
                SET l_discount = l_discount + 0.01 
              WHERE CURRENT OF update_cursor;
    ...
    EXEC SQL CLOSE update_cursor;
    ...
    EXEC SQL COMMIT WORK;
    ...
}

Compatibility

SQL standard compatibility

Feature ID

Description

Compatibility

F831

Full cursor update

O

B031

Basic dynamic SQL

O

For More Information

Refer to CLOSE cursor_name.