EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials PostgreSQL Tutorial Postgres Dump Database
Secondary Sidebar
PostgreSQL Tutorial
  • Basic
    • What is PostgreSQL
    • PostgreSQL Features
    • How to Install PostgreSQL
    • PostgreSQL Versions
    • PostgreSQL Architecture
    • PostgreSQL GUI
    • Postgres Command-Line
    • PostgreSQL Variables
    • PostgreSQL Data Types
    • PostgreSQL NOT NULL
    • PostgreSQL Integer
    • PostgreSQL Boolean
    • PostgreSQL BIGINT
    • PostgreSQL NULLIF
    • PostgreSQL Administration
    • PostgreSQL Commands
    • PostgreSQL Operators
    • PostgreSQL IN Operator
    • Postgres like query
    • PostgreSQL encode
    • PostgreSQL Cheat Sheet
    • PostgreSQL List Databases
    • PostgreSQL Rename Database
  • Control Statement
    • PostgreSQL IF Statement
    • PostgreSQL if else
    • PostgreSQL CASE Statement
    • PostgreSQL LOOP
    • PostgreSQL For Loop
    • PostgreSQL While Loop
  • Joins
    • Joins in PostgreSQL
    • PostgreSQL Inner Join
    • PostgreSQL Outer Join
    • LEFT OUTER JOIN in PostgreSQL
    • PostgreSQL FULL OUTER JOIN
    • PostgreSQL LEFT JOIN
    • PostgreSQL Full Join
    • PostgreSQL Cross Join
    • PostgreSQL NATURAL JOIN
    • PostgreSQL UPDATE JOIN
  • Queries
    • PostgreSQL Queries
    • PostgreSQL INSERT INTO
    • PostgreSQL WHERE Clause
    • PostgreSQL WITH Clause
    • PostgreSQL ORDER BY
    • PostgreSQL ORDER BY Random
    • PostgreSQL ORDER BY DESC
    • PostgreSQL GROUP BY
    • PostgreSQL group_concat
    • PostgreSQL HAVING
    • PostgreSQL Recursive Query
  • Advanced
    • PostgreSQL Schema
    • Postgres List Schemas
    • PostgreSQL Drop Schema
    • PostgreSQL VARCHAR
    • Array in PostgreSQL
    • PostgreSQL DDL
    • PostgreSQL List Users
    • Postgres Default User
    • Postgres add user
    • PostgreSQL User Password
    • PostgreSQL log_statement
    • PostgreSQL repository
    • PostgreSQL shared_buffer
    • PostgreSQL String Functions
    • PostgreSQL Compare Strings
    • PostgreSQL Text Search
    • PostgreSQL TEXT
    • PostgreSQL String Array
    • PostgreSQL where in array
    • PostgreSQL Constraints
    • PostgreSQL UNIQUE Constraint
    • PostgreSQL CHECK Constraint
    • PostgreSQL INTERSECT
    • PostgreSQL Like
    • Cursors in PostgreSQL
    • PostgreSQL UNION ALL
    • Indexes in PostgreSQL
    • PostgreSQL Index Types
    • PostgreSQL REINDEX
    • PostgreSQL UNIQUE Index
    • PostgreSQL Clustered Index
    • PostgreSQL DROP INDEX
    • PostgreSQL DISTINCT
    • PostgreSQL FETCH
    • PostgreSQL RAISE EXCEPTION
    • PostgreSQL Auto Increment
    • Sequence in PostgreSQL
    • Wildcards in PostgreSQL
    • PostgreSQL Subquery
    • PostgreSQL Alias
    • PostgreSQL LIMIT
    • PostgreSQL Limit Offset
    • PostgreSQL LAG()
    • PostgreSQL Table
    • Postgres Show Tables
    • PostgreSQL Describe Table
    • PostgreSQL Lock Table
    • PostgreSQL ALTER TABLE
    • Postgres Rename Table
    • PostgreSQL List Tables
    • PostgreSQL TRUNCATE TABLE
    • PostgreSQL Table Partitioning
    • Postgres DROP Table
    • PostgreSQL Functions
    • PostgreSQL Math Functions
    • PostgreSQL Window Functions
    • Aggregate Functions in PostgreSQL
    • PostgreSQL Primary Key
    • Foreign Key in PostgreSQL
    • PostgreSQL Procedures
    • PostgreSQL Stored Procedures
    • PostgreSQL Views
    • PostgreSQL Materialized Views
    • Postgres Create View
    • PostgreSQL Triggers
    • PostgreSQL DROP TRIGGER
    • PostgreSQL Date Functions
    • PostgreSQL TO_DATE()
    • PostgreSQL datediff
    • PostgreSQL Timestamp
    • PostgreSQL CURRENT_TIMESTAMP()
    • PostgreSQL Notify
    • PostgreSQL LENGTH()
    • PostgreSQL blob
    • PostgreSQL Median
    • PostgreSQL kill query
    • PostgreSQL Formatter
    • PostgreSQL RANK()
    • PostgreSQL Select
    • PostgreSQL Average
    • PostgreSQL DATE_PART()
    • PostgreSQL EXECUTE
    • PostgreSQL COALESCE
    • PostgreSQL EXTRACT()
    • PostgreSQL Sort
    • PostgreSQL TO_CHAR
    • PostgreSQL Interval
    • PostgreSQL Number Types
    • PostgreSQL ROW_NUMBER
    • Alter Column in PostgreSQL
    • PostgreSQL Identity Column
    • PostgreSQL SPLIT_PART()
    • PostgreSQL CONCAT()
    • PostgreSQL replace
    • PostgreSQL TRIM()
    • PostgreSQL MAX
    • PostgreSQL DELETE
    • PostgreSQL Float
    • PostgreSQL OID
    • PostgreSQL log
    • PostgreSQL REGEXP_MATCHES()
    • PostgreSQL MD5 
    • PostgreSQL NOW()
    • PostgreSQL RANDOM
    • PostgreSQL round
    • PostgreSQL Trunc()
    • PostgreSQL TIME
    • PostgreSQL IS NULL
    • PostgreSQL CURRENT_TIME
    • PostgreSQL MOD()
    • Postgresql Count
    • PostgreSQL Datetime
    • PostgreSQL MIN()
    • PostgreSQL age()
    • PostgreSQL enum
    • PostgreSQL OR
    • PostgreSQL Wal
    • PostgreSQL NOT IN
    • PostgreSQL SET
    • PostgreSQL Current Date
    • PostgreSQL Compare Date
    • PostgreSQL SERIAL
    • PostgreSQL UUID
    • PostgreSQL Merge
    • PostgreSQL Database
    • PostgreSQL Clone Database
    • PostgreSQL Copy Database
    • PostgreSQL Show Databases
    • PostgreSQL Restore Database
    • PostgreSQL DROP DATABASE
    • PostgreSQL ALTER DATABASE
    • Postgres DROP Database
    • Postgres Dump Database
    • PostgreSQL OFFSET
    • PostgreSQL GRANT
    • PostgreSQL COMMIT
    • PostgreSQL ROLLUP
    • PostgreSQL JSON
    • EXPLAIN ANALYZE in PostgreSQL
    • PostgreSQL Temporary Table
    • PostgreSQL Show Tables
    • PostgreSQL cluster
    • PostgreSQL Replication
    • PostgreSQL Logical Replication
    • PostgreSQL flush privileges
    • PostgreSQL Tablespaces
    • CAST in PostgreSQL
    • PostgreSQL CTE
    • hstore in PostgreSQL
    • PostgreSQL Encryption
    • PostgreSQL DECODE()
    • PostgreSQL Vacuum
    • PostgreSQL EXCLUDE
    • Postgres Change Password
    • Postgres Delete Cascade
    • PostgreSQL EXCEPT
    • PostgreSQL Roles
    • PostgreSQL Link
    • PostgreSQL Partition
    • PostgreSQL column does not exist
    • PostgreSQL Log Queries
    • PostgreSQL escape single quote
    • PostgreSQL Query Optimization
    • PostgreSQL Character Varying
    • PostgreSQL Transaction
    • PostgreSQL Extensions
    • PostgreSQL Import CSV
    • PostgreSQL Client
    • PostgreSQL caching
    • PostgreSQL Incremental Backup
    • PostgreSQL JSON vs JSONNB
    • PostgreSQL JDBC Driver
    • PostgreSQL Interview Questions

