Skip to main content

Insert Into Select

INSERT INTO loads query results into a target table. The examples below describe ordinary synchronous execution, not Group Commit: the statement returns a result after execution. All accepted rows commit together, or the transaction fails. Configured filters can reject rows before commit, so a successful transaction does not necessarily mean that every source row was loaded. Group Commit modes can change acknowledgment and visibility behavior.

Run these statements in SQL Editor or a connected SQL client in a running SaaS or BYOC warehouse. Create testdb if needed. You need CREATE to create the example tables, SELECT on source tables, and LOAD (also accepted as INSERT) on target tables. External catalogs and file sources also require valid source credentials and warehouse network access.

Example responses below are illustrative. IDs, timings, hosts, and row counts depend on your load.

Use cases​

Use INSERT INTO SELECT in the following scenarios:

ScenarioDescription
Inter-table ETL transformationApply ETL transformation to data in a warehouse table and write it into another warehouse table.
Importing data from external tablesMap tables from external systems such as MySQL or Hive through Multi-Catalog, and then use INSERT INTO SELECT to import the external data into a warehouse table.
Direct file importUse a Table Value Function (TVF) to query files on object storage or HDFS as a table, with automatic column type inference, and then write the result into a warehouse table.

Basic principles​

INSERT INTO submits an import job to the FE node through the MySQL protocol. The execution flow is as follows:

  1. The FE receives the SQL and generates an execution plan. The front part consists of query-related operators, and the last operator is OlapTableSink, which writes the query result into the target table.
  2. The execution plan is dispatched to BE nodes for execution.
  3. The query engine selects one BE as the Coordinator node, which is responsible for receiving data and distributing it to other BE nodes.

Quick start​

INSERT INTO is submitted through the MySQL protocol. The following examples use the MySQL command line to demonstrate the complete flow.

For detailed syntax, see INSERT INTO.

Prerequisites​

You need LOAD privilege on the target table (INSERT is accepted as a compatibility name). If you do not have it, ask an authorized administrator to grant it with GRANT.

Create an import job​

Step 1: Create the source table

CREATE TABLE testdb.test_table(
user_id BIGINT NOT NULL COMMENT "user id",
name VARCHAR(20) COMMENT "name",
age INT COMMENT "age"
)
DUPLICATE KEY(user_id)
DISTRIBUTED BY HASH(user_id) BUCKETS 10;

Step 2: Import data into the source table with INSERT INTO VALUES

INSERT INTO testdb.test_table (user_id, name, age)
VALUES (1, "Emily", 25),
(2, "Benjamin", 35),
(3, "Olivia", 28),
(4, "Alexander", 60),
(5, "Ava", 17);

Step 3: Create the target table (with the same schema as the source table)

CREATE TABLE testdb.test_table2 LIKE testdb.test_table;

Step 4: Use INSERT INTO SELECT to import into the target table

INSERT INTO testdb.test_table2
SELECT * FROM testdb.test_table WHERE age < 30;
Query OK, 3 rows affected (0.544 sec)
{'label':'label_9c2bae970023407d_b2c5b78b368e78a7', 'status':'VISIBLE', 'txnId':'9084'}

Step 5: View the import result

MySQL> SELECT * FROM testdb.test_table2 ORDER BY age;
+---------+--------+------+
| user_id | name | age |
+---------+--------+------+
| 5 | Ava | 17 |
| 1 | Emily | 25 |
| 3 | Olivia | 28 |
+---------+--------+------+
3 rows in set (0.02 sec)

Explore advanced usage:

  • You can use JOB to execute INSERT asynchronously.
  • The data source can be a TVF or a table in a Catalog.

View import jobs​

Use SHOW LOAD to view completed INSERT INTO tasks:

