SQL INSERT statement

An INSERT statement is the SQL command that adds rows to a table. It names the table and the columns being filled, then lists a value for each column, one row in brackets after another. Text values are quoted, numbers are written bare, and NULL means no value at all.

INSERT is how rows get into an SQL table. A generated file of INSERT statements is the most portable way to move data into a database: it needs no import wizard, runs in any SQL client, and can be read and checked before it is run.

The shape of one

INSERT INTO "customers" ("id", "name", "city") VALUES
  (1, 'Ada Lovelace', 'London'),
  (2, 'O''Brien', NULL);

The table comes first, then the columns in brackets, then one bracketed row per record. The values in each row line up with the column list, so a row with a value missing still needs a NULL in its place.

Quoting

Two kinds of quoting are involved and they are easy to confuse. Values that are text go in single quotes, with any single quote inside doubled. Names of tables and columns are quoted when they contain a space or are a reserved word such as order: standard SQL, PostgreSQL and SQLite use double quotes, and MySQL and MariaDB use backticks unless their ANSI_QUOTES mode is on. MySQL and MariaDB also read a backslash in a string as an escape by default, so a generator writing for them doubles it.

Types

Whether a value is quoted depends on the column it goes into. A number column takes 42 bare; a text column takes ‘42’ in quotes. A generator therefore has to decide each column’s type before writing a single row, and a CREATE TABLE written alongside the INSERT statements makes that decision visible, so it can be checked before anything is loaded.

Frequently asked questions

Why are quotes doubled inside a value?

A single quote ends an SQL string, so a value that contains one, such as O'Brien, writes it twice, 'O''Brien'. Without that, the rest of the value would be read as SQL, which is both a syntax error and how SQL injection works.

Why put many rows in one statement?

It is faster to load. Each statement has a cost of its own, so a thousand rows in ten statements of a hundred load much faster than a thousand statements of one. Very large statements can hit a database's size limit, which is why they are written in batches.

What is the difference between NULL and an empty string?

NULL means no value. An empty string is a value that happens to be empty. COUNT of a column skips NULL and counts empty strings, and a NOT NULL column accepts an empty string but refuses NULL.