Postgres Dump Database

By Payal UdhaniPayal Udhani

Postgres Dump Database

Introduction to Postgres Dump Database

If you are using the PostgreSQL database in the production environment for your clients then you need to make sure that your database is always working fine and is available 24 * 7. For the availability of the database, you must often keep the backup of your client’s database. In case if the database is corrupted or is crashed or lost then you should be able to restore the data in the database. For this reason, PostgreSQL provides us with a facility to dump the database using pg_dump utility. The advantage of this utility is that it is not server-side version specific and can work even on the machine having different architectures. For example, if you dump your database from a 32-bit architecture machine and then use it in a 64-bit machine then it will work fine.

You must dump your database frequently to have the updated backup of your database available with you. Whenever the backup is restored the database will be back to the state when that dump file was being created using pg_dump. One more advantage of using the pg_dump utility instead of file-level backups and archiving is that it is not specific to the version of the PostgreSQL server.

Also, the database operations which are running while pg_sump are not locked and run in the background except some of the operations related to structural changes such as ALTER TABLE are blocked. You will have to specify external -o in the pg_dump command in case if your database schema depends on OIDs such as foreign keys. For this, you will also need to dump the OIDs.

Syntax:

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

pg_dump databaseName > outputFile

All in One Data Science Bundle(360+ Courses, 50+ projects)
Python TutorialMachine LearningAWSArtificial Intelligence
TableauR ProgrammingPowerBIDeep Learning
Price
View Courses
360+ Online Courses | 50+ projects | 1500+ Hours | Verifiable Certificates | Lifetime Access
4.7 (86,527 ratings)
  • pg_dump – It is the utility program that is provided in PostgreSQL to store the current state of the database into a file that will contain commands which when run on the database server will recreate the state of the database when it was dumped using the same. It is a client-side program and needs to be run through the Linux command line prompt.
  • databaseName – It is the name of the database which you want to dump.
  • outputFile – It is the name of the file which has to be created after the dumping is finished.

