w3resource

Step-by-Step Guide to Dropping a Database in PostgreSQL


Deleting a PostgreSQL Database: The DROP DATABASE Command

The DROP DATABASE command in PostgreSQL is used to delete a database permanently from a PostgreSQL server. This operation removes the database along with its associated files and cannot be undone. This guide explains the syntax, prerequisites, examples, and precautions for using DROP DATABASE.


Syntax:

DROP DATABASE [IF EXISTS] database_name;

Parameters

  • IF EXISTS: Prevents an error if the specified database does not exist.
  • database_name: The name of the database to be dropped.

Prerequisites

    1. You must have the SUPERUSER role or ownership of the database.

    2. No active connections should exist to the database you want to drop.

Examples

1. Basic Usage

Code:

-- Drop a database named 'test_db'
DROP DATABASE test_db;

2. Use IF EXISTS

Code:

-- Safely drop the database only if it exists
DROP DATABASE IF EXISTS demo_db;

3. Check and Terminate Active Connections

Before dropping a database, terminate active connections to it:

Code:

-- Connect to the postgres database (not the target)
\c postgres

-- Terminate connections to the target database
SELECT pg_terminate_backend(pg_stat_activity.pid)
FROM pg_stat_activity
WHERE pg_stat_activity.datname = 'test_db'
  AND pid <> pg_backend_pid();

-- Now drop the database
DROP DATABASE test_db;

Explanation:

    1. Command Execution: The DROP DATABASE command removes the database files and metadata.

    2. Active Connections: PostgreSQL does not allow dropping a database with active connections. Use the pg_terminate_backend() function to terminate these connections.

    3. Safety with IF EXISTS: Adding the IF EXISTS clause prevents runtime errors if the database is absent.

Precautions

  • Data Loss: Once dropped, the database and its data are unrecoverable unless backed up.
  • Backup: Always back up the database using tools like pg_dump before dropping.
  • Connection Issues: Ensure no critical connections exist before using pg_terminate_backend().

Backup Before Dropping

Code:

# Back up the database to a file
pg_dump -U username -F c -f test_db_backup.dump test_db

Use Cases

  • Deleting outdated or unused databases to free resources.
  • Removing test or temporary databases after development.

All PostgreSQL Questions, Answers, and Code Snippets Collection.



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/postgres-drop-database.php