Skip to main content
Create a new table in the database. Tip This operation requires the CREATE TABLE privilege on the destination database.

Syntax

Tip
  • The table name, partition name, column name, and index name you create must follow the naming conventions in System limits.
  • When you specify database name, table name, column name, or partition name, note that some literals are used as reserved keywords in the database. Do not directly use these keywords in SQL statements. If you want to use such a keyword in an SQL statement, enclose it in a pair of backticks (`). See Keywords for these reserved keywords.

Keywords

EXTERNAL

Caution The EXTERNAL keyword is deprecated. We recommend that you use external catalogs to query data from Hive, Iceberg, Hudi, and JDBC data sources instead of using the EXTERNAL keyword to create external tables. Tip Recommendation From v3.1 onwards, StarRocks supports creating Parquet-formatted tables in Iceberg catalogs, and supports sinking data to these Parquet-formatted Iceberg tables by using INSERT INTO. From v3.2 onwards, StarRocks supports creating Parquet-formatted tables in Hive catalogs, and supports sinking data to these Parquet-formatted Hive tables by using INSERT INTO. From v3.3 onwards, StarRocks supports creating ORC- and Textfile-formatted tables in Hive catalogs, and supports sinking data to these ORC- and Textfile-formatted Hive tables by using INSERT INTO. If you would like to use the deprecated EXTERNAL keyword, please expand EXTERNAL keyword details EXTERNAL keyword details To create an external table to query external data sources, specify CREATE EXTERNAL TABLE and set ENGINE to any of these values. You can refer to External table for more information.
  • For MySQL external tables, specify the following properties:
    Note: “table_name” in MySQL should indicate the real table name. In contrast, “table_name” in CREATE TABLE statement indicates the name of this MySQL table on StarRocks. They can either be different or the same. The aim of creating MySQL tables in StarRocks is to access MySQL database. StarRocks itself does not maintain or store any MySQL data.
  • For Elasticsearch external tables, specify the following properties:
    • hosts: the URL that is used to connect your Elasticsearch cluster. You can specify one or more URLs.
    • user: the account of the root user that is used to log in to your Elasticsearch cluster for which basic authentication is enabled.
    • password: the password of the preceding root account.
    • index: the index of the table in your Elasticsearch cluster. The index name is the same as the table name. You can set this parameter to the alias of the table.
    • type: the type of index. The default value is doc.
  • For Hive external tables, specify the following properties:
    Here, database is the name of the corresponding database in Hive table. Table is the name of Hive table. hive.metastore.uris is the server address.
  • For JDBC external tables, specify the following properties:
    resource is the JDBC resource name and table is the destination table.
  • For Iceberg external tables, specify the following properties:
    resource is the Iceberg resource name. database is the Iceberg database. table is the Iceberg table.
  • For Hudi external tables, specify the following properties:

TEMPORARY

Creates a temporary table. From v3.3.1, the database supports creating temporary tables in the Default Catalog. For more information, see Temporary Table. Note When creating a temporary table, you must set ENGINE to olap.

Column definition

col_name

Note that normally you cannot create a column whose name is initiated with __op or __row because these name formats are reserved for special purposes in the database and creating such columns may result in undefined behavior. For native tables, the names of virtual columns (_tablet_id_, _segment_id_, _rss_id_, _source_id_, _row_id_, _rowset_id_, and _dynamic_rssid_) are reserved as well, because a table column of the same name shadows the virtual column and makes both of them impossible to reference in a query. External tables do not expose virtual columns, so they may keep such a column name. If you do need to create such column, set the FE dynamic parameter allow_system_reserved_names to TRUE.

col_type

Specific column information, such as types and ranges:
  • TINYINT (1 byte): Ranges from -2^7 + 1 to 2^7 - 1.
  • SMALLINT (2 bytes): Ranges from -2^15 + 1 to 2^15 - 1.
  • INT (4 bytes): Ranges from -2^31 + 1 to 2^31 - 1.
  • BIGINT (8 bytes): Ranges from -2^63 + 1 to 2^63 - 1.
  • LARGEINT (16 bytes): Ranges from -2^127 + 1 to 2^127 - 1.
  • FLOAT (4 bytes): Supports scientific notation.
  • DOUBLE (8 bytes): Supports scientific notation.
  • DECIMAL[(precision, scale)] (16 bytes)
    • Default value: DECIMAL(10, 0)
    • precision: 1 ~ 38
    • scale: 0 ~ precision
    • Integer part: precision - scale Scientific notation is not supported.
  • DATE (3 bytes): Ranges from 0000-01-01 to 9999-12-31.
  • DATETIME (8 bytes): Ranges from 0000-01-01 00:00:00 to 9999-12-31 23:59:59.
  • CHAR[(length)]: Fixed length string. Range: 1 ~ 255. Default value: 1.
  • VARCHAR[(length)]: A variable-length string. The default value is 1. Unit: bytes. In versions earlier than StarRocks 2.1, the value range of length is 1–65533. From StarRocks 2.1 to 4.1, the range is 1–1048576. From StarRocks 4.2 onwards, the range is 1–2147482624 (2 GiB minus 1 KiB).
  • HLL (1~16385 bytes): For HLL type, there’s no need to specify length or default value. The length will be controlled within the system according to data aggregation. HLL column can only be queried or used by hll_union_agg, Hll_cardinality, and hll_hash.
  • BITMAP: Bitmap type does not require specified length or default value. It represents a set of unsigned bigint numbers. The largest element could be up to 2^64 - 1.

agg_type

Aggregation type. If not specified, this column is a key column. If specified, it is a value column. The aggregation types supported are as follows:
  • SUM, MAX, MIN, REPLACE
  • HLL_UNION (only for HLL type)
  • BITMAP_UNION (only for BITMAP)
  • REPLACE_IF_NOT_NULL: This means the imported data will only be replaced when it is of non-null value. If it is of null value, the database will retain the original value.
Note
  • When the column of aggregation type BITMAP_UNION is imported, its original data types must be TINYINT, SMALLINT, INT, and BIGINT.
  • If NOT NULL is specified by REPLACE_IF_NOT_NULL column when the table was created, the database will still convert the data to NULL without sending an error report to the user. With this, the user can import selected columns.
This aggregation type applies ONLY to the Aggregate table whose key_desc type is AGGREGATE KEY. Since v3.1.9, REPLACE_IF_NOT_NULL newly supports the columns of the BITMAP type.

NULL | NOT NULL

Whether the column is allowed to be NULL. By default, NULL is specified for all columns in a table that uses the Duplicate Key, Aggregate, or Unique Key table. In a table that uses the Primary Key table, by default, value columns are specified with NULL, whereas key columns are specified with NOT NULL. If NULL values are included in the raw data, present them with \N. The database treats \N as NULL during data loading.

DEFAULT

The default value of a column. When you load data into the database, if the source field mapped onto the column is empty, the database automatically fills the default value in the column. You can specify a default value in one of the following ways:
  • DEFAULT current_timestamp: Use the current time as the default value. For more information, see current_timestamp().
  • DEFAULT (<expr>): Use the result returned by a given expression or function as the default value. The following expressions are supported:
    • uuid() and uuid_numeric(): Generate unique identifiers.
    • ARRAY literal expressions (e.g., [1, 2, 3]): For ARRAY type columns.
    • MAP expressions (e.g., map{key: value}): For MAP type columns.
    • row() function (e.g., row(val1, val2)): For STRUCT type columns.
  • DEFAULT <default_value>: Use a given value of the column data type as the default value. The database supports specifying default values for different types: Basic types: Use string literals to specify default values.
    JSON type: Use JSON-formatted strings to specify default values.
    VARBINARY type: Only empty string is supported as default value.
    BITMAP and HLL types: Only empty string is supported as default value, only for AGGREGATE KEY tables.
    Complex types (ARRAY/MAP/STRUCT): Use expression syntax to specify default values, only supported for OLAP tables. Note Default values for complex types are only supported when fast_schema_evolution = true. If the table’s fast_schema_evolution property is explicitly set to false, adding default values for complex types will result in an error.
    Limitations:
    • TIME and VARIANT types do not support default values yet.
    • Default values for complex types (ARRAY/MAP/STRUCT) are only supported for OLAP tables and require the fast_schema_evolution property to be enabled.

AUTO_INCREMENT

Specifies an AUTO_INCREMENT column. The data types of AUTO_INCREMENT columns must be BIGINT. Auto-incremented IDs start from 1 and increase at a step of 1. For more information about AUTO_INCREMENT columns, see AUTO_INCREMENT. Since v3.0, the database supports AUTO_INCREMENT columns.

AS

Specifies the generated column and its expression. The generated column can be used to precompute and store the results of expressions, which significantly accelerates queries with the same complex expressions. Since v3.1, the database supports generated columns.

Index definition

For more information about parameter descriptions and usage notes, see Bitmap indexing.

ENGINE

Default value: olap. If this parameter is not specified, an OLAP table (native table) is created by default. Optional value: mysql, elasticsearch, hive, jdbc, iceberg, and hudi.

Key

Syntax:
Data is sequenced in specified key columns and has different attributes for different key types:
  • AGGREGATE KEY: Identical content in key columns will be aggregated into value columns according to the specified aggregation type. It usually applies to business scenarios such as financial statements and multi-dimensional analysis.
  • UNIQUE KEY/PRIMARY KEY: Identical content in key columns will be replaced in value columns according to the import sequence. It can be applied to make addition, deletion, modification and query on key columns.
  • DUPLICATE KEY: Identical content in key columns co-exists in the database. It can be used to store detailed data or data with no aggregation attributes. Note DUPLICATE KEY is the default type. Data will be sequenced according to key columns.
Note Value columns do not need to specify aggregation types when other key type is used to create tables with the exception of AGGREGATE KEY.

Range-based Distribution

From v4.1 onwards, the database supports the Range-based Distribution semantic, controlled by the FE configuration enable_range_distribution. In shared-data mode it is enabled by default; set the configuration to false to disable it. It has no effect in shared-nothing mode. The data will be sequenced according to the data range of the key columns, and each tablet contains the data from a certain range. The range-based distribution semantic is different from the default semantic in the following aspects:
  • If the key type (AGGREGATE KEY/UNIQUE KEY/PRIMARY KEY/DUPLICATE KEY) is explicitly specified, and a DISTRIBUTED BY clause is not specified, the data will be distributed by range by default.
  • If none of the key type, a DISTRIBUTED BY clause, or an ORDER BY is specified, a Duplicate Key table with the random bucketing strategy will be created.
  • If the key type and a DISTRIBUTED BY clause are not specified, but an ORDER BY clause is specified, a Duplicate Key table with the range-based distribution strategy will be created. In this case, DUPLICATE KEY is equivalent to an ORDER BY clause, and vice versa.
  • If both DUPLICATE KEY and an ORDER BY clause are specified, only the ORDER BY clause will take effect, and DUPLICATE KEY will be ignored.

COMMENT

You can add a table comment when you create a table, optional. Note that COMMENT must be placed after key_desc. Otherwise, the table cannot be created. From v3.1 onwards, you can modify the table comment suing ALTER TABLE <table_name> COMMENT = "new table comment".

Partition

Partitions can be managed in the following ways:

Create partitions dynamically

Dynamic partitioning provides a time-to-live (TTL) management for partitions. The database automatically creates new partitions in advance and removes expired partitions to ensure data freshness. To enable this feature, you can configure Dynamic partitioning related properties at table creation.

Create partitions one by one

Specify only the upper bound for a partition

Syntax:
Note Please use specified key columns and specified value ranges for partitioning.
  • For the naming conventions of partitions, see System limits.
  • Before v3.3.0, columns for the range partitioning only support the following types: TINYINT, SMALLINT, INT, BIGINT, LARGEINT, DATE, and DATETIME. Since v3.3.0, three specific time functions can be used as columns for the range partitioning. For detailed usage, see Data distribution.
  • Partitions are left closed and right open. The left boundary of the first partition is of minimum value.
  • NULL value is stored only in partitions that contain minimum values. When the partition containing the minimum value is deleted, NULL values can no longer be imported.
  • Partition columns can either be single columns or multiple columns. The partition values are the default minimum values.
  • When only one column is specified as the partitioning column, you can set MAXVALUE as the upper bound for the partitioning column of the most recent partition.
Note
  • Partitions are often used for managing data related to time.
  • When data backtracking is needed, you may want to consider emptying the first partition for adding partitions later when necessary.

Specify both the lower and upper bounds for a partition

Syntax:
Note
  • Fixed Range is more flexible than LESS THAN. You can customize the left and right partitions.
  • Fixed Range is the same as LESS THAN in the other aspects.
  • When only one column is specified as the partitioning column, you can set MAXVALUE as the upper bound for the partitioning column of the most recent partition.

Create multiple partitions in a batch

Syntax
  • If the partitioning column is of a date type.
  • If the partitioning column is of an integer type.
Description You can specify the start and end values in START() and END() and the time unit or partitioning granularity in EVERY() to create multiple partitions in a batch.
  • Before v3.3.0, columns for the range partitioning only support the following types: TINYINT, SMALLINT, INT, BIGINT, LARGEINT, DATE, and DATETIME. Since v3.3.0, three specific time functions can be used as columns for the range partitioning. For detailed usage, see Data distribution.
  • If the partitioning column is of a date type, you need to use the INTERVAL keyword to specify the time interval. You can specify the time unit as hour (since v3.0), day, week, month, or year. The naming conventions of partitions are the same as those for dynamic partitions.
For more information, see Data distribution.

Distribution

The database supports hash bucketing and random bucketing. If you do not configure bucketing, the database uses random bucketing and automatically sets the number of buckets by default. In shared-data mode, a table that specifies a key type or an ORDER BY clause but no DISTRIBUTED BY clause uses range-based distribution by default instead; see Range-based Distribution.
  • Random bucketing (since v3.1) For data in a partition, the database distributes the data randomly across all buckets, which is not based on specific column values. And if you want the database to automatically set the number of buckets, you do not need to specify any bucketing configurations. If you choose to manually specify the number of buckets, the syntax is as follows:
    However, note that the query performance provided by random bucketing may not be ideal when you query massive amounts of data and frequently use certain columns as conditional columns. In this scenario, it is recommended to use hash bucketing. Because only a small number of buckets need to be scanned and computed, significantly improving query performance. Precautions
    • You can only use random bucketing to create Duplicate Key tables.
    • You can not specify a Colocation Group for a table bucketed randomly.
    • Spark Load cannot be used to load data into tables bucketed randomly.
    • Since StarRocks v2.5.7, you do not need to set the number of buckets when you create a table. The database automatically sets the number of buckets. If you want to set this parameter, see Set the number of buckets.
    For more information, see Random bucketing.
  • Hash bucketing Syntax:
    Data in partitions can be subdivided into buckets based on the hash values of the bucketing columns and the number of buckets. We recommend that you choose the column that meets the following two requirements as the bucketing column.
    • High cardinality column such as ID
    • Column that is often used as a filter in queries
    If such a column does not exist, you can determine the bucketing column according to the complexity of queries.
    • If the query is complex, we recommend that you select a high cardinality column as the bucketing column to ensure balanced data distribution among buckets and improve cluster resource utilization.
    • If the query is relatively simple, we recommend that you select the column that is often used as the query condition as the bucketing column to improve query efficiency.
    If partition data cannot be evenly distributed into each bucket by using one bucketing column, you can choose multiple bucketing columns (at most three). For more information, see Choose bucketing columns. Precautions:
    • When you create a table, you must specify its bucketing columns.
    • The values of bucketing columns cannot be updated.
    • Bucketing columns cannot be modified after they are specified.
    • Since StarRocks v2.5.7, you do not need to set the number of buckets when you create a table. The database automatically sets the number of buckets. If you want to set this parameter, see Set the number of buckets.
  • Range-based distribution From v4.1 onwards, the database supports the Range-based Distribution semantic, controlled by the FE configuration enable_range_distribution. In shared-data mode it is enabled by default. For detailed information, see Range-based distribution.

Rollup index

You can create rollups in bulk when you create a table. Syntax:

ORDER BY

Since v3.0, Primary Key tables support defining sort keys using ORDER BY. Since v3.3, Duplicate Key tables, Aggregate tables, and Unique Key tables support defining sort keys using ORDER BY. For more descriptions of sort keys, see Sort keys and prefix indexes.

PROPERTIES

Storage and replicas

If the engine type is OLAP, you can specify initial storage medium (storage_medium), automatic storage cooldown time (storage_cooldown_time) or time interval (storage_cooldown_ttl), and replica number (replication_num) when you create a table. The scope where the properties take effect: If the table has only one partition, the properties belong to the table. If the table is divided into multiple partitions, the properties belong to each partition. And when you need to configure different properties for specified partitions, you can execute ALTER TABLE … ADD PARTITION or ALTER TABLE … MODIFY PARTITION after table creation.

Set initial storage medium and automatic storage cooldown time

Properties
  • storage_medium: the initial storage medium, which can be set to SSD or HDD. Make sure that the type of storage medium you explicitly specified is consistent with the BE disk types for your cluster specified in the BE static parameter storage_root_path.
    If the FE configuration item enable_strict_storage_medium_check is set to true, the system strictly checks BE disk type when you create a table. If the storage medium you specified in CREATE TABLE is inconsistent with BE disk type, an error “Failed to find enough host in all backends with storage medium is SSD|HDD.” is returned and table creation fails. If enable_strict_storage_medium_check is set to false, the system ignores this error and forcibly creates the table. However, cluster disk space may be unevenly distributed after data is loaded.
    From v2.3.6, v2.4.2, v2.5.1, and v3.0 onwards, the system automatically infers storage medium based on BE disk type if storage_medium is not explicitly specified.
    • The system automatically sets this parameter to SSD in the following scenarios:
      • The disk types reported by BEs (storage_root_path) contain only SSD.
      • The disk types reported by BEs (storage_root_path) contain both SSD and HDD. Note that from v2.3.10, v2.4.5, v2.5.4, and v3.0 onwards, the system sets storage_medium to SSD when storage_root_path reported by BEs contain both SSD and HDD and the property storage_cooldown_time is specified.
    • The system automatically sets this parameter to HDD in the following scenarios:
      • The disk types reported by BEs (storage_root_path) contain only HDD.
      • From 2.3.10, 2.4.5, 2.5.4, and 3.0 onwards, the system sets storage_medium to HDD when storage_root_path reported by BEs contain both SSD and HDD and the property storage_cooldown_time is not specified.
  • storage_cooldown_ttl or storage_cooldown_time: the automatic storage cooldown time or time interval. Automatic storage cooldown refers to automatically migrate data from SSD to HDD. This feature is only effective when the initial storage medium is SSD.
    • storage_cooldown_ttl: the time interval of automatic storage cooldown for the partitions in this table. If you need to retain the most recent partitions on SSD and automatically cool down older partitions to HDD after a certain time interval, you can use this parameter. The automatic storage cooldown time for each partition is calculated using the value of this parameter plus the upper time bound of the partition.
    The supported values are <num> YEAR, <num> MONTH, <num> DAY, and <num> HOUR. <num> is a non-negative integer. The default value is null, indicating that storage cooldown is not automatically performed. For example, you specify the value as "storage_cooldown_ttl"="1 DAY" when creating the table, and the partition p20230801 with a range of [2023-08-01 00:00:00,2023-08-02 00:00:00) exists. The automatic storage cooldown time for this partition is 2023-08-03 00:00:00, which is 2023-08-02 00:00:00 + 1 DAY. If you specify the value as "storage_cooldown_ttl"="0 DAY" when creating the table, the automatic storage cooldown time for this partition is 2023-08-02 00:00:00.
    • storage_cooldown_time: the automatic storage cooldown time (absolute time) when the table is cooled down from SSD to HDD. The specified time needs to be later than the current time. Format: “yyyy-MM-dd HH:mm:ss”. When you need to configure different properties for specified partitions, you can execute ALTER TABLE … ADD PARTITION or ALTER TABLE … MODIFY PARTITION.
Usage
  • The comparison between the parameters related to automatic storage cooldown is as follows:
    • storage_cooldown_ttl: A table property that specifies the time interval of automatic storage cooldown for partitions in the table. The system automatically cools down a partition at the time the value of this parameter plus the upper time bound of the partition. So automatic storage cooldown is performed at the partition granularity, which is more flexible.
    • storage_cooldown_time: A table property that specifies the automatic storage cooldown time (absolute time) for this table. Also, you can configure different properties for specified partitions after table creation.
    • storage_cooldown_second: A static FE parameter that specifies the automatic storage cooldown latency for all tables within the cluster.
  • The table property storage_cooldown_ttl or storage_cooldown_time takes precedence over the FE static parameter storage_cooldown_second.
  • When configuring these parameters, you need to specify "storage_medium = "SSD".
  • If you do not configure these parameters, automatic storage cooldown is not be automatically performed.
  • Execute SHOW PARTITIONS FROM <table_name> to view the automatic storage cooldown time for each partition.
Limits
  • Expression and List partitioning are not supported.
  • The partition column need to be of date type.
  • Multiple partition columns are not supported.
  • Primary Key tables are not supported.

Set the number of replicas for each tablet in partitions

replication_num: number of replicas for each table in the partitions. Default number: 3.

Bloom filter indexes

If the Engine type is olap, you can specify a column to adopt bloom filter indexes. The following limits apply when you use bloom filter index:
  • You can create bloom filter indexes for all columns of a Duplicate Key or Primary Key table. For an Aggregate table or Unique Key table, you can only create bloom filter indexes for key columns.
  • TINYINT, FLOAT, DOUBLE, and DECIMAL columns do not support creating bloom filter indexes.
  • Bloom filter indexes can only improve the performance of queries that contain the in and = operators, such as Select xxx from table where x in {} and Select xxx from table where column = xxx. More discrete values in this column will result in more precise queries.
For more information, see Bloom filter indexing

Per-column ZSTD compression

For a table whose Engine type is olap, you can compress selected large text or JSON columns with ZSTD while the rest of the table keeps its own codec. This is aimed at columns whose rows repeat each other heavily — conversation history, templated payloads — where ZSTD pays off far more than on the table as a whole. The following limits apply:
  • Only CHAR, VARCHAR, STRING and JSON columns can be nominated.
  • Only value columns can be nominated; key columns are rejected.
  • A column may appear only once in the list.
  • The nominated columns are compressed with ZSTD, overriding the table-level compression for those columns. Every other column is untouched.
A column may also carry its own data page size, written after the column name:
The page is the unit of decompression, so what a larger page buys depends on how big the column’s rows are relative to it. A column whose rows are larger than a page loses all cross-row redundancy at the default 64 KB and can compress several times better with a large page. A column holding hundreds of rows per page already has that redundancy inside the page and gains almost nothing, while every point lookup would decompress the whole larger page. That is why the size is set per column. Columns written without a size keep the BE default (data_page_size). Accepted sizes range from 4 KB to 1 MB. The ceiling is where a point lookup still costs a bounded amount: a 1 MB page reads a single row in roughly a tenth of a millisecond, and past that the bill grows faster than the ratio does. Whether the internal dictionary is actually built for a column is decided by the data, not by the property:
  • The column has to end up plain-encoded. The database picks the encoding from the data, and a column with few distinct values is dictionary-encoded instead, which already compresses it far better than anything here would. Setting the property on such a column has no effect.
  • A CHAR/VARCHAR/STRING column holding 256 rows or fewer is dictionary-encoded outright, so very small tables never get an internal dictionary either. JSON columns have no such row floor — they are plain-encoded to begin with.
  • The column has to fill more than nine data pages in one segment. The first page is what the dictionary is sampled from and the next eight measure whether it pays; all nine are written without it, and the dictionary is used from the tenth page on. A column that ends before that never uses one, which is the right answer for it: the dictionary costs a page of its own and cannot pay for itself over a handful of pages.
  • Those eight pages have to come out clearly smaller with the dictionary than without it — by default at least a tenth smaller, see zstd_compression_dict_min_gain. Otherwise the dictionary is dropped and the rest of the column is written without it.
None of this is an error and none of it changes what the column is compressed with: the nominated columns are still ZSTD. zstd_compression_dict_pages_written counts the column writers that ended up with a dictionary (a flat JSON column has one writer per flattened sub-column). zstd_compression_dict_build_fallback counts only the writers that ATTEMPTED one and were turned down — the build failed, or the completed trial found it did not pay. The cases above where a dictionary is never attempted at all, because the column is dictionary-encoded or ends before the trial finishes, increment neither counter, so the two do not add up to the number of nominated columns. The property can also be changed later with ALTER TABLE ... SET ("zstd_compression_columns" = "..."). This is a schema change: it rewrites every tablet, so the existing data is re-encoded to the new setting as well, and it costs what any other schema change on a table that size costs. Follow it with SHOW ALTER TABLE COLUMN. The table stays readable throughout, and so do segments written either way, because each segment records how it was written.

Colocate Join

If you want to use Colocate Join attributes, specify it in properties.

Dynamic partitions

If you want to use dynamic partition attributes, please specify it in properties.
PROPERTIES Note When the partition column is the INT type, its format must be yyyyMMdd, regardless of the partition time granularity.

Bucket size with random bucketing

Since v3.2, for tables configured with random bucketing, you can specify the bucket size by using the bucket_size parameter in PROPERTIES at table creation to enable the on-demand and dynamic increase of the number of buckets. Unit: B.

Data compression algorithm

You can specify a data compression algorithm for a table by adding property compression when you create a table. The valid values of compression are:
  • LZ4: the LZ4 algorithm.
  • ZSTD: the Zstandard algorithm.
  • ZLIB: the zlib algorithm.
  • SNAPPY: the Snappy algorithm.
From v3.3.2 onwards, the database supports specifying the compression level for zstd compression format during table creation. Syntax:
compression_level: the compression level for ZSTD compression format. Type: Integer. Range: [1,22]. Default: 3 (Recommended). The greater the number, the higher the compression ratio. The higher the compression level, the more time consumption for compression and decompression. Example:
For more information about how to choose a suitable data compression algorithm, see Data compression.

Write quorum for data loading

If your cluster has multiple data replicas, you can set different write quorum for tables, that is, how many replicas are required to return loading success before the database can determine the loading task is successful. You can specify write quorum by adding the property write_quorum when you create a table. This property is supported from v2.5. The valid values of write_quorum are:
  • MAJORITY: Default value. When the majority of data replicas return loading success, the database returns loading task success. Otherwise, the database returns loading task failed.
  • ONE: When one of the data replicas returns loading success, the database returns loading task success. Otherwise, the database returns loading task failed.
  • ALL: When all of the data replicas return loading success, the database returns loading task success. Otherwise, the database returns loading task failed.
Caution
  • Setting a low write quorum for loading increases the risk of data inaccessibility and even loss. For example, you load data into a table with one write quorum in a cluster of two replicas, and the data was successfully loaded into only one replica. Despite that the database determines the loading task succeeded, there is only one surviving replica of the data. If the server which stores the tablets of loaded data goes down, the data in these tablets becomes inaccessible. And if the disk of the server is damaged, the data is lost.
  • The database returns the loading task status only after all data replicas have returned the status. The database will not return the loading task status when there are replicas whose loading status is unknown. In a replica, loading timeout is also considered as loading failed.

Replica data writing and replication mode

If your cluster has multiple data replicas, you can specify the replicated_storage parameter in PROPERTIES to configure the data writing and replication mode among replicas.
  • true (default in v3.0 and later) indicates “single leader replication”, which means data is written only to the primary replica. Other replicas synchronize data from the primary replica. This mode significantly reduces CPU cost caused by data writing to multiple replicas. It is supported from v2.5.
  • false (default in v2.5) indicates “leaderless replication”, which means data is directly written to multiple replicas, without differentiating primary and secondary replicas. The CPU cost is multiplied by the number of replicas.
In most cases, using the default value gains better data writing performance. If you want to change the data writing and replication mode among replicas, run the ALTER TABLE command. Example:

Delta Join unique and foreign key constraints

To enable query rewrite in the View Delta Join scenario, you must define the Unique Key constraints unique_constraints and Foreign Key constraints foreign_key_constraints for the table to be joined in the Delta Join. See Asynchronous materialized view - Rewrite queries in View Delta Join scenario for further information.
  • child_column: the Foreign Key of the table. You can define multiple child_column.
  • catalog_name: the name of the catalog where the table to join resides. The default catalog is used if this parameter is not specified.
  • database_name: the name of the database where the table to join resides. The current database is used if this parameter is not specified.
  • parent_table_name: the name of the table to join.
  • parent_column: the column to be joined. They must be the Primary Keys or Unique Keys of the corresponding tables.
Caution
  • unique_constraints and foreign_key_constraints are only used for query rewrite. Foreign Key constraints checks are not guaranteed when data is loaded into the table. You must ensure the data loaded into the table meets the constraints.
  • The primary keys of a Primary Key table or the unique keys of a Unique Key table are, by default, the corresponding unique_constraints. You do not need to set it manually.
  • The child_column in a table’s foreign_key_constraints must be referenced to a unique_key in another table’s unique_constraints.
  • The number of child_column and parent_column must agree.
  • The data types of the child_column and the corresponding parent_column must match.

Cloud-native tables for shared-data clusters

To use your database Shared-data cluster, you must create cloud-native tables with the following properties:
  • storage_volume: The name of the storage volume used to store the cloud-native table you want to create. If this property is not specified, the storage volume of the database is used; if the database has no storage volume, the default storage volume is used. This property is supported from v3.1 onwards.
  • datacache.enable: Whether to enable the local disk cache. Default: true.
    • When this property is set to true, the data to be loaded is simultaneously written into the object storage and the local disk (as the cache for query acceleration).
    • When this property is set to false, the data is loaded only into the object storage.
    Note To enable the local disk cache, you must specify the directory of the disk in the BE configuration item storage_root_path.
  • datacache.partition_duration: The time range of the hot partitions, counted back from the current time. For a table partitioned by a DATE or DATETIME column, when a query scans a partition, the database populates the cache with the scanned data only if the partition’s range overlaps this time range (or, for list partitioning, if a partition value falls within it). Queries on other partitions still read data that is already cached, but they do not populate the cache and do not use the in-memory page cache. This property is checked against partition bounds at query time, not against the time when data was loaded, and it does not evict data that is already cached. It has no effect on tables that are neither range-partitioned by a single DATE or DATETIME column nor list-partitioned by a DATE or DATETIME column. This property is a string value in the format <number> <unit>, where the unit can be YEAR, MONTH, WEEK, DAY, HOUR, MINUTE, or SECOND (case-insensitive, singular or plural), for example, 7 DAY and 12 HOUR. You can combine several pairs, such as 1 DAY 12 HOUR, but YEAR, MONTH, and WEEK cannot be combined with HOUR, MINUTE, or SECOND. If it is not specified, queries on all partitions populate the cache. Note This property is available only when datacache.enable is set to true.
  • file_bundling (Optional): Whether to enable the File Bundling optimization for the cloud-native table. Supported from v4.0 onwards. When this feature is enabled (setting to true), the system automatically bundles the data files generated by loading, Compaction, or Publish operations, thereby reducing the API cost caused by high-frequency access to the external storage system. Note
    • File Bundling is available only for shared-data clusters with StarRocks v4.0 or later.
    • File Bundling is enabled by default for tables created in v4.0 or later, controlled by FE configuration enable_file_bundling (Default: true).
    • After File Bundling is enabled, you can only downgrade the cluster to v3.5.2 or later. If you want to downgrade to versions earlier than v3.5.2, you must first drop the tables that have enabled File Bundling.
    • File Bundling remains disabled by default for the existing tables after the cluster is upgraded to v4.0.
    • You can manually enable File Bundling for existing tables using the ALTER TABLE statement with the following restrictions:
      • You cannot enable File Bundling for tables with Rollup Indexes created in versions earlier than v4.0. You can drop and recreate the indexes in v4.0 or later, and then enable File Bundling for the tables.
      • You cannot modify the file_bundling property repeatedly within a specific period of time. Otherwise, the system returns an error. You can check if the file_bundling property is available for modification by executing the following SQL statement:
        You are allowed to modify the file_bundling property only when 0 is returned. Non-zero values indicate that the data version corresponding to METADATA_SWITCH_VERSION is yet to be reclaimed by the GC mechanism. You must wait until the data version is reclaimed. You can foreshorten this interval by setting a lower value for the FE dynamic configuration lake_autovacuum_grace_period_minutes. However, remember to reset the configuration to its original value after you modify the file_bundling property.

Fast Schema Evolution

  • fast_schema_evolution: Whether to enable Fast Schema Evolution for the table. Valid values are TRUE or FALSE (default). Enabling Fast Schema Evolution can increase the speed of schema changes and reduce resource usage when columns are added or dropped. Currently, this property can only be enabled at table creation, and it cannot be modified using ALTER TABLE after table creation. Note
    • Fast Schema Evolution is supported for shared-nothing clusters since v3.2.0.
    • Fast Schema Evolution is supported for shared-data clusters since v3.3 and is enabled by default. You do not need to specify this property when creating cloud-native tables in shared-data clusters. The FE dynamic parameter enable_fast_schema_evolution (Default: true) controls this behavior.
  • cloud_native_fast_schema_evolution_v2: Whether to enable Fast Schema Evolution v2 for the cloud-native table. Supported from v4.1 onwards. Valid values are TRUE (default) or FALSE. When Fast Schema Evolution v2 is enabled, schema changes become a synchronous process. When the ALTER TABLE statement returns successfully, the new schema is effective immediately. The system will only modify FE metadata rather than tablet metadata located on S3, so it can always achieve second-level latency no matter how many partitions or tablets in the table. While in the legacy behavior, schema changes are run as an asynchronous job that updates tablet metadata over time. Note
    • Fast Schema Evolution v2 is supported from v4.1 onwards and only for cloud-native tables in shared-data clusters.
    • Default behaviors:
      • For new tables created in a v4.1 cluster, Fast Schema Evolution v2 is enabled by default.
      • For existing tables from a cluster upgraded to v4.1, Fast Schema Evolution v2 is disabled by default. You can enable it by explicitly setting this property to true via ALTER TABLE.
    • Downgrade requirements:
      • To downgrade a shared-data cluster from v4.1 to v4.0.5 or later, you can directly downgrade it following the standard downgrade procedures.
      • Before downgrading a shared-data cluster from v4.1 to v3.x or patch versions earlier than v4.0.5, you must manually set cloud_native_fast_schema_evolution_v2 to false for any tables that have enabled Fast Schema Evolution v2 via ALTER TABLE. You must wait until the asynchronous jobs become FINISHED. You can track the job status via SHOW ALTER.
You can inspect the schema change jobs via SHOW ALTER TABLE COLUMN. Example:
For cloud-native tables with Fast Schema Evolution v2 enabled, schema change jobs will typically appear as FINISHED, because the change is applied by updating FE metadata only.

Forbid Base Compaction

base_compaction_forbidden_time_ranges: The time range used to restrict Base Compaction for the table. Its effect depends on the table architecture and compaction policy, as described below. This property is supported from v3.2.13. Version scope: v3.2.13 is when this property became available for shared-nothing non-Primary Key tables, not for shared-data tables. The 4.1 series does not support setting it on shared-data tables; FE rejects the setting. The shared-data behavior below is supported from v4.2. The property defines when automatic Base Compaction is forbidden; manual ALTER TABLE ... COMPACT requests bypass the restriction in versions that support it. See Version support for shared-data Base Compaction. For shared-data Primary Key tables and non-Primary Key tables using the Base and Cumulative policy, the range restricts automatic Base Compaction when compaction is dispatched; Cumulative Compaction can still run. For non-Primary Key tables using the Size Tiered policy, the range only disables the delete-version threshold that forces Base Compaction. Normal Size Tiered level selection can still choose the oldest level during the forbidden period. The BE/CN parameter base_compaction_interval_seconds_since_last_operation applies the same restrictions until the minimum interval has elapsed. Manual ALTER TABLE ... COMPACT requests override these restrictions. Note For shared-nothing tables, make sure that the number of data loading to the table does not exceed 500 during the period when Base Compaction is forbidden. The value of base_compaction_forbidden_time_ranges follows the Quartz cron syntax, and only supports these fields: <minute> <hour> <day-of-the-month> <month> <day-of-the-week>, where <minute> must be *.
  • When this property is not set or set to "" (an empty string), Base Compaction is not forbidden at any time.
  • When this property is set to * * * * *, Base Compaction is always forbidden.
  • Other values follow the Quartz cron syntax.
    • An independent value indicates the unit time of a field. For example, 8 in the <hour> field means 8:00-8:59.
    • A value range indicates the time range of a field. For example, 8-9 in the <hour> field means 8:00-9:59.
    • Multiple value ranges separated by commas indicate multiple time ranges of the field.
    • <day of the week> has a starting value of 1 for Sunday, and 7 stands for Saturday.
Example:

Specify Common Partition Expression TTL

From v3.5.0 onwards, native tables support Common Partition Expression TTL. partition_retention_condition: The expression that declares the partitions to be retained dynamically. Partitions that do not meet the condition in the expression will be dropped regularly.
  • The expression can only contain partition columns and constants. Non-partition columns are not supported.
  • Common Partition Expression applies to List partitions and Range partitions differently:
    • For tables with List partitions, the database supports deleting partitions filtered by the Common Partition Expression.
    • For tables with Range partitions, the database can only filter and delete partitions using the partition pruning capability of FE. Partitions correspond to predicates that are not supported by partition pruning cannot be filtered and deleted.
Example:
To disable this feature, you can use the ALTER TABLE statement to set this property as an empty string:

Set Flat JSON properties on table level

In v3.3, the database introduced the Flat JSON feature to improve JSON data query efficiency and reduce the complexity of using JSON. This feature was controlled by specific BE configuration items and system variables. As a result, it can only be enabled (or disabled) globally. From v4.0 onwards, you can set the Flat JSON-related properties on table level.
  • flat_json.enable (Optional): Whether to enable the Flat JSON feature. After this feature is enabled, newly loaded JSON data will be automatically flattened, improving JSON query performance.
  • flat_json.null.factor (Optional): The proportion threshold of NULL values in the column. A column will not be extracted by Flat JSON if its proportion of NULL values is higher than this threshold. This parameter takes effect only when flat_json.enable is set to true. Default value: 0.3.
  • flat_json.sparsity.factor (Optional): The proportion threshold of columns with the same name. A column will not be extracted by Flat JSON if the proportion of columns with the same name is lower than this value. This parameter takes effect only when flat_json.enable is set to true. Default value: 0.3.
  • flat_json.column.max (Optional): The maximum number of sub-fields that can be extracted by Flat JSON. This parameter takes effect only when flat_json.enable is set to true. Default value: 100.

Target tablet size of a range-distributed table

Available only on range-distributed tables You can set the property tablet_reshard_target_size to give a range-distributed table its own target tablet size. Automatic tablet split and merge of the table use this value in place of the FE configuration tablet_reshard_target_size while that configuration is positive. Unit: bytes. The value must be a positive integer.
The property has no default value. A table without it follows the FE configuration tablet_reshard_target_size. On a table that is not range-distributed, the statement fails with tablet_reshard_target_size is only supported for range-distributed tables. You can change or remove this property with ALTER TABLE. For details, see Data distribution - Target tablet size.

Skip a table in automatic statistics collection

You can set enable_statistic_auto_collect to false to stop automatic statistics collection from collecting statistics on a table. Default: true.
When this property is false:
  • The automatic collection task provided by the database, and the automatic collection tasks created by CREATE ANALYZE ALL or CREATE ANALYZE DATABASE, skip this table.
  • Collection tasks that name this table, created by CREATE ANALYZE TABLE or run with ANALYZE TABLE, still collect its statistics.
  • Statistics collection triggered by data loading is not affected. It is controlled separately by enable_statistic_collect_on_first_load.
You can change this property with ALTER TABLE. This property is not supported for materialized views.

Examples

Aggregate table with Hash bucketing and columnar storage

Aggregate table with storage medium and cooldown time set

Duplicate Key table with Range partition, Hash bucketing, column-based storage, storage medium, and cooldown time

LESS THAN
Note: This statement will create three data partitions:
Data outside these ranges will be not be loaded. Fixed Range

MySQL external table

Table with HLL columns

Table using BITMAP_UNION aggregation type

The original data type of v1 and v2 columns must be TINYINT, SMALLINT, or INT.

Tables that support Colocate Join

Table with bitmap index

Dynamic partition table

The dynamic partitioning function must be enabled (“dynamic_partition.enable” = “true”) in FE configuration. For more information, see Configure dynamic partitions. This example creates partitions for the next three days and deletes partitions created three days ago. For example, if today is 2020-01-08, partitions with the following names will be created: p20200108, p20200109, p20200110, p20200111, and their ranges are:

Table with multiple partitions created in a batch, and an integer column as a partitioning column

In the following example, the partitioning column datekey is of the INT type. All the partitions are created by only one simple partition clause START ("1") END ("5") EVERY (1). The range of all the partitions starts from 1 and ends at 5, with a partition granularity of 1:
NOTE The partitioning column values in START() and END() need to be wrapped in quotation marks, while the partition granularity in the EVERY() does not need to be wrapped in quotation marks.

Hive external table

Before you create a Hive external table, you must have created a Hive resource and database. For more information, see External table.

Primary Key table with specific sort key

Suppose that you need to analyze user behavior in real time from dimensions such as users’ address and last active time. When you create a table, you can define the user_id column as the primary key and define the combination of the address and last_active columns as the sort key.

Partitioned temporary table

Table with Flat JSON properties

References