w3resource

How to import an SQL Dump into PostgreSQL?


Importing an SQL Dump into a PostgreSQL Database

To import an SQL dump file into a PostgreSQL database, you can use the psql command-line tool. This method is useful for restoring backups or migrating data from one PostgreSQL database to another. The SQL dump file typically contains the SQL statements required to recreate the database structure and insert data.

Syntax for Importing SQL Dump with psql

The basic syntax for importing an SQL dump into a PostgreSQL database is:

psql -U username -d database_name -f dump_file.sql

Method 1: Using the .pgpass File

Explanation:

  • -U username: Specifies the username for database access.
  • -d database_name: Names the database where the data will be imported.
  • -f dump_file.sql: Specifies the path to the SQL dump file.

Example Command:

Suppose you have an SQL dump file named backup.sql that you want to import into a PostgreSQL database named mydatabase using the user myuser. The command would look like this:

Example Code:

psql -U myuser -d mydatabase -f backup.sql

Explanation of the Command:

  • psql: Starts the PostgreSQL interactive terminal.
  • -U myuser: Specifies myuser as the username.
  • -d mydatabase: Specifies mydatabase as the target database.
  • -f backup.sql: Directs psql to read and execute commands from backup.sql.

Step-by-Step Code Example:

# Importing SQL dump into PostgreSQL

# Step 1: Ensure the target database exists (you can create it with createdb)
createdb -U myuser mydatabase

# Step 2: Import the SQL dump file into the database
psql -U myuser -d mydatabase -f backup.sql

Importing SQL Dump in a Docker Container

If you're working with PostgreSQL in a Docker container, the process is similar. Just run the psql command within the container.

Code:

docker exec -i container_name psql -U myuser -d mydatabase < backup.sql

Explanation:

  • docker exec -i container_name: Specifies the container to execute the command in.
  • psql -U myuser -d mydatabase: Connects to the specified PostgreSQL database.
  • < backup.sql: Redirects the content of backup.sql to psql.

Important Notes:

  • Permissions: Make sure the user has the necessary privileges on the target database.
  • Database Preparation: Ensure the target database exists before importing. Use createdb to create it if necessary.
  • Backup Compatibility: The SQL dump should be compatible with the PostgreSQL version in use for smooth import.


Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/PostgreSQL/snippets/import-sql-dump-into-postgresql-database.php