Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/scripts/postgresql/delete-in-batches.sql
1381 views
1
-- This is for the old patches table, but can be handy for other tables.
2
-- run psql and the just copy/paste this.
3
-- Expected output (about 2 seconds per line ...)
4
-- NOTICE: Deleted 10000 rows in 00:00:00.688278. Delay 1.376556
5
-- NOTICE: Deleted 10000 rows in 00:00:00.589805. Delay 1.17961
6
-- NOTICE: Deleted 10000 rows in 00:00:00.645825. Delay 1.29165
7
-- [...]
8
9
DO $$
10
DECLARE
11
rows_deleted INTEGER;
12
start_time TIMESTAMP;
13
elapsed_time INTERVAL;
14
delay DOUBLE PRECISION;
15
BEGIN
16
LOOP
17
-- Record start time
18
start_time := clock_timestamp();
19
20
-- Perform the deletion
21
DELETE FROM patches WHERE time <= (SELECT time FROM patches ORDER BY time ASC LIMIT 1 OFFSET 9999);
22
23
-- Get number of rows deleted
24
GET DIAGNOSTICS rows_deleted = ROW_COUNT;
25
26
-- Calculate elapsed time
27
elapsed_time := clock_timestamp() - start_time;
28
29
-- Exit loop if no rows were deleted
30
EXIT WHEN rows_deleted = 0;
31
32
-- Commit the transaction
33
COMMIT;
34
35
delay := 2 * EXTRACT(EPOCH FROM elapsed_time);
36
37
RAISE NOTICE 'Deleted % rows in %. Delay %', rows_deleted, elapsed_time, delay;
38
39
-- Wait for twice the elapsed time (in seconds)
40
PERFORM pg_sleep(delay);
41
END LOOP;
42
END $$;
43
44
45