Skip to content
Share on
Updated

Overview

The commands in this guide target PostgreSQL 18 clients and servers. This guide describes how you can export data from and import data into a PostgreSQL database. You can learn more about this topic in the official PostgreSQL docs.

Data export with pg_dump

pg_dump is a native PostgreSQL utility you can use to export data from your PostgreSQL database. To see all the options for this command, run:

pg_dump --help

pg_dump creates a consistent logical snapshot of one database while other clients keep using it. Its role needs permission to read the objects being dumped. It does not include cluster-wide roles or tablespaces; preserve those separately when your recovery plan requires them. Use a client version compatible with the source server; an older pg_dump cannot dump a newer major server version. See the client compatibility rules.

The basic syntax of the command looks like this:

pg_dump DB_NAME > OUTPUT_FILE

You need to replace the DB_NAME and OUTPUT_FILE placeholders with the respective values for:

  • your database name
  • the name of the desired output file (should end in .sql for best interoperability)

For example, to export data from a database called mydb on a local PostgreSQL server into a file called mydb.sql, you can use the following command:

pg_dump mydb > mydb.sql

Ordinary oid-valued columns are dumped without a special option. Historical per-row OIDs were removed in PostgreSQL 12, and modern pg_dump has no --oids option. OID values that identify objects in another database are not automatically valid there; verify their meaning after restoring.

Prisma Postgres

Let Prisma Postgres handle the operations

Prisma Postgres provisions a fully managed Postgres database with automated backups and connection pooling — so you can focus on your app, not the infrastructure.

Providing database credentials

You can add the following arguments to specify the location of your PostgreSQL database server:

ArgumentDefaultEnv varDescription
--host (short: -h)Unix socket on Unix; localhost on WindowsPGHOSTThe address of the server's host machine
--port (short: -p)-PGPORTThe port of the server's host machine where the PostgreSQL server is listening

To authenticate against the PostgreSQL database server, you can use the following argument:

ArgumentDefaultEnv varDescription
--username (short: -U)your current operating system user namePGUSERThe name of the database user.

For a remote server, use the verified TLS connection settings and a password prompt or protected password file. This template uses obvious placeholders and omits a password:

pg_dump --dbname='host=db.example.test port=5432 user=backup_user dbname=applicationdb sslmode=verify-full sslrootcert=/path/to/provider-ca.pem' --file=backup.sql

pg_dump prompts when the server requires a password and none is supplied by another mechanism. For automation, propagate its nonzero exit status and do not promote a partially written file to a valid backup. A successful dump still needs a restore test.

Controlling the output

There might be cases where you don't want to dump the entire database, for example you might want to:

  • dump only the actual data but exclude the DDL (i.e. the SQL statements that define your database schema like CREATE TABLE,...)
  • dump only the DDL but exclude the actual data
  • exclude a specific PostgreSQL schema
  • exclude large files
  • exclude specific tables

Here's an overview of a few command line options you can use in these scenarios:

ArgumentDefaultDescription
--data-only (short: -a)falseExclude any DDL statements and export only data.
--schema-only (short: -s)falseExclude data and export only DDL statements.
--large-objects (short: -b)true unless the --schema, --table, or --schema-only options are specifiedInclude binary large objects.
--no-large-objects (short: -B)falseExclude binary large objects.
--table (short: -t)includes all tables by defaultExplicitly specify the names of the tables to be dumped.
--exclude-table (short: -T)-Exclude specific tables from the dump.

Importing data from SQL files

Restore only dumps you trust: restoring can execute SQL chosen by the source database's owners. Use an isolated empty destination before touching an application database.

After having used SQL Dump to export your PostgreSQL database as a SQL file, you can restore the state of the database by feeding the SQL file into psql:

psql -X -v ON_ERROR_STOP=1 -d DB_NAME -f INPUT_FILE

You need to replace the DB_NAME and INPUT_FILE placeholders with the respective values for:

  • your database name (a database with that name must be created beforehand!)
  • the name of the target input file (likely ends with .sql)

To create the database DB_NAME beforehand, you can use the template0 (which creates a plain user database that doesn't contain any site-local additions):

CREATE DATABASE restoredb TEMPLATE template0;

For a plain SQL dump from the local mydb example, restore into the empty restoredb database:

psql -X -v ON_ERROR_STOP=1 -d restoredb -f mydb.sql

-X ignores startup customizations and ON_ERROR_STOP=1 makes statement errors return a failing process status. Ensure your shell or job runner treats that failure as a failed restore. Statements before the error may already have committed. --single-transaction is an optional atomic path only for scripts whose statements can run inside one transaction; scripts containing CREATE DATABASE, for example, cannot.

Archive formats and restore verification

A custom-format dump is restored with pg_restore, not psql. For a separate empty destination named archive_restore:

createdb -T template0 archive_restore
pg_dump -Fc --file=mydb.dump mydb
pg_restore --exit-on-error --dbname=archive_restore mydb.dump

After either restore, verify the schema, expected row counts and business invariants, foreign keys and unique constraints, and the next value of each sequence or identity column. Run application reads and writes with its normal restricted role. Process completion alone does not prove the database is usable.

Conclusion

Exporting data from PostgreSQL and ingesting it again to recreate your data structures and populate databases is a good way to migrate data, back up and recover, or prepare for replication. Understanding how the pg_dump and psql tools work together to accomplish this task will help you transfer data across the boundaries of your databases.

Create a managed Postgres database

Hosted Postgres with automated backups, connection pooling, and Query Insights — ready in seconds.

About the author
Justin Ellingwood

Justin Ellingwood

Justin has been writing about databases, Linux, infrastructure, and developer tools since 2013. He currently lives in Berlin with his wife and two rabbits. He doesn't usually have to write in the third person, which is a relief for all parties involved.