MySQL> SHOW LOAD FROM testdb;
+--------+-----------------------------------------+----------+--------------------+--------+---------+----------------------------------------------------------------------+----------+---------------------+---------------------+---------------------+---------------------+---------------------+------+-----------------------------------------------------------------------------------------------------------------------+---------------+--------------+------+---------+
| JobId | Label | State | Progress | Type | EtlInfo | TaskInfo | ErrorMsg | CreateTime | EtlStartTime | EtlFinishTime | LoadStartTime | LoadFinishTime | URL | JobDetails | TransactionId | ErrorTablets | User | Comment |
+--------+-----------------------------------------+----------+--------------------+--------+---------+----------------------------------------------------------------------+----------+---------------------+---------------------+---------------------+---------------------+---------------------+------+-----------------------------------------------------------------------------------------------------------------------+---------------+--------------+------+---------+
| 376416 | label_3e52da787aab4222_9126d2fce8f6d1e5 | FINISHED | Unknown id: 376416 | INSERT | NULL | cluster:N/A; timeout(s):26200; max_filter_ratio:0.0; priority:NORMAL | NULL | 2024-02-27 01:22:17 | 2024-02-27 01:22:17 | 2024-02-27 01:22:17 | 2024-02-27 01:22:17 | 2024-02-27 01:22:18 | | {"Unfinished backends":{},"ScannedRows":0,"TaskNumber":0,"LoadBytes":0,"All backends":{},"FileNumber":0,"FileSize":0} | 9081 | {} | root | |
| 376664 | label_9c2bae970023407d_b2c5b78b368e78a7 | FINISHED | Unknown id: 376664 | INSERT | NULL | cluster:N/A; timeout(s):26200; max_filter_ratio:0.0; priority:NORMAL | NULL | 2024-02-27 01:39:37 | 2024-02-27 01:39:37 | 2024-02-27 01:39:37 | 2024-02-27 01:39:37 | 2024-02-27 01:39:38 | | {"Unfinished backends":{},"ScannedRows":0,"TaskNumber":0,"LoadBytes":0,"All backends":{},"FileNumber":0,"FileSize":0} | 9084 | {} | root | |
+--------+-----------------------------------------+----------+--------------------+--------+---------+----------------------------------------------------------------------+----------+---------------------+---------------------+---------------------+---------------------+---------------------+------+-----------------------------------------------------------------------------------------------------------------------+---------------+--------------+------+---------+

Cancel an import job​

In the MySQL command-line client, you can cancel a running INSERT INTO job with Ctrl-C.

Reference​

Import command​

INSERT INTO SELECT saves the query result into the target table. The basic syntax is:

INSERT INTO target_table SELECT ... FROM source_table;

The SELECT statement can include WHERE, JOIN, and other query operations.

Import configuration parameters​

Defaults below are compiled values checked in Core 26.1.3, not verified settings of your warehouse. Check session values with SHOW VARIABLES. FE settings are service-managed. If a service setting needs adjustment, contact VeloDB Cloud support.

Service-managed FE configuration parameters

ParameterDefaultDescription
insert_load_default_timeout_second14400 (4 hours)Timeout of an import task, in seconds. If the task does not complete within this timeout, the system cancels it and the status changes to CANCELLED.

Session variables

ParameterDefaultDescription
insert_timeout14400 (4 hours)Timeout for INSERT INTO as a SQL statement, in seconds.
enable_insert_stricttrueWhen set to true, the import fails if rows are filtered. When set to false, non-conforming rows can be filtered, subject to insert_max_filter_ratio. Planning, type-analysis, and other execution errors can still fail the statement.
insert_max_filter_ratio1.0Takes effect only when enable_insert_strict = false. Applies to INSERT INTO ... VALUES and INSERT INTO ... SELECT, including queries from warehouse tables, external tables, and file TVFs. The range is 0 to 1. The transaction fails when filtered_rows / (loaded_rows + filtered_rows) exceeds the configured value. A value of 1.0 permits all rows eligible for filtering to be rejected, but does not suppress other execution errors.

Import return values​

The result of INSERT INTO falls into one of three cases:

Empty result set​

If the result set of the SELECT clause is empty, the statement returns:

