Inserting multiple rows into a database table is a common task when working with relational databases. While it’s possible to use separate INSERT statements for each row, this approach can be inefficient and lead to performance issues. Fortunately, most modern databases support inserting multiple rows using a single SQL query.
Introduction to Multi-Row Inserts
A multi-row insert statement allows you to add multiple records to a table in a single operation. This is achieved by specifying multiple sets of values for the columns, separated by commas. The basic syntax for a multi-row insert statement is as follows:
INSERT INTO table_name (column1, column2, ...)
VALUES
(value1, value2, ...),
(value3, value4, ...),
...
Example Usage
Let’s consider an example where we want to insert four rows into a table called MyTable
with columns Person
, Id
, and Office
. We can use the following SQL statement:
INSERT INTO MyTable (Person, Id, Office)
VALUES
('John', 123, 'Lloyds Office'),
('Jane', 124, 'Lloyds Office'),
('Billy', 125, 'London Office'),
('Miranda', 126, 'Bristol Office');
This statement will insert all four rows into the MyTable
table in a single operation.
Limitations and Workarounds
Some databases have limitations on the number of rows that can be inserted using a multi-row insert statement. For example, SQL Server has a limit of 1,000 rows. If you need to insert more than this, you can use a derived table in a SELECT statement instead:
INSERT INTO MyTable (Person, Id, Office)
SELECT Person, Id, Office
FROM (
VALUES ('John', 123, 'Lloyds Office'),
('Jane', 124, 'Lloyds Office'),
...
('Sally', 10026, 'Bristol Office')
) AS V(Person, Id, Office);
This approach allows you to insert an arbitrary number of rows without hitting the row limit.
Best Practices
When using multi-row insert statements, keep the following best practices in mind:
- Always specify the column names in the INSERT statement to ensure that the values are inserted into the correct columns.
- Use parentheses to enclose each set of values and separate them with commas.
- Be aware of any limitations on the number of rows that can be inserted using a multi-row insert statement, and use workarounds as needed.
By following these guidelines and using multi-row insert statements effectively, you can improve the performance and efficiency of your database operations.