Updated on 2024-08-20 GMT+08:00

CREATE TABLE SUBPARTITION

Description

Creates a level-2 partitioned table. Partitioning refers to splitting what is logically one large table into smaller physical pieces based on specific schemes. The table based on the logic is called a partitioned table, and each physical piece is called a partition. Data is stored on these physical partitions, instead of the logical partitioned table. For a level-2 partitioned table, the top-level node table and level-1 partitioned table are logical tables and do not store data. Only the level-2 partitioned (leaf node) stores data.

The partitioning solution of a level-2 partitioned table is a combination of the partitioning solutions of two level-1 partitions. For details about the partitioning solution of a level-1 partitioned table, see CREATE TABLE PARTITION.

Common combination solutions for level-2 partitioned tables include range-range partitioning, range-list partitioning, range-hash partitioning, list-range partitioning, list-list partitioning, list-hash partitioning, hash-range partitioning, hash-list partitioning, and hash-hash partitioning. Currently, level-2 partitioned tables can only be row-store tables.

Precautions

  • A level-2 partitioned table has two partition keys, and each partition key supports only one column.
  • If the constraint key of the unique constraint and primary key constraint contains all partition keys, a local index is created for the constraints. Otherwise, a global index is created. If a local unique index is created, all partition keys must be included.
  • When a level-2 partitioned table is created, if the specified level-2 partition is not displayed under the level-1 partition, a level-2 partition with the same range is automatically created.
  • The maximum total number of partitions (including level-1 and level-2 partitions) in a level-2 partitioned table is 1,048,575. Generally, you are advised not to create so many partitions. If the memory is insufficient due to too many partitions, the performance deteriorates sharply. Create partitions based on the value of local_syscache_threshold. The memory allocated to the level-2 partitioned tables can be calculated as follows: total number of partitions x 3/1024, in MB. Theoretically, the memory occupied by the partitions cannot be greater than the value of local_syscache_threshold. In addition, some space must be reserved for other functions.
  • Considering the impact on performance, it is recommended that the maximum number of partitions in a single table be less than or equal to 2000 and the number of level-2 partitions multiplied by (Number of local indexes + 1) be less than or equal to 10000.
  • Level-2 partitioned tables support only row store and do not support hash bucket.
  • Clusters are not supported.
  • When specifying a partition for query, for example, running SELECT * FROM tablename PARTITION/SUBPARTITION (partitionname), ensure that the keyword PARTITION and SUBPARTITION is correct. If they are incorrect, no error is reported during the query. In this case, the query is performed based on the table alias.
  • Encrypted databases, ledger databases, and row-level security are not supported.
  • In the PARTITION/SUBPARTITION FOR (VALUES) syntax for level-2 partitioned tables, VALUES can only be constants.
  • In the PARTITION/SUBPARTITION FOR (VALUES) syntax for level-2 partitioned tables, if data type conversion is required for VALUES, you are advised to use forcible type conversion to prevent the implicit type conversion result from being inconsistent with the expected result.
  • Currently, the statement specifying a partition cannot perform global index scan.
  • If you add a row-level expression when adding or changing an ILM policy for a data object, note that the row-level expression supports only the functions listed in the whitelist. For details about the whitelist function list, see Row Expression Function Whitelist.

Syntax