mysql> INSERT INTO tbl1 SELECT * FROM empty_tbl;
Query OK, 0 rows affected (0.02 sec)
  • Query OK indicates that the execution succeeded.
  • 0 rows affected indicates that no data was imported.

Non-empty result set with successful INSERT​

The examples with filtered-row warnings require enable_insert_strict = false and an insert_max_filter_ratio that permits the filtered proportion. For two loaded rows and two filtered rows, set the ratio to at least 0.5.

mysql> INSERT INTO tbl1 SELECT * FROM tbl2;
Query OK, 4 rows affected (0.38 sec)
{'label':'INSERT_8510c568-9eda-4173-9e36-6adc7d35291c', 'status':'visible', 'txnId':'4005'}

mysql> INSERT INTO tbl1 WITH LABEL my_label1 SELECT * FROM tbl2;
Query OK, 4 rows affected (0.38 sec)
{'label':'my_label1', 'status':'visible', 'txnId':'4005'}

mysql> INSERT INTO tbl1 SELECT * FROM tbl2;
Query OK, 2 rows affected, 2 warnings (0.31 sec)
{'label':'INSERT_f0747f0e-7a35-46e2-affa-13a235f4020d', 'status':'visible', 'txnId':'4005'}

mysql> INSERT INTO tbl1 SELECT * FROM tbl2;
Query OK, 2 rows affected, 2 warnings (0.31 sec)
{'label':'INSERT_f0747f0e-7a35-46e2-affa-13a235f4020d', 'status':'committed', 'txnId':'4005'}

Field descriptions:

  • Query OK: execution succeeded.
  • 4 rows affected: 4 rows were imported in total.
  • 2 warnings: number of rows that were filtered out.

The response also includes transaction details:

{'label':'my_label1', 'status':'visible', 'txnId':'4005'}
{'label':'INSERT_f0747f0e-7a35-46e2-affa-13a235f4020d', 'status':'committed', 'txnId':'4005'}
{'label':'my_label1', 'status':'visible', 'txnId':'4005', 'err':'some other error'}

The fields in the return value are described below:

ParameterDescription
txnIdID of the import transaction.
labelLabel of the import job. You can specify it with INSERT INTO tbl WITH LABEL label ....
statusIndicates whether the imported data is visible:

- visible: the import succeeded and the data is visible.

- committed: the import has completed. The data may become visible with some delay, and no retry is needed.

- Label Already Exists: the label is already in use. Check the original job or transaction before deciding whether to submit a different batch with a new label.

- Fail: the import failed.

errError message of the import.

To find diagnostic information for filtered rows, use the SHOW LOAD statement:

SHOW LOAD WHERE label="xxx";

The URL field identifies diagnostic data and may be private in a managed warehouse. See View Error Rows below.

A COMMITTED transaction has not yet become visible. Do not resubmit it with a new label. You can query the visibility state with the SHOW TRANSACTION statement:

SHOW TRANSACTION WHERE id=4005;

When the TransactionStatus column in the return value is visible, the data is visible.

{'label':'my_label1', 'status':'visible', 'txnId':'4005'}
{'label':'INSERT_f0747f0e-7a35-46e2-affa-13a235f4020d', 'status':'committed', 'txnId':'4005'}
{'label':'my_label1', 'status':'visible', 'txnId':'4005', 'err':'some other error'}

Non-empty result set with failed INSERT​

A failure means that no data was imported successfully. The return is as follows:

mysql> INSERT INTO tbl1 SELECT * FROM tbl2 WHERE k1 = "a";
ERROR 1064 (HY000): all partitions have no load data. url: <error-log-url>
  • ERROR 1064 (HY000): all partitions have no load data: the reason for the failure.
  • The returned URL can be used to query the error data. See View Error Rows below.

Best practices​

Import large volumes of data​

INSERT INTO SELECT can load large query results. Practical batch sizes depend on available compute, memory, source throughput, and timeout settings. Use the following estimate when planning the timeout:

Import timeout >= Data volume / Estimated import speed

