Project: StarRocks (App Definition and Development / Database)
File: CREATE_TABLE_AS_SELECT.md

displayed_sidebar: "English" keywords: ['CTAS'] You can use the CREATE TABLE AS SELECT (CTAS) statement to synchronously or asynchronously query a table and create a new table based on the query result, and then insert the query result into the new table. You can submit an asynchronous CTAS task using . Synchronously query a table and create a new table based on the query result, and then insert the query result into the new table. ```SQL CREATE TABLE [IF NOT EXISTS] [database.]table_name [columnname1 [, columnname2, ...]] [indexdefinition1 [, indexdefinition2, ...]] [key_desc] [COMMENT "table comment"] [partition_desc] [distribution_desc] [ORDER BY (columnname1 [, columnname2, ...])] [PROPERTIES ("key"="value", ...)] AS SELECT query [ ... ] ``` Asynchronously query a table and create a new table based on the query result, and then insert the query result into the new table. ```SQL SUBMIT [/+ SET_VAR(key=value) /] TASK [[database.]<task_name>]AS CREATE TABLE [IF NOT EXISTS] [database.]table_name [columnname1 [, columnname2, ...]] [indexdefinition1 [, indexdefinition2, ...]] [key_desc] [COMMENT "table comment"] [partition_desc] [distribution_desc] [ORDER BY (columnname1 [, columnname2, ...])] [PROPERTIES ("key"="value", ...)] AS SELECT query [ ... ] ``` | Parameter | Required | Description | | -- | | | | column_name | No | The name of a column in the new table. You do not need to specify the data type for the column. StarRocks automatically specifies an appropriate data type for the column. StarRocks converts FLOAT and DOUBLE data into DECIMAL(38,9) data. StarRocks also converts CHAR, VARCHAR, and STRING data into VARCHAR(65533) data. | | indexdefinition| No | Since v3.1.8, a bitmap index can be created for the new table. The syntax is `INDEX indexname (col_name. | | keydesc | No | The syntax is `keytype ( <colname1> . Valid values: `DUPLICATE KEY` and `PRIMARY KEY`. Default value: `DUPLICATE KEY`.</li><li> `colname`: the column to form the key.</li></ul> | | COMMENT | No | The comment of the new table. | | partition_desc | No | The partitioning method of the new table. By default, if you do not specify this parameter, the new table has no partition. For more information about partitioning, see . | | distribution_desc | No | The bucketing method of the new table. If you do not specify this parameter, the bucket column defaults to the column with the highest cardinality collected by the cost-based optimizer (CBO). The number of buckets defaults to 10. If the CBO does not collect information about the cardinality, the bucket column defaults to the first column in the new table. For more information about bucketing, see . | | ORDER BY | No | Since v3.1.8, a sort key can be specified for the new table if the new table is a Primary Key table. The sort key can be a combination of any columns. A Primary Key table is a table for which `PRIMARY KEY (xxx)` is specified at table creation.| | Properties | No | The properties of the new table. | | AS SELECT query | Yes | The query result. You can specify columns in `... AS SELECT query`, for example, `... AS SELECT a, b, c FROM tablea;`. In this example, `a`, `b`, and `c` indicates the column names of the table that is

If you do not specify the column names of the new table, the column names of the new table are also `a`, `b`, and `c`. You can specify expressions in `... AS SELECT query`, for example, `... AS SELECT a+1 AS x, b+2 AS y, c*c AS z FROM tablea;`. In this example, `a+1`, `b+2`, and `c*c` indicates the column names of the table that is queried, and `x`, `y`, and `z` indicates the column names of the new table. Note: The number of columns in the new table need to be the same as the number of the columns specified in the SELECT statement . We recommend that you use column names that are easy to identify. | The CTAS statement can only create a new table that meets the following requirements: `ENGINE` is `OLAP`. The table is a Duplicate Key table by default. You can also specify it as a Primary Key table in `key_desc`. The sort keys are the first three columns, and the storage space of the data types of these three columns does not exceed 36 bytes. The CTAS statement does not support setting indexes for a newly created table. If the CTAS statement fails to execute due to reasons, such as an FE restart, one of the following issues may occur: A new table is created successfully but does not contain data. A new table fails to be created. After a new table is created, if multiple methods (such as INSERT INTO) are used to insert data into the new table, the method that completes the INSERT operation first will insert its data into the new table. After a new table is created, you need to manually grant permissions on this table to users. If you do not specify a name for a Task when you asynchronously query a table and create a new table based on the query result, StarRocks automatically generates a name for the Task. Example 1: Synchronously query a table `order` and create a new table `order_new` based on the query result, and then insert the query result into the new table. ```SQL CREATE TABLE order_new AS SELECT * FROM order; ``` Example 2: Synchronously query the `k1`, `k2`, and `k3` columns in the table `order` and create a new table `order_new` based on the query result, and then insert the query result into the new table. Additionally, set the column names of the new table to `a`, `b`, and `c`. ```SQL CREATE TABLE order_new (a, b, c) AS SELECT k1, k2, k3 FROM order; ``` or ```SQL CREATE TABLE order_new AS SELECT k1 AS a, k2 AS b, k3 AS c FROM order; ``` Example 3: Synchronously query the largest value of the `salary` column in the table `employee` and create a new table `employeenew` based on the query result, and then insert the query result into the new table. Additionally, set the column name of the new table to `salarymax`. ```SQL CREATE TABLE employee_new AS SELECT MAX(salary) AS salary_max FROM employee; ``` After data is inserted, query the new table. ```SQL SELECT * FROM employee_new; ++ | salary_max | ++ | 10000 | ++ ``` Example 4: Synchronously query the `customerid` and `firstname` columns in the table `customers` and create a new table `customersnew` based on the query result, and then insert the query result into the new

Additionally, set the column names of the new table to `customeridnew` and `firstnamenew`. Also, build a bitmap index for the column `customerid_new` in the new table. ```SQL CREATE TABLE customers_new ( customeridnew, firstnamenew, INDEX idxbitmapcustomerid (customerid_new) USING BITMAP ) AS SELECT customerid,firstname FROM customers; ``` Example 5: Synchronously query a table `customers` and create a new table `customersnew` based on the query result, and then insert the query result into the new table. Additionally, specify the new table as a Primary Key table, and specify its sort key as `firstname` and `last_name`. ```SQL CREATE TABLE customers_pk PRIMARY KEY (customer_id) ORDER BY (firstname,lastname) AS SELECT * FROM customers; ``` Example 6: Use CTAS to create a Primary Key table. Note that the number of data rows in the Primary Key table may be less than that in the query result. It is because the table only stores the most recent data row among a group of rows that have the same primary key. ```SQL CREATE TABLE employee_new PRIMARY KEY(order_id) AS SELECT orderlist.orderid, sum(goods.price) as total FROM orderlist INNER JOIN goods ON goods.itemid1 = orderlist.itemid2 GROUP BY order_id; ``` Example 7: Synchronously query four tables, including `lineorder`, `customer`, `supplier`, and `part` and create a new table `lineorder_flat` based on the query result, and then insert the query result to the new table. Additionally, specify the partitioning method and bucketing method for the new table. ```SQL CREATE TABLE lineorder_flat PARTITION BY RANGE(`LO_ORDERDATE`) ( START ("1993-01-01") END ("1999-01-01") EVERY (INTERVAL 1 YEAR) ) DISTRIBUTED BY HASH(`LO_ORDERKEY`) AS SELECT l.LOORDERKEY AS LOORDERKEY, l.LOLINENUMBER AS LOLINENUMBER, l.LOCUSTKEY AS LOCUSTKEY, l.LOPARTKEY AS LOPARTKEY, l.LOSUPPKEY AS LOSUPPKEY, l.LOORDERDATE AS LOORDERDATE, l.LOORDERPRIORITY AS LOORDERPRIORITY, l.LOSHIPPRIORITY AS LOSHIPPRIORITY, l.LOQUANTITY AS LOQUANTITY, l.LOEXTENDEDPRICE AS LOEXTENDEDPRICE, l.LOORDTOTALPRICE AS LOORDTOTALPRICE, l.LODISCOUNT AS LODISCOUNT, l.LOREVENUE AS LOREVENUE, l.LOSUPPLYCOST AS LOSUPPLYCOST, l.LOTAX AS LOTAX, l.LOCOMMITDATE AS LOCOMMITDATE, l.LOSHIPMODE AS LOSHIPMODE, c.CNAME AS CNAME, c.CADDRESS AS CADDRESS, c.CCITY AS CCITY, c.CNATION AS CNATION, c.CREGION AS CREGION, c.CPHONE AS CPHONE, c.CMKTSEGMENT AS CMKTSEGMENT, s.SNAME AS SNAME, s.SADDRESS AS SADDRESS, s.SCITY AS SCITY, s.SNATION AS SNATION, s.SREGION AS SREGION, s.SPHONE AS SPHONE, p.PNAME AS PNAME, p.PMFGR AS PMFGR, p.PCATEGORY AS PCATEGORY, p.PBRAND AS PBRAND, p.PCOLOR AS PCOLOR, p.PTYPE AS PTYPE, p.PSIZE AS PSIZE, p.PCONTAINER AS PCONTAINER FROM lineorder AS l INNER JOIN customer AS c ON c.CCUSTKEY = l.LOCUSTKEY INNER JOIN supplier AS s ON s.SSUPPKEY = l.LOSUPPKEY INNER JOIN part AS p ON p.PPARTKEY = l.LOPARTKEY; ``` Example 8: Asynchronously query the table `orderdetail` and create a new table `orderstatistics` based on the query result, and then insert the query result into the new table. ```plaintext SUBMIT TASK AS CREATE TABLE orderstatistics AS SELECT COUNT(*) as count FROM orderdetail; +-+--+ | TaskName | Status | +-+--+ | ctas-df6f7930-e7c9-11ec-abac-bab8ee315bf2 | SUBMITTED | +-+--+ ``` Check information of the Task. ```SQL SELECT * FROM INFORMATION_SCHEMA.tasks; -- Information of the Task TASK_NAME: ctas-df6f7930-e7c9-11ec-abac-bab8ee315bf2 CREATE_TIME: 2022-06-14 14:07:06 SCHEDULE: MANUAL DATABASE: default_cluster:test DEFINITION: CREATE TABLE orderstatistics AS SELECT COUNT(*) as cnt FROM orderdetail EXPIRE_TIME: 2022-06-17 14:07:06 ``` Check the state of the TaskRun. ```SQL SELECT * FROM INFORMATIONSCHEMA.taskruns; -- State of the TaskRun QUERY_ID: 37bd2b63-eba8-11ec-8d41-bab8ee315bf2 TASK_NAME: ctas-df6f7930-e7c9-11ec-abac-bab8ee315bf2 CREATE_TIME: 2022-06-14 14:07:06 FINISH_TIME: 2022-06-14 14:07:07 STATE: SUCCESS DATABASE: DEFINITION: CREATE TABLE orderstatistics AS SELECT COUNT(*) as cnt FROM orderdetail EXPIRE_TIME: 2022-06-17 14:07:06 ERROR_CODE: 0 ERROR_MESSAGE: NULL ``` Query the new table when the state of the TaskRun is `SUCCESS`. ```SQL SELECT * FROM order_statistics; ```