CREATE TABLE [ IF NOT EXISTS ] subpartition_table_name
( 
{ column_name data_type [ COLLATE collation ] [ column_constraint [ ... ] ]
| table_constraint
| LIKE source_table [ like_option [...] ] }[, ... ]
)
[ table_option [ [ , ] ... ] ]
[ WITH ( {storage_parameter = value} [, ... ] ) ]
[ WITH ( {storage_parameter = value} [, ... ] ) ]
[ TABLESPACE tablespace_name ]
PARTITION BY {RANGE [ COLUMNS ] | LIST [ COLUMNS ] | HASH | KEY} (partition_key)[ PARTITIONS integer ] 
SUBPARTITION BY {RANGE | LIST | HASH | KEY} (subpartition_key) [ AUTOMATIC ] [ SUBPARTITIONS integer ]
(
  PARTITION partition_name1 [ VALUES LESS THAN {(val1) | MAXVALUE} | VALUES [IN] (val1[, …]) ]
[ ILM ADD POLICY ROW STORE { COMPRESS ADVANCED } { ROW } AFTER n { day | month | year } OF { NO MODIFICATION } [ ON ( EXPR ) ] ]
 [ TABLESPACE [=] tablespace ] 
  [(
       { SUBPARTITION subpartition_name1 [ VALUES LESS THAN (val1_1) | VALUES (val1_1[, …])] 
[ ILM ADD POLICY ROW STORE { COMPRESS ADVANCED } { ROW } AFTER n { day | month | year } OF { NO MODIFICATION } [ ON ( EXPR ) ] ]
 [ TABLESPACE [=] tablespace ] } [, ...]
  )][, ...]
)[ { ENABLE | DISABLE } ROW MOVEMENT ];
  • table_option is as follows:
    { COMMENT [ = ] 'string' |
      AUTO_INCREMENT [ = ] value }
  • Column constraint:
    [ CONSTRAINT constraint_name ]
    { NOT NULL |
      NULL | 
      CHECK ( expression ) | 
      DEFAULT default_e xpr | 
      ON UPDATE update_expr |
      GENERATED ALWAYS AS ( generation_expr ) [STORED] |
      GENERATED [ ALWAYS | BY DEFAULT [ ON NULL ] ] AS IDENTITY [ ( identity_options ) ] |
      AUTO_INCREMENT |
      COMMENT 'string' |
      UNIQUE [KEY] index_parameters | 
      PRIMARY KEY index_parameters |
      REFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ]
            [ ON DELETE action ] [ ON UPDATE action ] }
    [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ]
  • Table constraint:
    [ CONSTRAINT [ constraint_name ] ]
    { CHECK ( expression ) | 
      UNIQUE  [ index_name ][ USING method ] ( { column_name [ ASC | DESC ] } [, ... ] ) index_parameters | 
      PRIMARY KEY  [ USING method ] ( { column_name [ ASC | DESC ] } [, ... ] ) index_parameters |
      FOREIGN KEY [ index_name ] ( column_name [, ... ] ) REFERENCES reftable [ ( refcolumn [, ... ] ) ]
          [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] }
    [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ]
    { [ COMMENT 'string' ] [ ... ] }
  • LIKE options:
    { INCLUDING | EXCLUDING } { DEFAULTS | GENERATED | CONSTRAINTS | INDEXES | STORAGE | COMMENTS | RELOPTIONS| UPDATE | IDENTITY | ALL }
  • Index parameters:
    [ WITH ( {storage_parameter = value} [, ... ] ) ]
    [ USING INDEX TABLESPACE tablespace_name ]
  • update_expr is as follows:
    { CURRENT_TIMESTAMP | LOCALTIMESTAMP | NOW() }