Review the following timeout settings:

  1. Set the session variable insert_timeout for the statement.
  2. Contact VeloDB Cloud support if the service-managed insert_load_default_timeout_second needs investigation. Do not edit FE configuration.

View error rows​

When the INSERT INTO return value provides an accessible diagnostic URL, use it in the following command to view error rows:

SHOW LOAD WARNINGS ON "url";

Example:

SHOW LOAD WARNINGS ON "http://ip:port/api/_load_error_log?file=_shard_13/error_loginsert_stmt_d2cac0a0a16d482d-9041c949a4b71605_d2cac0a0a16d482d_9041c949a4b71605";

Common error causes:

  • Source column length exceeds target column length.
  • Column type mismatch.
  • Partition mismatch.
  • Column order mismatch.

Use enable_insert_strict to control whether filtered rows cause INSERT INTO to fail. When strict mode is disabled, insert_max_filter_ratio controls the permitted proportion of filtered rows.

Import external table data via multi-catalog​

Through the Multi-Catalog feature, VeloDB Cloud supports connecting to mainstream data lakes and databases such as Apache Hive, Apache Iceberg, Apache Hudi, Apache Paimon, Elasticsearch, MySQL, Oracle, and SQL Server. After creating an external table, you can import the external table data with INSERT INTO SELECT, or query it directly with SELECT.

For details, see the catalog overview. The following example uses a Hive external table to illustrate the import flow.

Step 1: create a Hive catalog​

CREATE CATALOG hive PROPERTIES (
'type'='hms',
'hive.metastore.uris' = 'thrift://<hive-metastore-host>:9083',
'hadoop.username' = 'hive',
'dfs.nameservices'='your-nameservice',
'dfs.ha.namenodes.your-nameservice'='nn1,nn2',
'dfs.namenode.rpc-address.your-nameservice.nn1'='<namenode-1-host>:<namenode-rpc-port>',
'dfs.namenode.rpc-address.your-nameservice.nn2'='<namenode-2-host>:<namenode-rpc-port>',
'dfs.client.failover.proxy.provider.your-nameservice'='org.apache.hadoop.hdfs.server.namenode.ha.ConfiguredFailoverProxyProvider'
);

Step 2: create the warehouse target table​

CREATE TABLE `target_tbl` (
`k1` decimal(9, 3) NOT NULL COMMENT "",
`k2` char(10) NOT NULL COMMENT "",
`k3` datetime NOT NULL COMMENT "",
`k5` varchar(20) NOT NULL COMMENT "",
`k6` double NOT NULL COMMENT ""
)
COMMENT "Warehouse target table"
DISTRIBUTED BY HASH(k1) BUCKETS 2;

For detailed instructions on creating tables, see the CREATE TABLE syntax reference.

Step 3: execute the import​

Import from the hive.db1.source_tbl table into the target_tbl table:

INSERT INTO target_tbl (k1, k2, k3) SELECT k1, k2, k3 FROM hive.db1.source_tbl LIMIT 100;

For ordinary synchronous execution, check the returned status to determine whether the transaction committed and whether the data is visible. Configured filters can discard source rows even when the transaction succeeds.

Notes​

  • You must ensure that the external data source and the warehouse have network connectivity, especially between the BE nodes and the external data source.

Import file data via TVF​

Through Table Value Function (TVF), VeloDB Cloud can directly query and analyze files on object storage or HDFS as a table, with automatic column type inference and multi-file import. For details, see the Lakehouse / TVF documentation.

TVF supports wildcards (*, ?, [...]) and range patterns ({1..10}) in file paths. For the full syntax, see File path pattern.

Automatic file column type inference​

Using S3 TVF as an example, first inspect the file schema with DESC FUNCTION:

