简体   繁体   中英

pg_dump INSERTS to SQL file sorted by primary key

I'm extracting a table from a database using the following command:

pg_dump -U postgres --column-inserts --data-only --table=<mytable> <mydb> > <mytablev2>.sql

This creates an .sql file of INSERT statements to recreate my table. The only issue I am having is that it is not sorting the data in the order of the primary key. This is a newer version of a table and I would like my rows to be in primary key order for the sake of tracking changes between versions a lot easier. Is it possible to do this?

For efficiency's sake pg_dump just dumps the data based on how it is stored on disk. This indeed makes it difficult if you want to sort your dump files or track changes with something like diff . I think the only way to achieve this is if you create another table with the sorted values:

postgres=# create table teller2 as SELECT * FROM pgbench_tellers order by tid;
SELECT 10
postgres=# \q
-bash-4.2$ pg_dump -U postgres --column-inserts --data-only --table=teller2    
<...snip...>
INSERT INTO public.teller2 (tid, bid, tbalance, filler) VALUES (1, 1, -58378, NULL);
INSERT INTO public.teller2 (tid, bid, tbalance, filler) VALUES (2, 1, 160826, NULL);
INSERT INTO public.teller2 (tid, bid, tbalance, filler) VALUES (3, 1, 21714, NULL);
INSERT INTO public.teller2 (tid, bid, tbalance, filler) VALUES (4, 1, -74568, NULL);
INSERT INTO public.teller2 (tid, bid, tbalance, filler) VALUES (5, 1, 21023, NULL);
INSERT INTO public.teller2 (tid, bid, tbalance, filler) VALUES (6, 1, -80872, NULL);
INSERT INTO public.teller2 (tid, bid, tbalance, filler) VALUES (7, 1, -26181, NULL);
INSERT INTO public.teller2 (tid, bid, tbalance, filler) VALUES (8, 1, -78087, NULL);
INSERT INTO public.teller2 (tid, bid, tbalance, filler) VALUES (9, 1, 43505, NULL);
INSERT INTO public.teller2 (tid, bid, tbalance, filler) VALUES (10, 1, -225725, NULL);

I know this might not scale well when you're dealing with millions of rows. The only other options I can think of require a bit more coding and low-level knowledge of how Postgres works -- basically, I would suggest using pg_waldump or logical decoding to create some tool to track your changes (but that wouldn't satisfy your original question of how to sort pg_dump output).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM