177

I'm looking for a way to get all rows as INSERT statements from one specific table within a database using pg_dump in PostgreSQL.

E.g., I have table A and all rows in table A I need as INSERT statements, it should also dump those statements to a file.

Is this possible?

l0b0
  • 55,365
  • 30
  • 138
  • 223
Elitmiar
  • 35,072
  • 73
  • 180
  • 229

5 Answers5

342

if version < 8.4.0

pg_dump -D -t <table> <database>

Add -a before the -t if you only want the INSERTs, without the CREATE TABLE etc to set up the table in the first place.

version >= 8.4.0

pg_dump --column-inserts --data-only --table=<table> <database>
dexter
  • 13,365
  • 5
  • 39
  • 56
psmears
  • 26,070
  • 4
  • 40
  • 48
  • 70
    The -d and -D options were removed from PostgreSQL 8.4 (see 8.4.0 release notes). You must now use the "long" names: pg_dump --column-inserts --data-only --table=
    – Matthew Wood May 18 '10 at 14:49
  • 1
    The `-d`, `-a`, and `-t` short versions are still present, though. Checked with PG11. – demisx Aug 23 '19 at 15:47
  • `--inserts` is another option; it restores slightly faster but can't tolerate column order changes – Andy Mar 29 '20 at 05:46
  • You can check postgres version by running the query `SELECT version();` – Tms91 Feb 10 '22 at 09:49
57

If you want to DUMP your inserts into an .sql file:

  1. cd to the location where you want the .sql file to be located
  2. Run the following command: pg_dump --column-inserts --data-only --table=<table> <database> > my_dump.sql

Note that the > my_dump.sql part of this command will put everything into an .sql file named my_dump

James111
  • 15,378
  • 15
  • 78
  • 121
8

just in case you are using a remote access and want to dump all database data, you can use:

pg_dump -a -h your_host -U your_user -W -Fc your_database > DATA.dump

it will create a dump with all database data and use

pg_restore -a -h your_host -U your_user -W -Fc your_database < DATA.dump

to insert the same data in your data base considering you have the same structure

Lenon Tolfo
  • 359
  • 4
  • 9
3

Put into a script I like something like that:

#!/bin/bash
set -o xtrace # remove me after debug
TABLE=some_table_name
DB_NAME=prod_database

BASE_DIR=/var/backups/someDir
LOCATION="${BASE_DIR}/myApp_$(date +%Y%m%d_%H%M%S)"
FNAME="${LOCATION}_${DB_NAME}_${TABLE}.sql"

# Create backups directory if not exists
if [[ ! -e $BASE_DIR ]];then
       mkdir $BASE_DIR
       chown -R postgres:postgres $BASE_DIR
fi

sudo -H -u postgres pg_dump --column-inserts --data-only --table=$TABLE $DB_NAME > $FNAME
sudo gzip $FNAME
Pipo
  • 4,653
  • 38
  • 47
3

for postgres 12, this worked for me:

pg_dump -d <database> -t <table> > DATA.dump
suhailvs
  • 20,182
  • 14
  • 100
  • 98