Parameters

  • IF NOT EXISTS

    Does not throw an error if a relationship with the same name existed. A notice is issued in this case.

  • subpartition_table_name

    Specifies the name of a level-2 partitioned table.

    Value range: a string. It must comply with the naming convention.

  • column_name

    Specifies the name of a column to be created in the new table.

    Value range: a string. It must comply with the naming convention.

  • data_type

    Specifies the data type of the column.

  • COLLATE collation

    Assigns a collation to the column (which must be of a collatable data type). If no collation is specified, the default collation is used. You can run the SELECT * FROM pg_collation; command to query collation rules from the pg_collation system catalog. The default collation rule is the row starting with default in the query result.

  • CONSTRAINT constraint_name

    Specifies the name of a column or table constraint. The optional constraint clauses specify constraints that new or updated rows must satisfy for an INSERT or UPDATE operation to succeed.

    There are two ways to define constraints:

    • A column constraint is defined as part of a column definition, and it is bound to a particular column.
    • A table constraint applies to multiple columns.

      The constraint_name is optional in B-compatible mode (sql_compatibility = 'B'). For other modes, constraint_name must be added.

  • index_name

    Index name

    • The index_name is supported only in B-compatible databases (that is, sql_compatibility set to 'B').
    • For foreign key constraints, if constraint_name and index_name are specified at the same time, constraint_name is used as the index name.
    • For a unique key constraint, if both constraint_name and index_name are specified, index_name is used as the index name.
  • USING method

    Specifies the name of the index method to be used.

    For details about the value range, see USING method in Parameters.

    • The USING method is supported only in B-compatible databases (that is, sql_compatibility set to 'B').
    • In B-compatible mode, if USING method is not specified, the default index method is btree for ASTORE or UB-tree for USTORE.
  • ASC | DESC

    ASC specifies an ascending (default) sort order. DESC specifies a descending sort order.

    The ASC|DESC is supported only in B-compatible databases (that is, sql_compatibility set to 'B').

  • LIKE source_table [ like_option ... ]

    Specifies a table from which the new table automatically copies all column names, their data types, and their not-null constraints.

    The new table and original table are decoupled after creation is complete. Changes to the original table will not be applied to the new table, and it is not possible to include data of the new table in scans of the original table.

    • Default expressions for the copied column definitions will be copied only if INCLUDING DEFAULTS is specified. The default behavior is to exclude default expressions, resulting in the copied columns in the new table having default values null.
    • If INCLUDING UPDATE is specified, the ON UPDATE CURRENT_TIMESTAMP attribute of the original table column is copied to the new table column. By default, the generated expression is not copied.
    • If INCLUDING GENERATED is specified, the generated expression of the original table column is copied to the new table. By default, the generated expression is not copied.
    • NOT NULL constraints are always copied to the new table. CHECK constraints will only be copied if INCLUDING CONSTRAINTS is specified; other types of constraints will never be copied. These rules also apply to column constraints and table constraints.

    The copied columns and constraints are not merged with similarly named columns and constraints. If the same name is specified explicitly or in another LIKE clause, an error is reported.

    • Any indexes on the original table will not be created on the new table, unless the INCLUDING INDEXES clause is specified.
    • If INCLUDING STORAGE is specified, the STORAGE setting of the original table column is also copied. By default, the STORAGE setting is not included.
    • If INCLUDING COMMENTS is specified, comments of the original table columns, constraints, and indexes are also copied. The default behavior is to exclude comments.
    • If INCLUDING RELOPTIONS is specified, the storage parameters (WITH clauses) of the original table are also copied to the new table. The default behavior is to exclude partition definition of the storage parameter of the original table.
    • If INCLUDING IDENTITY is specified, the IDENTITY function of the original table is copied to the new table, and a SEQUENCE with the same SEQUENCE parameter as that of the original table is created. By default, the IDENTITY function of the original table is not copied.
    • INCLUDING ALL contains the contents of INCLUDING DEFAULTS, INCLUDING UPDATE, INCLUDING CONSTRAINTS, INCLUDING INDEXES, INCLUDING STORAGE, INCLUDING COMMENTS, INCLUDING PARTITION, INCLUDING RELOPTIONS, and INCLUDING IDENTITY.
  • AUTO_INCREMENT [ = ] value

    This clause specifies an initial value for an auto-increment column. The value must be a positive integer and cannot exceed 2127 – 1.

    This clause takes effect only when sql_compatibility is set to 'B'.

  • COMMENT [ = ] 'string'
    • The COMMENT [ = ] 'string' clause is used to add comments to a table.
    • The COMMENT 'string' in column_constraint indicates that comments are added to a column.
    • The COMMENT 'string' in table_constraint indicates that comments are added to the indexes corresponding to the primary key and unique key.

    For details, see COMMENT [ = ] 'string'.

  • WITH ( storage_parameter [= value] [, ... ] )

    Specifies an optional storage parameter for a table or an index. Optional parameters are as follows:

    • FILLFACTOR

      The fill factor of a table is a percentage from 10 to 100. If the Ustore is used, the default value is 92. If the Astore is used, the default value is 100 (completely filled). When a smaller fill factor is specified, INSERT operations fill table pages only to the indicated percentage. The remaining space on each page is reserved for updating rows on that page. This gives UPDATE a chance to place the updated copy of a row on the same page, which is more efficient than placing it on a different page. For a table whose entries are never updated, setting the fill factor to 100 (complete filling) is the best choice, but in heavily updated tables a smaller fill factor would be appropriate.

      Value range: 10–100

    • ORIENTATION

      Determines the data storage mode of the table.

      Value range:

      • ROW (default value): The data will be stored in rows.

        ORIENTATION cannot be modified.

    • STORAGE_TYPE

      Specifies the storage engine type. This parameter cannot be modified once it is set.

      Value range:

      • USTORE indicates that tables support the in-place update storage engine.

        To use Ustore tables, you need to enable the track_counts and track_activities parameters. Otherwise, space expansion occurs.

      • ASTORE indicates that tables support the append-only storage engine.

      Default value:

      If no table is specified, data is stored in inplace-update mode by default.

    • COMPRESSION
      • Row-store tables do not support compression.
    • segment

      The data is stored in segment-page mode. This parameter supports only row-store tables. Temporary tables and unlogged tables are not supported.

      Value range: on and off

      Default value: off

    • statistic_granularity

      Specifies the default partition_mode of a table during statistics analysis. For details about partition_mode, see ANALYZE|ANALYSE. This parameter is invalid for non-partitioned tables.

      Value range: See the value range of partition_mode.

      Default value: AUTO.

    • enable_tde

      Specifies that the table is an encrypted table. The database automatically encrypts the data in the encrypted table before storing it. Before using this parameter, ensure that TDE function has been enabled using the GUC parameter enable_tde and the information for accessing the key service has been set using the GUC parameter tde_key_info. For details about how to use this parameter, see section "Transparent Data Encryption" in Feature Guide. This parameter applies only to row-store tables, segment-page tables, hash bucket tables, temporary tables, and unlogged tables.

      Value range: on and off When enable_tde is set to on, key_type, tde_cmk_id, and dek_cipher are automatically generated by the database and cannot be manually specified or modified.

      Default value: off

    • encrypt_algo

      Specifies the encryption algorithm of the encryption table. This parameter must be used together with enable_tde.

      Value range: a string. The value can be AES_128_CTR or SM4_CTR.

      Default value: null if enable_tde and AES_128_CTR if enable_tde is set.

    • dek_cipher

      Specifies the DEK ciphertext. After a user sets the enable_tde parameter for a table, the database automatically generates a data key.

      Value range: a string

      Default value: null

    • key_type

      Specifies the type of the master key. After the enable_tde parameter is set for a table, the database automatically obtains the master key type from the GUC parameter tde_key_info.

      Value range: a string

      Default value: null

    • cmk_id

      Specifies the ID of the master key. After the enable_tde parameter is set for a table, the database automatically obtains the master key ID from the GUC parameter tde_key_info.

      Value range: a string

      Default value: null

  • [ ILM ADD POLICY ROW STORE { COMPRESS ADVANCED } { ROW } AFTER n { day | month | year } OF { NO MODIFICATION } [ ON ( EXPR )]]

    When creating a table, you can call ILM ADD POLICY ROW STORE COMPRESS ADVANCED ROW to add an advanced compression policy for row store. Subpartitions inherit the policy of partitions.

    • AFTER n { day | month | year } OF NO MODIFICATION: indicates the rows that are not modified in n days, months, or years.
    • ON (EXPR): indicates the row-level expression, which is used to determine whether a row is hot or cold.
  • TABLESPACE tablespace_name

    Specifies that the new table will be created in the tablespace_name tablespace. If not specified, the default tablespace is used.

  • PARTITION BY {RANGE [COLUMNS] | LIST [COLUMNS] | HASH | KEY} (partition_key)
    • For partition_key, the partitioning policy supports only one column of partition keys.
    • The data types supported by the partition key are the same as those supported by the level-1 partitioned table.
    • The COLUMNS keyword can be used only when sql_compatibility is set to 'B' and can be added only after RANGE or LIST. The semantics of RANGE COLUMNS is the same as that of RANGE, and the semantics of LIST COLUMNS is the same as that of LIST.
    • The KEY keyword can be used only when sql_compatibility is set to 'B'. The meaning of KEY is the same as that of HASH.
  • SUBPARTITION BY {RANGE | LIST | HASH | KEY} (subpartition_key)
    • For subpartition_key, the partitioning policy supports only one column of partition keys.
    • The data types supported by the partition key are the same as those supported by the level-1 partitioned table.
    • The KEY keyword can be used only when sql_compatibility is set to 'B'. The meaning of KEY is the same as that of HASH.
  • AUTOMATIC

    If keyword AUTOMATIC is specified when a table is created, the automatic partitioning function of list partitions is enabled. By default, the automatic partitioning function is disabled. Only list partitions can use the automatic partitioning function.

    After the automatic partitioning function is enabled, if the inserted data cannot match an existing partition, an independent partition is automatically created.

    Based on whether the automatic partitioning function is enabled for level-1 and level-2 partitions, the following situations may occur during data insertion:

    • The automatic expansion function is enabled for the level-1 partition, and any partition policy is used for the level-2 partition. If the inserted data does not match the level-1 partition, the corresponding level-1 partition is automatically created, and the corresponding level-2 partition is a full set.
    • The automatic partitioning function is enabled for the level-2 partition, and the level-1 partition is any partition policy. If the inserted data does not match the level-1 partition, the insertion fails. If the inserted data matches the level-1 partition but does not match the level-2 partition, the corresponding level-2 partition is automatically created.
    • The automatic partitioning function is enabled for both level-1 and level-2 partitions. If the inserted data does not match the level-1 or level-2 partition, the system automatically creates a partition at the corresponding level.
  • PARTITIONS integer

    Specifies the number of partitions.

    integer indicates the number of partitions. The value must be an integer greater than 0 and cannot be greater than 1048575.

    • When this clause is specified after the range and list partitions, each partition must be explicitly defined, and the number of defined partitions must be equal to the integer value. This clause can be specified after the range and list partitions only when sql_compatibility is set to 'B'.
    • When this clause is specified after the hash and key partitions, if the definition of each partition is not listed, an integer number of partitions are automatically generated. The automatically generated partition name is "p+number", and the number ranges from 0 to integer minus 1. The tablespace of the partition is the tablespace of the table by default. If each partition definition is explicitly defined, the number of defined partitions must be the same as the value of integer. If neither the partition definition nor the number of partitions is specified, a unique partition is created.
  • SUBPARTITIONS integer

    Specifies the number of level-2 partitions.

    integer indicates the number of level-2 partitions. The value must be an integer greater than 0 and cannot be greater than 1048575.

    • This clause can be specified only for level-2 HASH and KEY partitions.
      • If level-2 partitions are not defined, an integer number of level-2 partitions are automatically generated in each level-1 partition. The automatically generated level-2 partitions are named in the format of "level-1 partition name+sp+number", where the number ranges from 0 to integer minus 1. The tablespace of the partition is the tablespace of the table by default.
      • If level-2 partitions are defined, the number of level-2 partitions must be the same as the value of integer.
      • If level-2 partitions are not defined and the number of level-2 partitions is not specified, a unique level-2 partition is created.
  • { ENABLE | DISABLE } ROW MOVEMENT

    Specifies whether to enable row movement.

    If the tuple value is updated on the partition key during the UPDATE operation, the partition where the tuple is located is altered. Setting this parameter enables error messages to be reported or movement of the tuple between partitions.

    Value range:

    • ENABLE (default value): Row movement is enabled.
    • DISABLE: Row movement is disabled.

    If the row movement is enabled, an error may be reported when UPDATE and DELETE operations are performed concurrently. The causes are as follows:

    The old data is marked as deleted in the UPDATE and DELETE operations. If the row movement is enabled, the cross-partition update occurs when the partition key is updated, the kernel marks the old data in the old partition as deleted and adds a data to the new partition. As a result, the new data cannot be found by querying the old data.

    If data in the same row is concurrently operated, the cross-partition and non-cross-partition data results have different behaviors in the following three concurrency scenarios: UPDATE and UPDATE concurrency, DELETE and DELETE concurrency, UPDATE and DELETE concurrency.

    1. For non-cross-partition data, no error is reported for the second operation after the first operation is performed.
      • If the first operation is UPDATE, the latest data can be found and operated after the second operation is performed.
      • If the first operation is DELETE, the second operation is terminated if the current data is deleted and the latest data cannot be found.
    2. For the cross-partition data result, an error is reported for the second operation after the first operation is performed.
      • If the first operation is UPDATE, the second operation cannot find the latest data because the new data is in the new partition. Therefore, the second operation fails and an error is reported.
      • If the first operation is DELETE, performing the second operation can find that the current data is deleted and the latest data cannot be found, but cannot determine whether the operation of deleting the old data is UPDATE or DELETE. If the operation is UPDATE, an error is reported. If the operation is DELETE, the operation is terminated. To ensure the data correctness, an error is reported.

    If the UPDATE and UPDATE concurrency, and UPDATE and DELETE concurrency are performed, the error can be solved only when the operations are performed serially. If the DELETE and DELETE concurrency are performed, the error can be solved by disabling the row movement.

  • NOT NULL

    Forbids NULL values in columns. ENABLE can be omitted.

  • NULL

    Allows to contain NULL values. This is the default setting.

    This clause is only provided for compatibility with non-standard SQL databases. It is not recommended.

  • CHECK (condition) [ NO INHERIT ]

    Specifies an expression producing a Boolean result where the INSERT or UPDATE operation of new or updated rows can succeed only when the expression result is TRUE or UNKNOWN; otherwise, an error is thrown and the database is not altered.

    A check constraint specified as a column constraint should reference only the column's values, while an expression in a table constraint can reference multiple columns.

    A constraint marked with NO INHERIT will not propagate to child tables.

    ENABLE can be omitted.

  • DEFAULT default_expr

    Assigns a default data value to a column. The value can be any variable-free expressions. (Subqueries and cross-references to other columns in the current table are not allowed.) The data type of the default expression must match the data type of the column.

    The default expression will be used in any insert operation that does not specify a value for the column. If there is no default value for a column, then the default value is NULL.

  • ON UPDATE update_expr

    The ON UPDATE clause is an attribute constraint of a column.

    When an UPDATE operation is performed on a tuple in a table, if new values of updated columns are different from old values in the table, column values with this attribute but not in updated columns are automatically updated to the current timestamp. If new values of updated columns are the same as old values in the table, column values with this attribute but not in updated columns remain unchanged. If columns with this attribute are in updated columns, column values are updated according to the specified update value.

    • This attribute can be specified only in B-compatible database 5.7 (that is, sql_compatibility is set to 'B', b_format_version is set to '5.7', and b_format_dev_version is set to 's1').
    • In terms of syntax, update_expr supports three keywords: CURRENT_TIMESTAMP, LOCALTIMESTAMP, and NOW(). You can also specify or not specify the precision of a keyword with parentheses. For example, ON UPDATE CURRENT_TIMESTAMP(), ON UPDATE CURRENT_TIMESTAMP(5), ON UPDATE LOCALTIMESTAMP(), and ON UPDATE LOCALTIMESTAMP(6). If the keyword does not contain parentheses or contains empty parentheses, the precision is 0. The NOW keyword cannot contain parentheses. The three types of keywords are synonyms of each other and have the same attribute effect.
    • This attribute can be specified only for columns of the following types: timestamp, datetime, date, time without time zone, smalldatetime, and abstime.
    • The CREATE TABLE AS syntax does not inherit the column attributes.
    • The CREATE TABLE LIKE syntax can use INCLUDING UPDATE or EXCLUDING UPDATE to inherit or exclude a constraint. The LIKE syntax is inherited from the LIKE syntax of PostgreSQL. Currently, the ILM policy information of the old table cannot be copied.
    • The precision specified by this attribute can be different from the precision specified by the type in the corresponding column. After the column value is updated through this attribute, the minimum precision is displayed. For example, CREATE TABLE t1 (col1 timestamp(6) ON UPDATE CURRENT_TIMESTAMP(3));. If the UPDATE syntax triggers the attribute to take effect, three decimal places in the value of col1 are displayed after the update.
    • The same column cannot be specified for this attribute and the generated column constraint at the same time.
    • This attribute cannot be specified for the partition key in a partitioned table.
  • GENERATED ALWAYS AS ( generation_expr ) [STORED]

    This clause creates a column as a generated column. The value of the generated column is calculated by generation_expr when data is written (inserted or updated). STORED indicates that the value of the generated column is stored as a common column.

    • The STORED keyword can be omitted, which has the same semantics as not omitting STORED.
    • The generation expression cannot refer to data other than the current row in any way. The generation expression cannot reference other generation columns or system columns. The generation expression cannot return a result set. No subquery, aggregate function, or window function can be used. The function called by the generation expression can only be an immutable function.
    • Default values cannot be specified for generated columns.
    • The generated column cannot be used as a part of the partition key.
    • Do not specify the generated column and the CASCADE, SET NULL, and SET DEFAULT actions of the ON UPDATE constraint clause together. Do not specify the generated column and the SET NULL, and SET DEFAULT actions of the ON DELETE constraint clause together.
    • The method of modifying and deleting generated columns is the same as that of common columns. Delete the common column that the generated column depends on. The generated column is automatically deleted. The type of the column on which the generated column depends cannot be changed.
    • The generated column cannot be directly written. In the INSERT or UPDATE statement, values cannot be specified for generated columns, but the keyword DEFAULT can be specified.
    • The permission control for generated columns is the same as that for common columns.
  • GENERATED [ ALWAYS | BY DEFAULT [ ON NULL ] ] AS IDENTITY [ ( identity_options ) ]

    Creates a column as an IDENTITY column. An implicit sequence is automatically created based on identity_options and attached to a specified column. When data is inserted, the value obtained from the sequence is automatically assigned to the column.

    • GENERATED ALWAYS AS IDENTITY: Only identity values provided by the sequence generator can be inserted into this column. User-specified values cannot be inserted into this column.
    • GENERATED BY DEFAULT AS IDENTITY: User-specified values are preferentially inserted into this column. If no value is specified, the identity values provided by the sequence generator are inserted.
    • GENERATED BY DEFAULT ON NULL AS IDENTITY: User-specified values are preferentially inserted into this column. If a null value is specified or no value is specified, the identity values provided by the sequence generator are inserted.
    The optional identity_options clause can be used to override sequence options.
    • increment: specifies the implicit sequence step. If the value is a positive number, an ascending sequence is generated. If the value is a negative number, a descending sequence is generated. The default value is 1.
    • MINVALUE minvalue | NO MINVALUE | NOMINVALUE: specifies the minimum value of an execution sequence. If minvalue is not specified or NO MINVALUE is specified, the default value of an ascending sequence is 1, and the default value of a descending sequence is –1027 + 1. NOMINVALUE is equivalent to NO MINVALUE.
    • MAXVALUE maxvalue | NO MAXVALUE | NOMAXVALUE: specifies the maximum value of an execution sequence. If maxvalue is not specified or NO MAXVALUE is specified, the default value of an ascending sequence is 1028 – 1, and the default value of a descending sequence is –1. NOMAXVALUE is equivalent to NO MAXVALUE.
    • start specifies the start value of an implicit sequence. The default value for an ascending sequence is minvalue and that for a descending sequence is maxvalue.
    • cache: specifies the number of sequences stored in the memory for quick access purposes. The default value is 1, indicating that only one value can be generated at a time, that is, no cache is generated.
    • NOCACHE: No value of the sequence is stored in advance.
    • CYCLE: recycles sequences after the number of sequences reaches maxvalue or minvalue. If NO CYCLE is declared, any call to nextval returns an error after the sequence reaches its maximum or minimum value. NOCYCLE is equivalent to NO CYCLE. The default value is NO CYCLE.
    • SCALE: enables sequence scalability. If specified, a numeric offset is appended to the beginning of the sequence to prevent duplicate items in the generated value. If NOSCALE is declared, sequence scalability is disabled. The default value is NOSCALE.
    • EXTEND: extends the numeric offset length (default value: 6), aligns the sequence generation value to x (default value: 6) + y (maximum number of digits). SCALE must be specified when EXTEND is specified. If NOEXTEND is declared, the numeric offset length is not extended. The default value is NOEXTEND.
    • The IDENTITY column can only be of the smallint, integer, bigint, decimal, numeric, float, double precision, or real type.
    • In A-compatible mode, when an IDENTITY column of the integer type is created, the IDENTITY column is of the numeric type by default.
    • The method of changing an IDENTITY column is the same as that of changing a common column, but the type can be changed only to smallint, integer, bigint, decimal, numeric, float, double precision, or real.
    • By default, the IDENTITY column has the NOT NULL constraint.
    • A table can contain only one IDENTITY column.
    • The method of deleting an IDENTITY column is the same as that of deleting a common column. When a column is deleted, the implicit sequence of the IDENTITY column is automatically deleted.
    • The IDENTITY column cannot be specified together with the SET DEFAULT action.
    • The type of the implicit sequence that is automatically created is LARGE SEQUENCE.
    • You cannot use DROP LARGE SEQUENCE or ALTER LARGE SEQUENCE to modify the implicit sequence of an identity.
    • After permission is granted to the table, data can be inserted properly. To modify the IDENTITY column, delete the IDENTITY attribute, or delete the IDENTITY column, you need to grant permission to the corresponding implicit sequence.
    • The [ SCALE [ EXTEND | NOEXTED ] | NOSCALE ] clause is available only when an IDENTITY column is created in a centralized system in A-compatible mode.
    • In a fully-encrypted database, the encrypted IDENTITY column cannot be specified during table creation.
  • AUTO_INCREMENT

    Specifies an auto-increment column.

    For details, see AUTO_INCREMENT.

  • UNIQUE [KEY] index_parameters

    UNIQUE ( column_name [, ... ] ) index_parameters

    Specifies that a group of one or more columns of a table can contain only unique values.

    For the purpose of a unique constraint, null is not considered equal.

    UNIQUE KEY can be used only when sql_compatibility is set to 'B', which has the same semantics as UNIQUE.

  • PRIMARY KEY index_parameters

    PRIMARY KEY ( column_name [, ... ] ) index_parameters

    Specifies that a column or columns of a table can contain only unique (non-duplicate) and non-null values.

    Only one primary key can be specified for a table.

  • DEFERRABLE | NOT DEFERRABLE

    Determines whether the constraint can be deferred. A constraint that is not deferrable will be checked immediately after every command. Checking of constraints that are deferrable can be postponed until the end of the transaction using the SET CONSTRAINTS command. NOT DEFERRABLE is the default value. Currently, only UNIQUE constraints, primary key constraints, and foreign key constraints accept this clause. All the other constraints are not deferrable.

  • INITIALLY IMMEDIATE | INITIALLY DEFERRED

    If a constraint is deferrable, this clause specifies the default time to check the constraint.

    • If the constraint is INITIALLY IMMEDIATE (default value), it is checked after each statement.
    • If the constraint is INITIALLY DEFERRED, it is checked only at the end of the transaction.

    The constraint check time can be altered using the SET CONSTRAINTS statement.

  • USING INDEX TABLESPACE tablespace_name

    Allows selection of the tablespace in which the index associated with a UNIQUE or PRIMARY KEY constraint will be created. If not specified, the index is created in default_tablespace. If default_tablespace is empty, the default tablespace of the database is used.