DESC FUNCTION s3 (
"URI" = "https://<bucket>.s3.<region>.amazonaws.com/test.snappy.parquet",
"s3.access_key"= "<access-key>",
"s3.secret_key" = "<secret-key>",
"format" = "parquet",
"use_path_style"="true"
);
+---------------+--------------+------+-------+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------------+--------------+------+-------+---------+-------+
| p_partkey | INT | Yes | false | NULL | NONE |
| p_name | TEXT | Yes | false | NULL | NONE |
| p_mfgr | TEXT | Yes | false | NULL | NONE |
| p_brand | TEXT | Yes | false | NULL | NONE |
| p_type | TEXT | Yes | false | NULL | NONE |
| p_size | INT | Yes | false | NULL | NONE |
| p_container | TEXT | Yes | false | NULL | NONE |
| p_retailprice | DECIMAL(9,0) | Yes | false | NULL | NONE |
| p_comment | TEXT | Yes | false | NULL | NONE |
+---------------+--------------+------+-------+---------+-------+

Notes:

  • The example specifies the file path, connection information, and authentication information.
  • You can view the file schema with DESC FUNCTION.
  • For Parquet files, the query engine automatically infers column types from file metadata.
  • VeloDB Cloud currently supports analysis and column type inference for Parquet, ORC, CSV, and JSON formats.

Import with INSERT INTO SELECT​

-- 1. Create a warehouse target table
CREATE TABLE IF NOT EXISTS test_table
(
id int,
name varchar(50),
age int
)
DISTRIBUTED BY HASH(id) BUCKETS 4
;

-- 2. Insert data using the S3 Table Value Function
INSERT INTO test_table (id,name,age)
SELECT cast(id as INT) as id, name, cast (age as INT) as age
FROM s3(
"uri" = "https://<bucket>.s3.<region>.amazonaws.com/test.snappy.parquet",
"s3.access_key"= "<access-key>",
"s3.secret_key" = "<secret-key>",
"format" = "parquet",
"use_path_style" = "true");

Notes​

  • If the URI specified for the S3 / hdfs TVF does not match any file, or all matched files are empty, the TVF returns an empty result set. In this case, using DESC FUNCTION to view the schema returns a single fake column named __dummy_col, which can be ignored.
  • If the TVF format is specified as CSV and the error The first line is empty, can not parse column numbers is reported, the cause is that the schema cannot be parsed from the first line of the file.

FAQ​

Q1: Is INSERT INTO synchronous or asynchronous?

Ordinary INSERT INTO execution is synchronous. Group Commit modes can change acknowledgment and visibility behavior. To execute it asynchronously, you can combine it with JOB.

Q2: Will partial data be written when INSERT INTO fails?

No. INSERT INTO guarantees atomicity: all accepted rows commit together, or the transaction fails. Configured filters can reject rows before commit.

Q3: How do I handle import timeouts?

Use Import timeout >= Data volume / Estimated import speed as a planning estimate, and review the following settings:

  • Set the session variable insert_timeout.
  • Ask VeloDB Cloud support about the service-managed insert_load_default_timeout_second.

Q4: How do I control tolerance for error data?

  • enable_insert_strict = true: fail the transaction if rows are filtered.
  • enable_insert_strict = false: allow non-conforming rows to be filtered, subject to insert_max_filter_ratio.
  • insert_max_filter_ratio applies to both INSERT INTO ... VALUES and INSERT INTO ... SELECT, including warehouse tables, external tables, and file TVFs. When strict mode is disabled, the transaction fails if filtered_rows / (loaded_rows + filtered_rows) exceeds the configured threshold. A value of 1.0 allows all rows eligible for filtering to be rejected, but does not suppress other execution errors.

Q5: What should I do when the status returns committed but not visible?

committed means that the import has completed, and visibility is pending, so do not submit the same batch again with a new label. You can use SHOW TRANSACTION to check whether TransactionStatus has changed to visible.

See also​

For detailed syntax, see the INSERT INTO reference. You can also enter HELP INSERT in the MySQL client command line for more help.

Cost and cleanup​

Loading consumes warehouse compute and storage. See Billing. Use a separate test database or table, verify the result, and remove only test objects that you no longer need. Retain the source files until you have checked the load status and representative target rows.