PostgreSQL INSERT Multiple Rows
Summary: in this tutorial, you will learn how to use the PostgreSQL INSERT
statement to insert multiple rows into a table.
Inserting multiple rows into a table
To insert multiple rows into a table using a single INSERT
statement, you use the following syntax:
In this syntax:
- First, specify the name of the table that you want to insert data after the
INSERT INTO
keywords. - Second, list the required columns or all columns of the table in parentheses that follow the table name.
- Third, supply a comma-separated list of rows after the
VALUES
keyword.
To insert multiple rows and return the inserted rows, you add the RETURNING
clause as follows:
Inserting multiple rows at once has advantages over inserting one row at a time:
- Performance: Inserting multiple rows in a single statement is often more efficient than multiple individual inserts because it reduces the number of round-trips between the application and the PostgreSQL server.
- Atomicity: The entire
INSERT
statement is atomic, meaning that either all rows are inserted, or none are. This ensures data consistency.
Inserting multiple rows into a table examples
Let’s take some examples of inserting multiple rows into a table.
Setting up a sample table
The following statement creates a new table called contacts
that has four columns id
, first_name
, last_name
, and email
:
1) Basic inserting multiple rows example
The following statement uses the INSERT
statement to insert three rows into the links
table:
PostgreSQL returns the following message:
To verify the inserts, you use the following statement:
Output:
2) Inserting multiple rows and returning inserted rows
The following statement uses the INSERT
statement to insert two rows into the contacts
table and returns the inserted rows:
Output:
If you just want to return the inserted id list, you can specify the id
column in the RETURNING
clause like this:
Output:
Summary
- Specify multiple value lists in the
INSERT
statement to insert multiple rows into a table. - Use
RETURNING
clause to return the inserted rows.