🔥 Articles, eBooks, Jobs, Columnist, Forum, Podcasts, Courses 🎓

How to create an SQL to do multiple inserts in one statement? | ecode10.com


How to create an SQL to do multiple inserts in one statement?

Practical examples

image

To insert multiple rows in a single SQL statement, use a single INSERT INTO command followed by the VALUES keyword and multiple comma-separated sets of values, each enclosed in parentheses.

This method is supported by most modern SQL database systems (MySQL, PostgreSQL, SQLite, SQL Server 2008 and later) and is more efficient than executing multiple single-row insert statements.

Syntax

SQL

INSERT INTO table_name (column1, column2, column3)
VALUES
    (value1_row1, value2_row1, value3_row1),
    (value1_row2, value2_row2, value3_row2),
    (value1_row3, value2_row3, value3_row3),
    ...;
  • table_name: The name of the table you are inserting into.

  • column1, column2, column3: The names of the columns you are providing data for. These can be omitted if you are providing values for all columns in the table in the correct order.

  • (value1, value2, value3): Each parenthesized list of values represents a single row to be inserted.

  • ,: Commas are used to separate each row's values set.

Example

To insert multiple employee records into an Employees table: SQL

INSERT INTO Employees (EmployeeName, Age, Department)
VALUES
    ('John Doe', 30, 'Sales'),
    ('Jane Smith', 25, 'Marketing'),
    ('Peter Jones', 40, 'Engineering');

Alternative Methods

  • INSERT INTO ... SELECT: This method is used to insert multiple rows by selecting data from another table or a derived table. This approach can be useful for inserting more than 1,000 rows in SQL Server, which has a limitation on the number of value sets in the VALUES clause.

  • BULK INSERT: For very large data imports from external files (like CSV), the BULK INSERT command (in SQL Server) or COPY command (in PostgreSQL) is the most performant method.





Related articles




Top