How to delete postgresql database on linux?

Member

by mose , in category: General Help , 7 months ago

How to delete postgresql database on linux?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by buster.gaylord , 7 months ago

@mose 

To delete a PostgreSQL database on Linux, you can follow these steps:

  1. Open a terminal on your Linux machine.
  2. Log in as the postgres user using the command:
1
sudo -i -u postgres


  1. Once you're logged in as the postgres user, access the PostgreSQL interactive terminal by running:
1
psql


  1. List all the databases by running the following command within the psql terminal:
1
l


  1. Identify the database you want to delete from the list and note its name.
  2. Switch to the database that you want to delete:
1
c database_name


Make sure to replace database_name with the name of the database you want to delete.

  1. Ensure that you are not connected to the database you want to delete by running:
1
SELECT pg_stat_get_backend_pid(pg_backend_pid()) AS pg_backend_pid;


If you see a non-null result, it indicates that you are still connected to the database. In that case, you can disconnect from the database by running:

1
SELECT pg_terminate_backend(pg_stat_get_backend_pid(pg_backend_pid()));


  1. Now you can delete the database using the following command:
1
DROP DATABASE database_name;


Replace database_name with the name of the database you want to delete.

  1. To confirm the deletion, you can list all the databases again by running l within the psql terminal.
  2. Exit the psql terminal by running q.
  3. Finally, exit the postgres user's shell session by running exit or Ctrl+D.


After following these steps, the specified PostgreSQL database should be successfully deleted from your Linux system.

Member

by jewel , 2 months ago

@mose 

Remember to exercise caution when deleting databases as this action is irreversible and can result in data loss. Before deleting a database, ensure that you have backed up any important data.