Inserts, NULLs and Cleanup

What is an insert statement?

An INSERT statement adds new rows to a table. Learn its syntax, how to insert several rows at once, and why it can't fill an empty column in existing rows.

On this page
  1. The short answer
  2. The parts of an INSERT
  3. Inserting several rows
  4. Columns you leave out
  5. Copying rows from a query
  6. What INSERT doesn’t do

The short answer

An INSERT statement adds one or more new rows to a table.

INSERT INTO customers (customer_id, name, city)
VALUES (101, 'Maria Lopez', 'Denver');

The parts of an INSERT

  • INSERT INTO customers names the table.
  • (customer_id, name, city) lists the columns that get values. Listing them keeps the statement working if someone adds a column to the table later.
  • VALUES (...) gives the values for one row, in the same order as the column list. Each value must fit its column’s data type.

Inserting several rows

Most major databases accept several rows in one VALUES list:

INSERT INTO customers (customer_id, name, city)
VALUES (102, 'Sam Chen', 'Austin'),
       (103, 'Priya Nair', 'Boise');

Columns you leave out

If you leave out a column, the database uses that column’s default value if it has one. Otherwise it stores NULL, provided the column allows NULL. If the column doesn’t allow NULL and has no default, the INSERT fails.

Copying rows from a query

INSERT ... SELECT takes its rows from a query instead of a VALUES list:

INSERT INTO denver_customers (customer_id, name, city)
SELECT customer_id, name, city
FROM customers
WHERE city = 'Denver';

Data warehouse loads often land rows in a temporary table first, the step described in what is staging in a database.

What INSERT doesn’t do

An INSERT adds rows and doesn’t change rows that already exist. To fill an empty column in rows you already have, use UPDATE, as covered in how to insert values in empty column in sql.

Some databases offer an option that updates a row when the insert clashes with an existing key, such as MySQL’s ON DUPLICATE KEY UPDATE or PostgreSQL’s ON CONFLICT clause. These are separate forms of the statement, so check your database’s manual before you use one.

The complete guide to inserts, nulls and cleanup

How to Insert Values Into an Empty Column in SQL
Read the guide

Keep exploring

Guides from other topics

All topics →