Sub topic 4
Inserting several rows in one statement
This chapter assumes you can write a single-row INSERT with a column list and that you know the customers and orders tables from the first chapter of this tutorial. Here you will add many rows with one statement, see how that statement succeeds or fails as a unit, and learn the limits that decide how big a batch can be.
The multi-row VALUES syntax
A single INSERT can carry more than one row. After VALUES, write one parenthesized group per row and separate the groups with commas.
INSERT INTO customers (id, name, email)
VALUES
(2, 'Grace Hopper', '[email protected]'),
(3, 'Alan Turing', NULL);The column list applies to every group. Each group must contain exactly as many values as the column list has columns, and the values are matched to columns by position. The statement above adds two rows. The status column is not listed, so both rows receive its default, 'active'.
You can check the result with a query:
SELECT id, name, email, status
FROM customers
ORDER BY id;If row 1 (Ada Lovelace) was inserted earlier, you now see three rows, all with status active. Alan Turing has a NULL email. NULL is allowed there because email is declared UNIQUE but not NOT NULL.
Rules for each row
- Same width. Every group needs the same number of values. A group with too few or too many causes a syntax or column-count error, and nothing is inserted.
- Types are checked per value. The text
'abc'in a numeric position fails the whole statement, even if it is in the last row. - NULL is a value you write explicitly. Writing
NULLin a position is different from leaving the column out of the list. Leaving a column out gives it its default. WritingNULLstores a missing value, and it fails on aNOT NULLcolumn even when that column has a default. - Order of rows is not guaranteed to mean anything. Do not rely on the rows receiving generated keys in the order you typed them, unless your database documents it.
One statement succeeds or fails as a unit
A single INSERT is atomic. Either every row in it is stored, or none is. This follows from how the database treats one statement: it checks constraints for all the new rows, and if any row breaks a rule, it undoes the statement's changes and returns an error.
Suppose customers already contains Ada with the email [email protected]. This statement has one valid row and one row that duplicates Ada's email:
INSERT INTO customers (id, name, email)
VALUES
(4, 'Katherine Johnson', '[email protected]'),
(5, 'Ada Clone', '[email protected]');The second row violates the UNIQUE constraint on email. The database rejects the statement, and Katherine Johnson is not inserted either. Afterwards, SELECT COUNT(*) FROM customers returns the same number as before.
This behavior is useful. You never end up with half of a batch and have to work out which half. It also means the error message may name only the first problem found, so after you fix one row, a later row can fail on the next attempt.
Dialect notes on atomicity
The rule above holds for PostgreSQL, SQL Server, SQLite, and MySQL with the InnoDB storage engine. Older MySQL tables that use the MyISAM engine have no transactions and can keep the rows inserted before the failure. Some dialects offer a way to skip bad rows instead of failing. MySQL has INSERT IGNORE, and PostgreSQL and SQLite have ON CONFLICT DO NOTHING. Both skip only certain conflicts, and they can hide mistakes, so use them on purpose and not as a habit. The last chapters of this tutorial cover conflict handling in detail.
Why batch rows
You could insert 1,000 rows with 1,000 single-row statements. A multi-row statement is usually faster, for three reasons:
- Fewer round trips. Each statement sent from an application travels to the server and back. One statement carrying 1,000 rows pays that cost once.
- Less parsing and planning. The server parses and plans one statement instead of 1,000.
- Fewer commits. In autocommit mode, which most databases use by default, each statement is its own transaction, and each commit forces the database to write its log to disk. One statement means one commit.
You can get the third benefit with single-row statements too, by wrapping them in one transaction (covered in a later chapter). Combining both is common: a transaction around a few multi-row statements.
| Approach | Round trips | Commits (autocommit) | Failure behavior |
|---|---|---|---|
| 1,000 single-row INSERTs | 1,000 | 1,000 | Earlier rows stay stored |
| One 1,000-row INSERT | 1 | 1 | All or nothing |
| 10 INSERTs of 100 rows | 10 | 10 | Earlier batches stay stored |
The table shows a trade-off: larger batches are faster, but a failure discards more work and a bigger statement is harder to debug.
Limits on batch size
Every database caps how large one statement can be. The cap depends on the dialect.
| Database | Limit to know |
|---|---|
| SQL Server | At most 1,000 row groups in one `VALUES` list. A statement can also carry at most 2,100 parameters. |
| PostgreSQL | At most 65,535 bind parameters per statement when you use placeholders. |
| MySQL | The whole statement must fit in `max_allowed_packet`. |
| SQLite | Multi-row `VALUES` works from version 3.7.11. Placeholders are capped by `SQLITE_MAX_VARIABLE_NUMBER`, which defaults to 32,766 from version 3.32. |
The parameter limits matter when an application builds the statement. Each value in each row uses one placeholder, so a table with 4 inserted columns reaches 65,535 placeholders at about 16,000 rows in PostgreSQL. A common practice is to insert in chunks of a few hundred to a few thousand rows. That stays below every limit and keeps a failed chunk cheap to retry.
Older Oracle versions do not accept multi-row VALUES and use INSERT ALL ... SELECT 1 FROM dual instead. Oracle 23ai accepts the standard syntax.
Common mistakes
- Missing comma between groups.
(2, 'Grace'...) (3, 'Alan'...)is a syntax error. The groups need a comma, and there must be no comma after the last one. - A trailing semicolon inside the list. Put the semicolon once, at the end of the statement.
- Mixing explicit and omitted columns across rows. Every row shares one column list. If one row needs a different set of columns, use a second statement.
- Reusing a primary key. Giving two rows in the same statement the same
idviolates the primary key. The database rejects the whole statement. - Assuming a partial insert. After an error, check with
SELECT. You should find that none of the statement's rows exist.
Trying it end to end
This script runs on PostgreSQL, MySQL, and SQLite. It starts with a clean customers table, inserts a batch, and then shows that a failing batch changes nothing.
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(255) UNIQUE,
status VARCHAR(20) NOT NULL DEFAULT 'active'
);
INSERT INTO customers (id, name, email)
VALUES
(1, 'Ada Lovelace', '[email protected]'),
(2, 'Grace Hopper', '[email protected]'),
(3, 'Alan Turing', NULL);
SELECT COUNT(*) FROM customers;
-- This statement fails: the second row repeats id 3.
INSERT INTO customers (id, name, email)
VALUES
(4, 'Katherine Johnson', '[email protected]'),
(3, 'Duplicate Id', '[email protected]');
SELECT COUNT(*) FROM customers;Both counts return 3. The failed statement left no trace, and Katherine Johnson is not in the table. In SQL Server the script also works, because it uses only syntax that SQL Server accepts.
Exercise
A table orders (id, customer_id, total, status) has status NOT NULL DEFAULT 'new'. You run INSERT INTO orders (id, customer_id, total, status) VALUES (10, 1, 5.00, 'new'), (11, 1, 7.50, NULL), (12, 2, 9.00, 'new');. How many rows are stored afterwards, and why?
Show answer
Zero rows. The second group writes an explicit NULL into a NOT NULL column, and the default is not applied to an explicit NULL. The statement fails as a unit, so rows 10 and 12 are not stored either. Omitting status from the column list (or using the DEFAULT keyword where supported) would give the second row 'new'.
Exercise
You need to insert 50,000 rows into SQL Server from an application that uses one row group per row. Why does a single statement not work, and what should you do?
Show answer
SQL Server allows at most 1,000 row groups in one VALUES list, and a statement can carry at most 2,100 parameters. Split the rows into chunks (for example 500 rows or fewer, fewer still if you use placeholders), and run the chunks inside one transaction so the whole load can be committed or rolled back together.