Managing databases involves two critical skills: Safety (Backups) and Cloning (Copying). In PostgreSQL, these tasks are primarily handled through the command line using utilities like pg_dump and psql.
pg_dump)A backup creates a text file containing the SQL commands necessary to reconstruct the database to the exact state it was in at the time of the backup.
pg_dump -U username -d dbname > backup_file.sql-U: Specifies the database user (e.g., postgres).-d: The name of the database you want to back up.> : Redirects the output into a file.psql)Restoring involves running the SQL script generated by the backup against a fresh database.
CREATE DATABASE new_db;psql -U username -d new_db < backup_file.sqlSometimes you need to duplicate a database on the same server (e.g., creating a “test” version of a “production” database). PostgreSQL makes this easy with the TEMPLATE clause.
SQL Syntax:
CREATE DATABASE destination_db
WITH TEMPLATE source_db;
Note: You must disconnect all users from the
source_dbbefore running this command, or the copy will fail.
Complete these tasks to master the workflow. Assume your username is postgres.
school_db.students with columns for id and name.school_db to a file named school_backup.sql.school_db database (DROP DATABASE school_db;).school_recovered.school_backup.sql into school_recovered. Verify the students are still there.school_recovered.TEMPLATE command to create a copy of school_recovered named school_test.SUPERUSER or CREATEDB privileges.bin folder (e.g., C:\Program Files\PostgreSQL\16\bin) in your command prompt to run pg_dump.SELECT pg_terminate_backend(pg_stat_activity.pid)
FROM pg_stat_activity
WHERE pg_stat_activity.datname = 'source_db_name'
AND pid <> pg_backend_pid();