Skip to main content

Overview

The INSERT INTO statement adds new rows to an existing table using a SELECT statement or explicitly stating input values.

Syntax

The basic syntax for INSERT INTO is as follows:
or
Where:
  • table_name: The table name.
  • (columns_order): Optional column order in the table.
  • select_statement: A SELECT 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.
We’ll then insert values representing different distance measurements.
Display the table using the query below.
You’ll get the following output.

Case #2: Switching Column Orders

In this example, we create a weight table with columns kilo and gram. Then, we add data using the default column order (kilo, gram).
Next, we insert data with a switched column order (gram, kilo).
Let’s see what’s on the table.
The output displays the first row with data from the default column order and the second row with reversed data from the switched column order.

Case #3: Inserting with a NULL Column

In this case, we only insert data into a gram column while leaving the kilo column as NULL.
Display the table.
The output shows the first column (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.
The error result indicates that 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 a gram column and a NULL value into a kilo column.
You will get an error result as you try to input data only in the gram column, leaving the kilo column empty, where there is a NOT NULL constraint.