Force drop db while others may be connectedUnable to force drop Postgres databaseDrop database from remote...

"Cheaper by the dozen" phrase origin?

Why did Tywin never remarry?

Ethernet cable only works in certain positions

Are there any rules or guidelines about the order of saving throws?

The Hilbert symbols of quaternion algebras over a totally real field

Found a major flaw in paper from home university – to which I would like to return

What happens to someone who dies before their clone has matured?

Workplace intimidation due to child's chronic health condition

How quickly could a motion be passed to alter minimum age for POTUS?

GPL - Is it required to post source code to the Public - when is a software released?

Why is it a problem for Freddie if the guys from Munich did what he wanted?

What happens if you declare more than $10,000 at the US border?

How to know if I am a 'Real Developer'

Would life expectancy increase if we replaced healthy organs with artificial ones?

finding the probability of an event, not equiprobable cases.

Why do climate experts from the UN/IPCC never mention Grand Solar Minimum?

Why don't hotels offer ≥ 1 kitchen that must be booked?

For US ESTA, should I mention a visa denial from before I got UK citizenship?

Is it possible to detect 100% of SQLi with a simple regex?

If an area is covered in both Ball Bearings and Caltrops, does the creature need to move at half speed or quarter speed to avoid both their effects?

How to explain one side of Super Earth is smoother than the other side?

Unable to login to ec2 instance after running “sudo chmod 2770 /”

How to have a different style for edges of a triangle

Python 3.7 UltimateBruteforcer



Force drop db while others may be connected


Unable to force drop Postgres databaseDrop database from remote that has connected usershow can i lock or disable connections to postgres DB while performing maintenance?Postgresql 9.4.1 stuck all queries when making multi updatesPostgres Administration rolesMake Postgres database temporarily read-only (for performing volume snapshots)PostgreSQL Drop Database With Connected UsersCan not drop a PostgreSQL database using dropdb?Dropped database still shows but causes errors PostgreSQLPostgreSQL ANALYZE execution time over 24h (still running)How do I detach all other users from a postgres database?How to drop all connections to a specific database without stopping the server?Drop and restore PostgresSQL database without losing settingsDrop database from remote that has connected usersPostgres drop type XX000 “cache lookup failed for type”Why does PostgreSQL require a database connection?PostgreSQL Drop Database With Connected Usershow to force postgresql to filll work_mem?how can i lock or disable connections to postgres DB while performing maintenance?Cannot remove idle connections to a Postgres database













90















I need to remove a database from a PostgreSQL DB cluster. How can I do it even if there are active connections? I need sort of a -force flag, that will drop all connections and then the DB.



How can I implement it?



I'm using dropdb currently, but other tools are possible.










