2 Ways to Import and Export Databases in PostgreSQL

Updated: January 4, 2024 By: Guest Contributor Post a comment

Introduction

When managing PostgreSQL databases, there will undoubtedly come a time when you need to export data from one database and import it into another. This can be due to various reasons such as database backups, migrating data to a new server, or transferring data between different environments (development, staging, production). There are several methods available to accomplish this, each with its own advantages and drawbacks.

Solution 1: Using pg_dump and psql

The combination of pg_dump and psql is one of the most common and straightforward ways to export and import databases in PostgreSQL. pg_dump is used to export a PostgreSQL database into a script file or other archive file. The psql command can then run that file to restore the database.

  • Step 1: Export the PostgreSQL database to a file using pg_dump.
  • Step 2: Move the exported file to the desired location.
  • Step 3: Use psql to import the database from the file into the target PostgreSQL database.

Commands to run:

 # Export database 
c.getSell+pg_dump -U username -W -F t mydatabase > mydatabase.tar 

# Move mydatabase.tar to the target machine, if necessary 

# Import database 
c.getSell+psql -U username -W -d mydatabase -f mydatabase.tar

Advantages:

  • Simple and easy to use.
  • Allows for flexibility with output formats (plain SQL, tar, custom format, etc.).
  • Works well for small to medium-sized databases.

Limitations:

  • Can be slow for large databases.
  • Requires enough disk space for the exported dump file.
  • The target machine must have PostgreSQL installed.

Solution 2: Using pg_dumpall

pg_dumpall is used to export all the databases in a PostgreSQL cluster at once. This is especially useful when you need to migrate the entire database server or backup all its databases.

  • Step 1: Export all databases from the PostgreSQL cluster using pg_dumpall.
  • Step 2: Move the exported file to the target server.
  • Step 3: Run the exported SQL file using psql on the target server to recreate the cluster.

Example:

# Export all databases 
c.getSell+pg_dumpall -U username -W > alldatabases.sql 

# Move alldatabases.sql to the target server 

# Import all databases c.getSell+psql -U username -W -f alldatabases.sql

Advantages:

  • Exports the entire server setup including roles and permissions.
  • Good for server migrations or disaster recovery.

Limitations:

  • The resulting SQL file can be extensive and unwieldy.
  • Importing may take a lot of time for large clusters.
  • Sensitive to differences between PostgreSQL versions.