Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL: Drop PostgreSQL database through command line [closed]

I'm trying to drop my database and create a new one through the command line.

I log in using psql -U username and then do a \connect template1, followed by a DROP DATABASE databasename;.

I get the error

database databasename is being accessed by other users

I shut down Apache and tried this again but I'm still getting this error. Am I doing something wrong?

like image 270
iman453 Avatar asked Aug 16 '11 04:08

iman453


People also ask

How do I delete a PostgreSQL database?

The first method to remove a PostgreSQL database is to use the following SQL statement: DROP DATABASE <database name>; The command removes the directory containing the database information and the catalog entries. Only the database owner can execute the DROP DATABASE command.

How do I force delete a database in PostgreSQL?

A new command-line option is added to dropdb command, and a similar SQL option “FORCE” is also added in DROP DATABASE. Using the option -f or –force with dropdb command or FORCE with DROP DATABASE to drop the database, it will terminate all existing connections with the database.

How do I delete a pgAdmin database?

Deleting (Dropping) Databases in pgAdmin Fortunately, deleting (also known as dropping a table is super simple in pgAdmin / PostgreSQL. Below, in the interface, we right click the name of the newly created database and click “Delete/Drop”, and click Okay.

Can I drop default postgres database?

Basically - no. postgres database is here as a non-template database with reasonable guarantee that it exists - so any script that doesn't know where to connect to, can connect there. if you will remove template1 - you will lose the ability to create new databases (at least easily).


1 Answers

You can run the dropdb command from the command line:

dropdb 'database name' 

Note that you have to be a superuser or the database owner to be able to drop it.

You can also check the pg_stat_activity view to see what type of activity is currently taking place against your database, including all idle processes.

SELECT * FROM pg_stat_activity WHERE datname='database name'; 

Note that from PostgreSQL v13 on, you can disconnect the users automatically with

DROP DATABASE dbname WITH (FORCE); 

or

dropdb -f dbname 
like image 115
csano Avatar answered Nov 27 '22 07:11

csano