share|improve this question





























    90















    I need to remove a database from a PostgreSQL DB cluster. How can I do it even if there are active connections? I need sort of a -force flag, that will drop all connections and then the DB.



    How can I implement it?



    I'm using dropdb currently, but other tools are possible.










    share|improve this question



























      90












      90








      90


      38






      I need to remove a database from a PostgreSQL DB cluster. How can I do it even if there are active connections? I need sort of a -force flag, that will drop all connections and then the DB.



      How can I implement it?



      I'm using dropdb currently, but other tools are possible.










      share|improve this question
















      I need to remove a database from a PostgreSQL DB cluster. How can I do it even if there are active connections? I need sort of a -force flag, that will drop all connections and then the DB.



      How can I implement it?



      I'm using dropdb currently, but other tools are possible.







      postgresql maintenance






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Feb 19 '15 at 22:24









      Erwin Brandstetter

      92.6k9176291




      92.6k9176291










      asked Jan 30 '12 at 11:28









      AlexAlex

      590177




      590177






















          4 Answers
          4






          active

          oldest

          votes


















          134














          In PostgreSQL*, you cannot drop a database while clients are connected to it.



          At least, not with the dropdb utility - which is only a simple wrapper around DROP DATABASE server query.



          Quite robust workaround follows:



          Connect to your server as superuser, using psql or other client. Do not use the database you want to drop.



          psql -h localhost postgres postgres


          Now using plain database client you can force drop database using three simple steps:





          1. Make sure no one can connect to this database. You can use one of following methods (the second seems safer, but does not prevent connections from superusers).



            /* Method 1: update system catalog */
            UPDATE pg_database SET datallowconn = 'false' WHERE datname = 'mydb';

            /* Method 2: use ALTER DATABASE. Superusers still can connect!
            ALTER DATABASE mydb CONNECTION LIMIT 0; */



          2. Force disconnection of all clients connected to this database, using pg_terminate_backend.



            SELECT pg_terminate_backend(pid)
            FROM pg_stat_activity
            WHERE datname = 'mydb';

            /* For old versions of PostgreSQL (up to 9.1), change pid to procpid:

            SELECT pg_terminate_backend(procpid)
            FROM pg_stat_activity
            WHERE datname = 'mydb'; */



          3. Drop the database.



            DROP DATABASE mydb;



          Step 1 requires superuser privileges for the 1st method, and database owner privileges for the 2nd one. Step 2 requires superuser privileges. Step 3 requires database owner privilege.





          * This applies to all versions of PostgreSQL, up to version 11.









          share|improve this answer


























          • So I don't know what I did wrong, but now I can't even connect to the database I targeted! Nor can I drop it as it says "Maintenance database cannot be dropped"

            – Matt Skeldon
            Jul 7 '17 at 5:32











          • @MattSkeldon, no idea what this message means. In vanilla PostgreSQL you can drop any database except template0 & template1. Maybe you use some non-free / commercial version? Maybe it's client issue not server issue? Did you try psql?

            – filiprem
            Jul 12 '17 at 19:05











          • Unfortunately I come from a SQL background, using PGSQL is being used owing to the non commercial / free status.

            – Matt Skeldon
            Jul 12 '17 at 19:09











          • This doesn't work for me where there are long-running zombie sessions. pg_terminate_backend() does not kill those sessions so I'm still a bit stuck about what to do: I am a Postgres su, but I don't have access to the server it's running on.

            – Alexander
            Mar 29 '18 at 16:25



















          6
















          There is a way to do this with the shell utilities dropdb & pg_ctl (or pg_ctlcluster in Debian and derivates). But @filiprem's method is superior for several reasons:




          • It only disconnects users from the database in question.

          • It does not need to restart the whole cluster.

          • It prevents immediate reconnects, possibly spoiling the dropdb command.


          I quote man pg_ctlcluster:




          With the --force option the "fast" mode is used which rolls back all active transactions, disconnects clients immediately and thus shuts down cleanly. If that does not work, shutdown is attempted again in "immediate" mode, which can leave the cluster in an inconsistent state and thus will lead to a recovery run at the next start. If this still does not help, the postmaster process is killed. Exits with 0 on success, with 2 if the server is not running, and with 1 on other failure conditions. This mode should only be used when the machine is about to be shut down.




          pg_ctlcluster 9.1 main restart --force


          or



          pg_ctl restart -D datadir -m fast


          or



          pg_ctl restart -D datadir -m immediate


          immediately followed by:



          dropdb mydb


          Possibly in a script for immediate succession.






          share|improve this answer





















          • 4





            Not only is this less than ideal as it kicks the full postgres instance but it is not guaranteed to work. It is possible for a client to connect between the time you restart the server and attempt to run dropdb again. @filiprem 's answer above disables all connections to the database prior to disconnecting and will keep other databases up.

            – Jim Mitchener
            Oct 22 '14 at 5:28



















          3














          Using @filiprem's answer in a my case and simplifying it:



          -- Connecting to the current user localhost's postgres instance
          psql

          -- Making sure the database exists
          SELECT * from pg_database where datname = 'my_database_name'

          -- Disallow new connections
          UPDATE pg_database SET datallowconn = 'false' WHERE datname = 'my_database_name';
          ALTER DATABASE my_database_name CONNECTION LIMIT 1;

          -- Terminate existing connections
          SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = 'my_database_name';

          -- Drop database
          DROP DATABASE my_database_name





          share|improve this answer































            0














            If you're on something like RDS where connections without a database selected put you into the DB you asked to be created by default you can do this variant to get around yourself being the last open connection.



             DROP DATABASE IF EXISTS temporary_db_that_shouldnt_exist; 

            CREATE DATABASE temporary_db_that_shouldnt_exist with OWNER your_user;

            connect temporary_db_that_shouldnt_exist
            SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = 'the_db_you_want_removed';


            DROP DATABASE IF EXISTS the_db_you_want_removed;
            --
            -- Name: the_db_you_want_removed; Type: DATABASE; Schema: -; Owner: your_user
            --

            CREATE DATABASE savings_champion WITH TEMPLATE = template0 ENCODING = 'UTF8' LC_COLLATE = 'en_US.UTF-8' LC_CTYPE = 'en_US.UTF-8';


            ALTER DATABASE the_db_you_want_removed OWNER TO your_user;

            connect the_db_you_want_removed

            DROP DATABASE IF EXISTS temporary_db_that_shouldnt_exist;





            share|improve this answer























              Your Answer








              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "182"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: false,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: null,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














              draft saved

              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f11893%2fforce-drop-db-while-others-may-be-connected%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              4 Answers
              4






              active

              oldest

              votes








              4 Answers
              4






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              134














              In PostgreSQL*, you cannot drop a database while clients are connected to it.



              At least, not with the dropdb utility - which is only a simple wrapper around DROP DATABASE server query.



              Quite robust workaround follows:



              Connect to your server as superuser, using psql or other client. Do not use the database you want to drop.



              psql -h localhost postgres postgres


              Now using plain database client you can force drop database using three simple steps:





              1. Make sure no one can connect to this database. You can use one of following methods (the second seems safer, but does not prevent connections from superusers).



                /* Method 1: update system catalog */
                UPDATE pg_database SET datallowconn = 'false' WHERE datname = 'mydb';

                /* Method 2: use ALTER DATABASE. Superusers still can connect!
                ALTER DATABASE mydb CONNECTION LIMIT 0; */



              2. Force disconnection of all clients connected to this database, using pg_terminate_backend.



                SELECT pg_terminate_backend(pid)
                FROM pg_stat_activity
                WHERE datname = 'mydb';

                /* For old versions of PostgreSQL (up to 9.1), change pid to procpid:

                SELECT pg_terminate_backend(procpid)
                FROM pg_stat_activity
                WHERE datname = 'mydb'; */



              3. Drop the database.



                DROP DATABASE mydb;



              Step 1 requires superuser privileges for the 1st method, and database owner privileges for the 2nd one. Step 2 requires superuser privileges. Step 3 requires database owner privilege.





              * This applies to all versions of PostgreSQL, up to version 11.









              share|improve this answer


























              • So I don't know what I did wrong, but now I can't even connect to the database I targeted! Nor can I drop it as it says "Maintenance database cannot be dropped"

                – Matt Skeldon
                Jul 7 '17 at 5:32











              • @MattSkeldon, no idea what this message means. In vanilla PostgreSQL you can drop any database except template0 & template1. Maybe you use some non-free / commercial version? Maybe it's client issue not server issue? Did you try psql?

                – filiprem
                Jul 12 '17 at 19:05











              • Unfortunately I come from a SQL background, using PGSQL is being used owing to the non commercial / free status.

                – Matt Skeldon
                Jul 12 '17 at 19:09











              • This doesn't work for me where there are long-running zombie sessions. pg_terminate_backend() does not kill those sessions so I'm still a bit stuck about what to do: I am a Postgres su, but I don't have access to the server it's running on.

                – Alexander
                Mar 29 '18 at 16:25
















              134














              In PostgreSQL*, you cannot drop a database while clients are connected to it.



              At least, not with the dropdb utility - which is only a simple wrapper around DROP DATABASE server query.



              Quite robust workaround follows:



              Connect to your server as superuser, using psql or other client. Do not use the database you want to drop.



              psql -h localhost postgres postgres


              Now using plain database client you can force drop database using three simple steps:





              1. Make sure no one can connect to this database. You can use one of following methods (the second seems safer, but does not prevent connections from superusers).



                /* Method 1: update system catalog */
                UPDATE pg_database SET datallowconn = 'false' WHERE datname = 'mydb';

                /* Method 2: use ALTER DATABASE. Superusers still can connect!
                ALTER DATABASE mydb CONNECTION LIMIT 0; */



              2. Force disconnection of all clients connected to this database, using pg_terminate_backend.



                SELECT pg_terminate_backend(pid)
                FROM pg_stat_activity
                WHERE datname = 'mydb';

                /* For old versions of PostgreSQL (up to 9.1), change pid to procpid:

                SELECT pg_terminate_backend(procpid)
                FROM pg_stat_activity
                WHERE datname = 'mydb'; */



              3. Drop the database.



                DROP DATABASE mydb;



              Step 1 requires superuser privileges for the 1st method, and database owner privileges for the 2nd one. Step 2 requires superuser privileges. Step 3 requires database owner privilege.





              * This applies to all versions of PostgreSQL, up to version 11.









              share|improve this answer


























              • So I don't know what I did wrong, but now I can't even connect to the database I targeted! Nor can I drop it as it says "Maintenance database cannot be dropped"

                – Matt Skeldon
                Jul 7 '17 at 5:32











              • @MattSkeldon, no idea what this message means. In vanilla PostgreSQL you can drop any database except template0 & template1. Maybe you use some non-free / commercial version? Maybe it's client issue not server issue? Did you try psql?

                – filiprem
                Jul 12 '17 at 19:05











              • Unfortunately I come from a SQL background, using PGSQL is being used owing to the non commercial / free status.

                – Matt Skeldon
                Jul 12 '17 at 19:09











              • This doesn't work for me where there are long-running zombie sessions. pg_terminate_backend() does not kill those sessions so I'm still a bit stuck about what to do: I am a Postgres su, but I don't have access to the server it's running on.

                – Alexander
                Mar 29 '18 at 16:25














              134












              134








              134







              In PostgreSQL*, you cannot drop a database while clients are connected to it.



              At least, not with the dropdb utility - which is only a simple wrapper around DROP DATABASE server query.



              Quite robust workaround follows:



              Connect to your server as superuser, using psql or other client. Do not use the database you want to drop.



              psql -h localhost postgres postgres


              Now using plain database client you can force drop database using three simple steps:





              1. Make sure no one can connect to this database. You can use one of following methods (the second seems safer, but does not prevent connections from superusers).



                /* Method 1: update system catalog */
                UPDATE pg_database SET datallowconn = 'false' WHERE datname = 'mydb';

                /* Method 2: use ALTER DATABASE. Superusers still can connect!
                ALTER DATABASE mydb CONNECTION LIMIT 0; */



              2. Force disconnection of all clients connected to this database, using pg_terminate_backend.



                SELECT pg_terminate_backend(pid)
                FROM pg_stat_activity
                WHERE datname = 'mydb';

                /* For old versions of PostgreSQL (up to 9.1), change pid to procpid:

                SELECT pg_terminate_backend(procpid)
                FROM pg_stat_activity
                WHERE datname = 'mydb'; */



              3. Drop the database.



                DROP DATABASE mydb;



              Step 1 requires superuser privileges for the 1st method, and database owner privileges for the 2nd one. Step 2 requires superuser privileges. Step 3 requires database owner privilege.





              * This applies to all versions of PostgreSQL, up to version 11.









              share|improve this answer















              In PostgreSQL*, you cannot drop a database while clients are connected to it.



              At least, not with the dropdb utility - which is only a simple wrapper around DROP DATABASE server query.



              Quite robust workaround follows:



              Connect to your server as superuser, using psql or other client. Do not use the database you want to drop.



              psql -h localhost postgres postgres


              Now using plain database client you can force drop database using three simple steps:





              1. Make sure no one can connect to this database. You can use one of following methods (the second seems safer, but does not prevent connections from superusers).



                /* Method 1: update system catalog */
                UPDATE pg_database SET datallowconn = 'false' WHERE datname = 'mydb';

                /* Method 2: use ALTER DATABASE. Superusers still can connect!
                ALTER DATABASE mydb CONNECTION LIMIT 0; */



              2. Force disconnection of all clients connected to this database, using pg_terminate_backend.



                SELECT pg_terminate_backend(pid)
                FROM pg_stat_activity
                WHERE datname = 'mydb';

                /* For old versions of PostgreSQL (up to 9.1), change pid to procpid:

                SELECT pg_terminate_backend(procpid)
                FROM pg_stat_activity
                WHERE datname = 'mydb'; */



              3. Drop the database.



                DROP DATABASE mydb;



              Step 1 requires superuser privileges for the 1st method, and database owner privileges for the 2nd one. Step 2 requires superuser privileges. Step 3 requires database owner privilege.





              * This applies to all versions of PostgreSQL, up to version 11.










              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited 5 hours ago

























              answered Jan 30 '12 at 11:51









              filipremfiliprem

              3,27111226




              3,27111226













              • So I don't know what I did wrong, but now I can't even connect to the database I targeted! Nor can I drop it as it says "Maintenance database cannot be dropped"

                – Matt Skeldon
                Jul 7 '17 at 5:32











              • @MattSkeldon, no idea what this message means. In vanilla PostgreSQL you can drop any database except template0 & template1. Maybe you use some non-free / commercial version? Maybe it's client issue not server issue? Did you try psql?

                – filiprem
                Jul 12 '17 at 19:05











              • Unfortunately I come from a SQL background, using PGSQL is being used owing to the non commercial / free status.

                – Matt Skeldon
                Jul 12 '17 at 19:09











              • This doesn't work for me where there are long-running zombie sessions. pg_terminate_backend() does not kill those sessions so I'm still a bit stuck about what to do: I am a Postgres su, but I don't have access to the server it's running on.

                – Alexander
                Mar 29 '18 at 16:25



















              • So I don't know what I did wrong, but now I can't even connect to the database I targeted! Nor can I drop it as it says "Maintenance database cannot be dropped"

                – Matt Skeldon
                Jul 7 '17 at 5:32











              • @MattSkeldon, no idea what this message means. In vanilla PostgreSQL you can drop any database except template0 & template1. Maybe you use some non-free / commercial version? Maybe it's client issue not server issue? Did you try psql?

                – filiprem
                Jul 12 '17 at 19:05











              • Unfortunately I come from a SQL background, using PGSQL is being used owing to the non commercial / free status.

                – Matt Skeldon
                Jul 12 '17 at 19:09











              • This doesn't work for me where there are long-running zombie sessions. pg_terminate_backend() does not kill those sessions so I'm still a bit stuck about what to do: I am a Postgres su, but I don't have access to the server it's running on.

                – Alexander
                Mar 29 '18 at 16:25

















              So I don't know what I did wrong, but now I can't even connect to the database I targeted! Nor can I drop it as it says "Maintenance database cannot be dropped"

              – Matt Skeldon
              Jul 7 '17 at 5:32





              So I don't know what I did wrong, but now I can't even connect to the database I targeted! Nor can I drop it as it says "Maintenance database cannot be dropped"

              – Matt Skeldon
              Jul 7 '17 at 5:32













              @MattSkeldon, no idea what this message means. In vanilla PostgreSQL you can drop any database except template0 & template1. Maybe you use some non-free / commercial version? Maybe it's client issue not server issue? Did you try psql?

              – filiprem
              Jul 12 '17 at 19:05





              @MattSkeldon, no idea what this message means. In vanilla PostgreSQL you can drop any database except template0 & template1. Maybe you use some non-free / commercial version? Maybe it's client issue not server issue? Did you try psql?

              – filiprem
              Jul 12 '17 at 19:05













              Unfortunately I come from a SQL background, using PGSQL is being used owing to the non commercial / free status.

              – Matt Skeldon
              Jul 12 '17 at 19:09





              Unfortunately I come from a SQL background, using PGSQL is being used owing to the non commercial / free status.

              – Matt Skeldon
              Jul 12 '17 at 19:09













              This doesn't work for me where there are long-running zombie sessions. pg_terminate_backend() does not kill those sessions so I'm still a bit stuck about what to do: I am a Postgres su, but I don't have access to the server it's running on.

              – Alexander
              Mar 29 '18 at 16:25





              This doesn't work for me where there are long-running zombie sessions. pg_terminate_backend() does not kill those sessions so I'm still a bit stuck about what to do: I am a Postgres su, but I don't have access to the server it's running on.

              – Alexander
              Mar 29 '18 at 16:25













              6
















              There is a way to do this with the shell utilities dropdb & pg_ctl (or pg_ctlcluster in Debian and derivates). But @filiprem's method is superior for several reasons:




              • It only disconnects users from the database in question.

              • It does not need to restart the whole cluster.

              • It prevents immediate reconnects, possibly spoiling the dropdb command.


              I quote man pg_ctlcluster:




              With the --force option the "fast" mode is used which rolls back all active transactions, disconnects clients immediately and thus shuts down cleanly. If that does not work, shutdown is attempted again in "immediate" mode, which can leave the cluster in an inconsistent state and thus will lead to a recovery run at the next start. If this still does not help, the postmaster process is killed. Exits with 0 on success, with 2 if the server is not running, and with 1 on other failure conditions. This mode should only be used when the machine is about to be shut down.




              pg_ctlcluster 9.1 main restart --force


              or



              pg_ctl restart -D datadir -m fast


              or



              pg_ctl restart -D datadir -m immediate


              immediately followed by:



              dropdb mydb


              Possibly in a script for immediate succession.






              share|improve this answer





















              • 4





                Not only is this less than ideal as it kicks the full postgres instance but it is not guaranteed to work. It is possible for a client to connect between the time you restart the server and attempt to run dropdb again. @filiprem 's answer above disables all connections to the database prior to disconnecting and will keep other databases up.

                – Jim Mitchener
                Oct 22 '14 at 5:28
















              6
















              There is a way to do this with the shell utilities dropdb & pg_ctl (or pg_ctlcluster in Debian and derivates). But @filiprem's method is superior for several reasons:




              • It only disconnects users from the database in question.

              • It does not need to restart the whole cluster.

              • It prevents immediate reconnects, possibly spoiling the dropdb command.


              I quote man pg_ctlcluster:




              With the --force option the "fast" mode is used which rolls back all active transactions, disconnects clients immediately and thus shuts down cleanly. If that does not work, shutdown is attempted again in "immediate" mode, which can leave the cluster in an inconsistent state and thus will lead to a recovery run at the next start. If this still does not help, the postmaster process is killed. Exits with 0 on success, with 2 if the server is not running, and with 1 on other failure conditions. This mode should only be used when the machine is about to be shut down.




              pg_ctlcluster 9.1 main restart --force


              or



              pg_ctl restart -D datadir -m fast


              or



              pg_ctl restart -D datadir -m immediate


              immediately followed by:



              dropdb mydb


              Possibly in a script for immediate succession.






              share|improve this answer





















              • 4





                Not only is this less than ideal as it kicks the full postgres instance but it is not guaranteed to work. It is possible for a client to connect between the time you restart the server and attempt to run dropdb again. @filiprem 's answer above disables all connections to the database prior to disconnecting and will keep other databases up.

                – Jim Mitchener
                Oct 22 '14 at 5:28














              6












              6








              6









              There is a way to do this with the shell utilities dropdb & pg_ctl (or pg_ctlcluster in Debian and derivates). But @filiprem's method is superior for several reasons:




              • It only disconnects users from the database in question.

              • It does not need to restart the whole cluster.

              • It prevents immediate reconnects, possibly spoiling the dropdb command.


              I quote man pg_ctlcluster:




              With the --force option the "fast" mode is used which rolls back all active transactions, disconnects clients immediately and thus shuts down cleanly. If that does not work, shutdown is attempted again in "immediate" mode, which can leave the cluster in an inconsistent state and thus will lead to a recovery run at the next start. If this still does not help, the postmaster process is killed. Exits with 0 on success, with 2 if the server is not running, and with 1 on other failure conditions. This mode should only be used when the machine is about to be shut down.




              pg_ctlcluster 9.1 main restart --force


              or



              pg_ctl restart -D datadir -m fast


              or



              pg_ctl restart -D datadir -m immediate


              immediately followed by:



              dropdb mydb


              Possibly in a script for immediate succession.






              share|improve this answer

















              There is a way to do this with the shell utilities dropdb & pg_ctl (or pg_ctlcluster in Debian and derivates). But @filiprem's method is superior for several reasons:




              • It only disconnects users from the database in question.

              • It does not need to restart the whole cluster.

              • It prevents immediate reconnects, possibly spoiling the dropdb command.


              I quote man pg_ctlcluster:




              With the --force option the "fast" mode is used which rolls back all active transactions, disconnects clients immediately and thus shuts down cleanly. If that does not work, shutdown is attempted again in "immediate" mode, which can leave the cluster in an inconsistent state and thus will lead to a recovery run at the next start. If this still does not help, the postmaster process is killed. Exits with 0 on success, with 2 if the server is not running, and with 1 on other failure conditions. This mode should only be used when the machine is about to be shut down.




              pg_ctlcluster 9.1 main restart --force


              or



              pg_ctl restart -D datadir -m fast


              or



              pg_ctl restart -D datadir -m immediate


              immediately followed by:



              dropdb mydb


              Possibly in a script for immediate succession.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Apr 13 '17 at 12:43









              Community

              1




              1










              answered Jan 30 '12 at 16:15









              Erwin BrandstetterErwin Brandstetter

              92.6k9176291




              92.6k9176291








              • 4





                Not only is this less than ideal as it kicks the full postgres instance but it is not guaranteed to work. It is possible for a client to connect between the time you restart the server and attempt to run dropdb again. @filiprem 's answer above disables all connections to the database prior to disconnecting and will keep other databases up.

                – Jim Mitchener
                Oct 22 '14 at 5:28














              • 4





                Not only is this less than ideal as it kicks the full postgres instance but it is not guaranteed to work. It is possible for a client to connect between the time you restart the server and attempt to run dropdb again. @filiprem 's answer above disables all connections to the database prior to disconnecting and will keep other databases up.

                – Jim Mitchener
                Oct 22 '14 at 5:28








              4




              4





              Not only is this less than ideal as it kicks the full postgres instance but it is not guaranteed to work. It is possible for a client to connect between the time you restart the server and attempt to run dropdb again. @filiprem 's answer above disables all connections to the database prior to disconnecting and will keep other databases up.

              – Jim Mitchener
              Oct 22 '14 at 5:28





              Not only is this less than ideal as it kicks the full postgres instance but it is not guaranteed to work. It is possible for a client to connect between the time you restart the server and attempt to run dropdb again. @filiprem 's answer above disables all connections to the database prior to disconnecting and will keep other databases up.

              – Jim Mitchener
              Oct 22 '14 at 5:28











              3














              Using @filiprem's answer in a my case and simplifying it:



              -- Connecting to the current user localhost's postgres instance
              psql

              -- Making sure the database exists
              SELECT * from pg_database where datname = 'my_database_name'

              -- Disallow new connections
              UPDATE pg_database SET datallowconn = 'false' WHERE datname = 'my_database_name';
              ALTER DATABASE my_database_name CONNECTION LIMIT 1;

              -- Terminate existing connections
              SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = 'my_database_name';

              -- Drop database
              DROP DATABASE my_database_name





              share|improve this answer




























                3














                Using @filiprem's answer in a my case and simplifying it:



                -- Connecting to the current user localhost's postgres instance
                psql

                -- Making sure the database exists
                SELECT * from pg_database where datname = 'my_database_name'

                -- Disallow new connections
                UPDATE pg_database SET datallowconn = 'false' WHERE datname = 'my_database_name';
                ALTER DATABASE my_database_name CONNECTION LIMIT 1;

                -- Terminate existing connections
                SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = 'my_database_name';

                -- Drop database
                DROP DATABASE my_database_name





                share|improve this answer


























                  3












                  3








                  3







                  Using @filiprem's answer in a my case and simplifying it:



                  -- Connecting to the current user localhost's postgres instance
                  psql

                  -- Making sure the database exists
                  SELECT * from pg_database where datname = 'my_database_name'

                  -- Disallow new connections
                  UPDATE pg_database SET datallowconn = 'false' WHERE datname = 'my_database_name';
                  ALTER DATABASE my_database_name CONNECTION LIMIT 1;

                  -- Terminate existing connections
                  SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = 'my_database_name';

                  -- Drop database
                  DROP DATABASE my_database_name





                  share|improve this answer













                  Using @filiprem's answer in a my case and simplifying it:



                  -- Connecting to the current user localhost's postgres instance
                  psql

                  -- Making sure the database exists
                  SELECT * from pg_database where datname = 'my_database_name'

                  -- Disallow new connections
                  UPDATE pg_database SET datallowconn = 'false' WHERE datname = 'my_database_name';
                  ALTER DATABASE my_database_name CONNECTION LIMIT 1;

                  -- Terminate existing connections
                  SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = 'my_database_name';

                  -- Drop database
                  DROP DATABASE my_database_name






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Feb 8 '17 at 23:02









                  DorianDorian

                  1394




                  1394























                      0














                      If you're on something like RDS where connections without a database selected put you into the DB you asked to be created by default you can do this variant to get around yourself being the last open connection.



                       DROP DATABASE IF EXISTS temporary_db_that_shouldnt_exist; 

                      CREATE DATABASE temporary_db_that_shouldnt_exist with OWNER your_user;

                      connect temporary_db_that_shouldnt_exist
                      SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = 'the_db_you_want_removed';


                      DROP DATABASE IF EXISTS the_db_you_want_removed;
                      --
                      -- Name: the_db_you_want_removed; Type: DATABASE; Schema: -; Owner: your_user
                      --

                      CREATE DATABASE savings_champion WITH TEMPLATE = template0 ENCODING = 'UTF8' LC_COLLATE = 'en_US.UTF-8' LC_CTYPE = 'en_US.UTF-8';


                      ALTER DATABASE the_db_you_want_removed OWNER TO your_user;

                      connect the_db_you_want_removed

                      DROP DATABASE IF EXISTS temporary_db_that_shouldnt_exist;





                      share|improve this answer




























                        0














                        If you're on something like RDS where connections without a database selected put you into the DB you asked to be created by default you can do this variant to get around yourself being the last open connection.



                         DROP DATABASE IF EXISTS temporary_db_that_shouldnt_exist; 

                        CREATE DATABASE temporary_db_that_shouldnt_exist with OWNER your_user;

                        connect temporary_db_that_shouldnt_exist
                        SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = 'the_db_you_want_removed';


                        DROP DATABASE IF EXISTS the_db_you_want_removed;
                        --
                        -- Name: the_db_you_want_removed; Type: DATABASE; Schema: -; Owner: your_user
                        --

                        CREATE DATABASE savings_champion WITH TEMPLATE = template0 ENCODING = 'UTF8' LC_COLLATE = 'en_US.UTF-8' LC_CTYPE = 'en_US.UTF-8';


                        ALTER DATABASE the_db_you_want_removed OWNER TO your_user;

                        connect the_db_you_want_removed

                        DROP DATABASE IF EXISTS temporary_db_that_shouldnt_exist;





                        share|improve this answer


























                          0












                          0








                          0







                          If you're on something like RDS where connections without a database selected put you into the DB you asked to be created by default you can do this variant to get around yourself being the last open connection.



                           DROP DATABASE IF EXISTS temporary_db_that_shouldnt_exist; 

                          CREATE DATABASE temporary_db_that_shouldnt_exist with OWNER your_user;

                          connect temporary_db_that_shouldnt_exist
                          SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = 'the_db_you_want_removed';


                          DROP DATABASE IF EXISTS the_db_you_want_removed;
                          --
                          -- Name: the_db_you_want_removed; Type: DATABASE; Schema: -; Owner: your_user
                          --

                          CREATE DATABASE savings_champion WITH TEMPLATE = template0 ENCODING = 'UTF8' LC_COLLATE = 'en_US.UTF-8' LC_CTYPE = 'en_US.UTF-8';


                          ALTER DATABASE the_db_you_want_removed OWNER TO your_user;

                          connect the_db_you_want_removed

                          DROP DATABASE IF EXISTS temporary_db_that_shouldnt_exist;





                          share|improve this answer













                          If you're on something like RDS where connections without a database selected put you into the DB you asked to be created by default you can do this variant to get around yourself being the last open connection.



                           DROP DATABASE IF EXISTS temporary_db_that_shouldnt_exist; 

                          CREATE DATABASE temporary_db_that_shouldnt_exist with OWNER your_user;

                          connect temporary_db_that_shouldnt_exist
                          SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = 'the_db_you_want_removed';


                          DROP DATABASE IF EXISTS the_db_you_want_removed;
                          --
                          -- Name: the_db_you_want_removed; Type: DATABASE; Schema: -; Owner: your_user
                          --

                          CREATE DATABASE savings_champion WITH TEMPLATE = template0 ENCODING = 'UTF8' LC_COLLATE = 'en_US.UTF-8' LC_CTYPE = 'en_US.UTF-8';


                          ALTER DATABASE the_db_you_want_removed OWNER TO your_user;

                          connect the_db_you_want_removed

                          DROP DATABASE IF EXISTS temporary_db_that_shouldnt_exist;






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Mar 29 '18 at 12:25









                          JharwoodJharwood

                          1




                          1






























                              draft saved

                              draft discarded




















































                              Thanks for contributing an answer to Database Administrators Stack Exchange!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid



                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.


                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f11893%2fforce-drop-db-while-others-may-be-connected%23new-answer', 'question_page');
                              }
                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              Parapolítica Índice Antecedentes El escándalo Proceso judicial Consecuencias Véase...

                              How to remove border from elements in the last row?Targeting flex items on the last rowHow to vertically wrap...

                              Tecnologías entrañables Índice Antecedentes Desarrollo Tecnologías Entrañables en la...