Overview
TheINSERT INTO
statement adds new rows to an existing table using a SELECT
statement or explicitly stating input values.
Syntax
The basic syntax forINSERT INTO
is as follows:
table_name
: The table name.(columns_order)
: Optional column order in the table.select_statement
: ASELECT
statement that provides the data to insert. For example,SELECT (value 1), (value 2), ... (value n);
.
Examples
Case #1: Basic Usage
Let’s create a distance table.Case #2: Switching Column Orders
In this example, we create aweight
table with columns kilo
and gram
. Then, we add data using the default column order (kilo
, gram
).
gram
, kilo
).
Case #3: Inserting with a NULL Column
In this case, we only insert data into agram
column while leaving the kilo
column as NULL.
kilo
) as NULL.
Case #4: Error Handling - Too Many Values
In this case, an error occurs when attempting to insert more values than the specified columns in the table.weight
has only 2 columns.
Case #5: Error Handling - Inserting NULL into a Not-Nullable Column
In this example, you insert data into agram
column and a NULL value into a kilo
column.
gram
column, leaving the kilo
column empty, where there is a NOT NULL constraint.