Examples

  • Creating a level-2 partitioned table
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    -- Create a level-2 partitioned table tbl_list_list. Both of the level-1 and level-2 partitions are of the LIST type.
    gaussdb=# CREATE TABLE tbl_list_list(
        sal_year    varchar(4)  NOT NULL,
        area_id     char(5)     NOT NULL,
        emp_id      char(5)     NOT NULL,
        sales_amt   int
    ) PARTITION BY LIST (sal_year) SUBPARTITION BY LIST(area_id)(
        PARTITION P_2019 VALUES ('2019')(
            SUBPARTITION p_2019_01001 VALUES ('01001'),
            SUBPARTITION p_2019_01002 VALUES ('01002'),
            SUBPARTITION p_2019_01003 VALUES ('01003')            
        ),
        PARTITION p_2020 VALUES ('2020')(
            SUBPARTITION p_2020_01001 VALUES ('01001'),
            SUBPARTITION p_2020_01002 VALUES ('01002'),
            SUBPARTITION p_2020_01003 VALUES ('01003')      
        )
    );
    
    -- Create a level-2 partitioned table tbl_range_list. The level-1 partition is of the RANGE type and level-2 partition is of the LIST type.
    gaussdb=# CREATE TABLE tbl_range_list(
        sal_date    varchar(6)  NOT NULL,
        area_id     char(5)     NOT NULL,
        emp_id      char(5)     NOT NULL,
        sales_amt   int         
    ) PARTITION BY RANGE (sal_date) SUBPARTITION BY LIST(area_id)(
        PARTITION p_201901 VALUES LESS THAN (201902)(
            SUBPARTITION p_201901_01001 VALUES ('01001'),
            SUBPARTITION p_201901_01002 VALUES ('01002'),
            SUBPARTITION p_201901_01003 VALUES ('01003')
        ),
        PARTITION p_201902 VALUES LESS THAN (201903)(
            SUBPARTITION p_201902_01001 VALUES ('01001'),
            SUBPARTITION p_201902_01002 VALUES ('01002'),
            SUBPARTITION p_201902_01003 VALUES ('01003')
        ) 
    );
    
  • Specifying partitions in a level-2 partitioned table using DML statements
    • INSERT
      -- Insert data to a specified level-1 partition.
      gaussdb=# INSERT INTO tbl_range_list PARTITION(p_201901) VALUES('201901', '01001', '0001', 75000 );
      
      -- The actual partition is inconsistent with the specified partition. An error is reported.
      gaussdb=# INSERT INTO tbl_range_list PARTITION(p_201902) VALUES('201901', '01001', '0002', 6000);
      ERROR:  inserted partition key does not map to the table partition
      DETAIL:  N/A.
      
      -- Insert data to a specified level-2 partition.
      gaussdb=# INSERT INTO tbl_range_list SUBPARTITION(p_201902_01001) VALUES('201902', '01001', '0002', 8000);
    • SELECT
      -- Query data in a specified partition.
      gaussdb=# SELECT * FROM tbl_range_list PARTITION(p_201902);
       sal_date | area_id | emp_id | sales_amt 
      ----------+---------+--------+-----------
       201902   | 01001   | 0002   |      8000
      (1 row)
      
      gaussdb=# SELECT * FROM tbl_range_list SUBPARTITION(p_201901_01001);
       sal_date | area_id | emp_id | sales_amt 
      ----------+---------+--------+-----------
       201901   | 01001   | 0001   |     75000
      (1 row)
    • UPDATE
      -- Update data in a specified partition.
      gaussdb=# UPDATE tbl_range_list PARTITION(p_201901) SET sales_amt = 7000;
      
      gaussdb=# SELECT * FROM tbl_range_list;
       sal_date | area_id | emp_id | sales_amt 
      ----------+---------+--------+-----------
       201901   | 01001   | 0001   |      7000
       201902   | 01001   | 0002   |      8000
      (2 rows)
      
      gaussdb=# UPDATE tbl_range_list SUBPARTITION FOR('201902','01001') SET sales_amt=6000;
      
      gaussdb=# SELECT * FROM tbl_range_list;
       sal_date | area_id | emp_id | sales_amt 
      ----------+---------+--------+-----------
       201901   | 01001   | 0001   |      7000
       201902   | 01001   | 0002   |      6000
      (2 rows)
    • DELETE
      -- Delete data from a specified partition.
      gaussdb=# DELETE FROM tbl_range_list PARTITION (p_201901);
      DELETE 1
      
      gaussdb=# DELETE FROM tbl_range_list SUBPARTITION (p_201902_01001);
      DELETE 1
      
      gaussdb=# DELETE FROM tbl_range_list SUBPARTITION for ('201901','01002');
      DELETE 0
      
      -- When sql_compatibility is set to 'B', data can be deleted from multiple partitions.
      gaussdb=# CREATE DATABASE db dbcompatibility 'B';
      gaussdb=# \c db
      db=# CREATE TABLE range_list
      (
          month_code VARCHAR2 ( 30 ) NOT NULL ,
          dept_code  VARCHAR2 ( 30 ) NOT NULL ,
          user_no    VARCHAR2 ( 30 ) NOT NULL ,
          sales_amt  int
      )
      PARTITION BY RANGE (month_code) SUBPARTITION BY LIST (dept_code)
      (
        PARTITION p_201901 VALUES LESS THAN( '201903' )
        (
          SUBPARTITION p_201901_a VALUES ('1'),
          SUBPARTITION p_201901_b VALUES ('2')
        ),
        PARTITION p_201902 VALUES LESS THAN( '201910' )
        (
          SUBPARTITION p_201902_a VALUES ('1'),
          SUBPARTITION p_201902_b VALUES ('2')
        )
      );
      
      db=# DELETE FROM range_list AS t partition (p_201901_a, p_201901);
      DELETE 0
      
      -- Delete the database (replace the database name with the actual one).
      db=# \c postgres 
      gaussdb=# DROP DATABASE db;
      
      -- Delete the table.
      gaussdb=# DROP TABLE tbl_list_list;
      gaussdb=# DROP TABLE tbl_range_list;