SQL INSERT INTO

The SQL INSERT INTO Statement

The INSERT INTO statement is used to insert new records (rows) in a table.


Syntax

It is possible to write the INSERT INTO statement in two ways.

1. Specify both the column names and the values to be inserted:

In this form, you list the columns you want to fill and then provide the corresponding values. This is the recommended approach as it's more readable and less likely to break if the table structure changes.

INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);

2. Add values for all columns of the table:

If you are adding values for all the columns of the table, you do not need to specify the column names in the SQL query. However, make sure the order of the values is in the same order as the columns in the table.

INSERT INTO table_name
VALUES (value1, value2, value3, ...);

Warning: This second form is fragile. If the order or number of columns in the table changes, this statement will fail.


Demo Database

Below is the structure of the Customers table:

Customers Table:

CustomerID CustomerName ContactName Country

Example 1: Inserting a Full New Record

The following SQL statement inserts a new record into the Customers table. We specify all the values, so we don't need to list the column names.

INSERT Example

INSERT INTO Customers
VALUES (92, 'Cardinal', 'Tom B. Erichsen', 'Norway');

Example 2: Inserting Data in Specific Columns

It is also possible to only add data in specific columns. The following SQL statement will insert a new record, but only for the CustomerName and Country columns. The other columns (CustomerID, ContactName, etc.) will be filled with their default values (often NULL).

INSERT into Specific Columns

INSERT INTO Customers (CustomerName, Country)
VALUES ('Cardinal', 'Norway');

This is the more robust and preferred method for inserting data.