This topic describes how to insert, update, and delete multiple data records of an ApsaraDB RDS for PostgreSQL instance at a time. These operations can reduce the number of interactions between your RDS instance and your application and increase the data processing capability of your RDS instance.
Insert multiple data records at a time
You can use one of the following methods to insert multiple data records at a time:
In this example, the following statement is used to create a test table named tbl1:
CREATE TABLE tbl1 (
id SERIAL PRIMARY KEY,
info TEXT,
crt_time TIMESTAMP
);
Method 1: Execute the INSERT INTO ... SELECT statement.
Sample statements
INSERT INTO tbl1 (id, info ,crt_time) SELECT GENERATE_SERIES(1,10000),'test',NOW();
SELECT COUNT(*) FROM tbl1;
Output
Method 2: Use the VALUES(),(),...(); function.
Sample statements
INSERT INTO tbl1 (id,info,crt_time) VALUES (1,'test',NOW()), (2,'test2',NOW()), (3,'test3',NOW());
SELECT COUNT(*) FROM tbl1;
Output
Method 3: Run a BEGIN; ...Multiple INSERT statements...; END; transaction.
Note
This method allows you to include multiple INSERT statements in one transaction. This reduces the wait time on transaction commit, which in turn improves the performance of your RDS instance.
Sample statements
BEGIN;
INSERT INTO tbl1 (id,info,crt_time) VALUES (1,'test',NOW());
INSERT INTO tbl1 (id,info,crt_time) VALUES (2,'test2',NOW());
INSERT INTO tbl1 (id,info,crt_time) VALUES (3,'test3',NOW());
END;
SELECT COUNT(*) FROM tbl1;
Output
Method 4: Use the COPY command.
Note
Compared with the INSERT statement, the COPY command is easy to use and can insert data at higher efficiency.
Sample statements
COPY tbl1 FROM stdin;
1 'test' '2023-01-01'
2 'test1' '2023-02-02'
\.
SELECT COUNT(*) FROM tbl1;
Output
Note
The available COPY functions vary based on the language driver that you use. For more information, see the following documentation:
Update multiple data records at a time
Sample statements
UPDATE tbl1 SET info=tmp.info from (VALUES (1,'new1'),(2,'new2'),(6,'new6')) AS tmp (id,info) WHERE tbl1.id=tmp.id;
SELECT * FROM tbl1;
Output
id | info | crt_time
3 | hello | 2017-04-24 15:31:49.14291
4 | digoal0123 | 2017-04-24 15:42:50.912887
5 | hello digoal | 2017-04-24 15:57:29.622045
1 | new1 | 2017-04-24 15:58:55.610072
2 | new2 | 2017-04-24 15:28:20.37392
6 | new6 | 2017-04-24 15:59:12.265915
(6 rows)
Delete multiple data records at a time