INSERT
Description
Use INSERT to insert rows or query results into a table.
INSERT INTO table_name
[ PARTITION (p1, ...) ]
[ WITH LABEL label]
[ (column [, ...]) ]
[ [ hint [, ...] ] ]
{ VALUES ( { expression | DEFAULT } [, ...] ) [, ...] | query }
Parameters:
table_name: The destination table. You can qualify it asdb_name.table_name.PARTITION: The destination partitions, which must exist intable_name. Separate multiple partition names with commas.label: A label for theINSERTtask.column: A destination column, which must exist intable_name.expression: The expression whose value is assigned to a column.DEFAULT: Use the column's default value.query: A query whose results are written to the destination table.hint: Controls the execution behavior ofINSERT. Choose/*+ STREAMING */,/*+ SHUFFLE */, or/*+ NOSHUFFLE */.STREAMING: Has no practical effect and is retained for compatibility with previous versions. Previously, this hint caused the statement to return a label. Statements now return a label by default.SHUFFLE: Repartitions data when the destination table is partitioned.NOSHUFFLE: Does not repartition data, even when the destination table is partitioned. Other operations ensure that data is written to the correct partitions.
For a Unique table with merge-on-write enabled, you can also perform partial columns updates using the insert statement. To perform partial column updates with the insert statement, you need to set the session variable enable_unique_key_partial_update to true (the default value for this variable is false, meaning partial columns updates with the insert statement are not allowed by default). When performing partial columns updates, the columns being inserted must contain at least all the Key columns and specify the columns you want to update. If the Key column values for the inserted row already exist in the original table, the data in the row with the same key column values will be updated. If the Key column values for the inserted row do not exist in the original table, a new row will be inserted into the table. In this case, columns not specified in the insert statement must either have default values or be nullable. These missing columns will first attempt to be populated with default values, and if a column has no default value, it will be filled with null. If a column cannot be null, the insert operation will fail.
Please note that the default value of the session variable enable_insert_strict, which controls whether the insert statement operates in strict mode, is true. In other words, the insert statement is in strict mode by default, and in this mode, updating non-existing keys in partial column updates is not allowed. Therefore, when using the insert statement for partial columns update and wishing to insert non-existing keys, you need to set enable_unique_key_partial_update to true and simultaneously set enable_insert_strict to false.
Notice:
When executing the INSERT statement, the default behavior is to filter the data that does not conform to the target table format, such as the string is too long. However, for business scenarios that require data not to be filtered, you can set the session variable enable_insert_strict to true to ensure that INSERT will not be executed successfully when data is filtered out.
Example
The test table contains two columns, c1 and c2.
- Import a row of data into the
testtable
INSERT INTO test VALUES (1, 2);
INSERT INTO test (c1, c2) VALUES (1, 2);
INSERT INTO test (c1, c2) VALUES (1, DEFAULT);
INSERT INTO test (c1) VALUES (1);
The first and second statements have the same effect. When you omit the destination column list, values follow the table's column order.
The third and fourth statements both use the default value of c2.
- Import multiple rows of data into the
testtable at one time
INSERT INTO test VALUES (1, 2), (3, 2 + 2);
INSERT INTO test (c1, c2) VALUES (1, 2), (3, 2 * 2);
INSERT INTO test (c1) VALUES (1), (3);
INSERT INTO test (c1, c2) VALUES (1, DEFAULT), (3, DEFAULT);
The first and second statements both insert two rows into test with the same values.
The third and fourth statements both insert two rows using the default value of c2.
- Import a query result into the
testtable
INSERT INTO test SELECT * FROM test2;
INSERT INTO test (c1, c2) SELECT * from test2;
- Import a query result into the
testtable, specifying the partition and label
INSERT INTO test PARTITION(p1, p2) WITH LABEL `label1` SELECT * FROM test2;
INSERT INTO test WITH LABEL `label1` (c1, c2) SELECT * from test2;
Keywords
INSERT
Best practice
-
View the returned results
The INSERT operation is a synchronous operation, and the return of the result indicates the end of the operation. Users need to perform corresponding processing according to the different returned results.
-
The execution is successful, the result set is empty
If the result set of the insert corresponding to the select statement is empty, it will return as follows:
mysql> insert into tbl1 select * from empty_tbl;Query OK, 0 rows affected (0.02 sec)Query OKindicates successful execution.0 rows affectedmeans that no data was imported. -
The execution is successful, the result set is not empty
When the query returns rows, inspect the returned status information:
-
Insert executes successfully and is visible:
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'}Query OKindicates successful execution.4 rows affectedmeans that a total of 4 rows of data were imported.2 warningsindicates the number of lines to be filtered.The response also includes status information:
{'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'}labelis the user-specified or automatically generated identifier for theINSERT INTOload job. Each load job has a unique label within its database.statusindicates whether the imported data is visible. Showvisibleif visible,committedif not visible.txnIdis the ID of the transaction for thisINSERTstatement.The
errfield shows some other unexpected errors.To find diagnostics for filtered rows, run:
show load where label="xxx";The URL in the returned result identifies the filtered-row diagnostics.
Invisibility of data is a temporary state, this batch of data will eventually be visible
You can view the visible status of this batch of data with the following statement:
show transaction where id=4005;If the
TransactionStatuscolumn in the returned result isvisible, the imported data is visible.
-
-
Execution failed
Execution failure indicates that no data was successfully imported, and the following is returned:
mysql> insert into tbl1 select * from tbl2 where k1 = "a";ERROR 1064 (HY000): all partitions have no load data. url: http://10.74.167.16:8042/api/_load_error_log?file=__shard_2/error_log_insert_stmt_ba8bb9e158e4879-ae8de8507c0bf8a2_ba8bb9e158e4879_ae8de8507c0ERROR 1064 (HY000): all partitions have no load dataidentifies the failure. To inspect diagnostics using the URL returned in the error, run:show load warnings on "url";You can view the specific error line.
-
-
Timeout time
The timeout for an
INSERToperation is governed bymax(insert_timeout, query_timeout). Both are environment variables, withinsert_timeoutdefaulting to 4 hours andquery_timeoutdefaulting to 5 minutes. If the operation exceeds the timeout, the job will be canceled. The introduction ofinsert_timeoutis to ensure thatINSERTstatements have a longer default timeout, allowing import tasks to be unaffected by the shorter default timeout typically applied to regular queries. -
Label and atomicity
INSERTloads are atomic. See Import transactions and atomicity.When using
CTE(Common Table Expressions)as the query part in an insert operation, theWITH LABELandcolumnparts must be specified. -
Filter threshold
INSERTuses the session variableinsert_max_filter_ratioto control the filter threshold, rather than the load propertymax_filter_ratio. Its range is 0 to 1, its reference default is 1.0, and it takes effect only whenenable_insert_strict = false. It applies toINSERT INTO ... VALUESandINSERT INTO ... SELECT, including queries over internal tables, external tables, and file TVFs. The statement fails whenfiltered_rows / (loaded_rows + filtered_rows)exceeds this value.To reject any filtered data, set the session variable
enable_insert_stricttotrue(the reference default).INSERTthen fails if any row is filtered. The filter threshold does not suppress other execution errors, such as SQL analysis errors or data source access failures. -
Performance issues
There is no single row insertion using the
VALUESmethod. If you must use it this way, combine multiple rows of data into one INSERT statement for bulk commit.