pg_dump process needs to be done only by the superuser login as it has permission to read all the databases and tables. Although, you do have a facility to dump the database remotely. By default, the environment variables PGHOST, PGPORT, and PGUSER are considered as the localhost,5432, and username using which you default to connect to database which is the same as the username of the operating system.

You can change the PGHOST and PGPORT by using the options -h for host and -p for the port in pg_dump command. To change and override the PGUSER variable you can use -U option in the statement. All this is confirmed using the client authentication mechanisms.

For example

pg_dump postgres > myBackupFile
ls

Check whether the file is created successfully. Let us use ls command which lists all the files in the current directory –

Postgres Dump Database 1

Now, our backup file which is dumped is ready with name myBackupFile.

Let us see the contents of the Postgres database by checking all its tables with the help of \dt command.

\c postgres
\dt

Postgres Dump Database 2

So, it contains three tables which we will drop one by one. By using the commands

drop table educba;
drop table teams cascade;
drop table developers;
\dt

and then further check whether all of them are deleted by \dt command.

Postgres Dump Database 3

So, now my database Postgres does not contain any tables in it. Now, we will learn how we can restore the data into the database.

Restoring the dump

Now, if we have a backup file, we can anytime restore the database in case if we want to and the database is corrupted or lost. However, you need to consider some things before restoring. The database which you are trying to restore should be present on the database server. If not then you should create the database with the help of the command

createdb -T template0 Postgres

in our case. As the database already exists which can be check by using the command \l which results in follow in by database server, we don’t need to execute the createdb command now.

\l

Postgres Dump Database 4

The other thing to make sure that the database which you are restoring should already consist of all the users who had right on it. In our case, the Postgres user is the owner of the Postgres database. Hence, or database server should already have a user named Postgres or else it will give an error while restoring. You can check this by firing the command –

SELECT usename FROM pg_catalog.pg_user;

which results in the following –

FROM 1

Now, as the Postgres database and Postgres user are already present in my database server. I can go for restoring the database using the command –

psql postgres < myBackupFile;

as the syntax of restoring the dump is

psql empty_database < backup_file

where empty_database is the database that you want to restore and backup_file is the file which was the resultant of the pg_dump command.

psql postgres < myBackupFile;

gives the output as follows.

FROM 2

Now, if we check the contents of the Postgres database using the command \dt it gives the output as –

FROM 3

Also, the contents of all the tables are restored correctly –

select * from developers;

FROM 4

Handling restoration errors

The PostgreSQL continues to restore the database even when any error is occurred in between. It only tells about them at the end of completion of restore. In this case, the database is restored incompletely. If you want to stop the restoration process on error occurrence, you can use –

psql --set ON_ERROR_STOP=on postgres < myBackupFile

ON_ERROR_STOP option helps you to stop the restoration process whenever the error occurs. Now, if you want to perform restoration in the transactional manner i.e either the whole database should be restored or nothing then you can use -1 or –single-transaction option to make it transactional process.

psql -1 postgres < myBackupFile

For dumping all the databases in the current database server to a file you can use pg_dumpall utility program and provide default database while restoration.

Conclusion: Postgres Dump Database

We can dump our database, so that backup is available in the near future to restore the database in case of any problem with data available from the database using pg_dump in PostgreSQL.

Recommended Articles

This is a guide to Postgres Dump Database. Here we discuss the introduction of Postgres Dump Database, syntax, parameters, and examples with code implementation. You may also have a look at the following articles to learn more –

  1. PostgreSQL Link
  2. PostgreSQL Query Optimization
  3. PostgreSQL Index Types
  4. PostgreSQL Roles
Popular Course in this category
PostgreSQL Course (2 Courses, 1 Project)
  2 Online Courses |  1 Hands-on Project |  7+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

SPSS, Data visualization with Python, Matplotlib Library, Seaborn Package

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more