DEV Community

Divine Ayerume
Divine Ayerume

Posted on

How to restore a postgreSQL database using command line

In this article, I will be talking about One of the quickest ways to restore a database backup file on postgresql. When working with a new database file, it is more convenient to use the command line to restore the database, especially if the file is large so as to reduce query execution time.

1. Locating the database file
The first step is determine the location of the ".sql" file on your computer and change the directory in command line to the folder containing the database. In the example below we'll be using the "store.sql" database which is located in downloads. To change the directory you type "cd" followed by the file path then press Enter to switch to the new directory.

Changing command line directory to the location of the database


2. Running the postgresql application in command line
After switching to the directory containing the database file, the next step is to run the postgersql executable file "psql.exe" in command line so that the database will be inserted through postgresql. to do this you have to copy the file path that contains the "psql.exe" file and the paste it in the command line wrapped up in quotes, this is to let the command line know that it should be run together.

Running the psql executable file in command line


3. Creating the database in PostgreSQL
The next step is to create a database, this is the database that will house the backup file and this can be done using pgadmin. For this example we will create a database and name it "Store".

creating a database on pdadmin


4. Upload the backup database file into the created database
The last step is to upload the ".sql" file into the database that was created with pgadmin. to do this, following the line of code in step 2, you have to indicate the user "-U username" and the database "-d database_name". In this example the user is "postgres" which is the same as the "owner" from the picture in step 3, and the database_name is "Store", created in the previous step. once the user and the database have been indicated, you type "<" followed by the file name "store.sql" then press Enter to upload the database. you will the be prompted to input your user password and after the password has been correctly inputted, the backup file will be uploaded into the database.

Uploading the backup file to the created database

Top comments (1)

Collapse
 
andrewbaisden profile image
Andrew Baisden

Really useful tutorial.