Last Updated: February 25, 2016
·
7.236K
· mhenrixon

How to kill all Postgres connections

#!/usr/bin/env bash
# kill all connections to the postgres server
if [ -n "$1" ] ; then
  where="where pg_stat_activity.datname = '$1'"
  echo "killing all connections to database '$1'"
else
  where="where pg_stat_activity.datname in (select datname from pg_database where datname != 'postgres')"
  echo "killing all connections to database"
fi

cat <<-EOF | psql -U mhenrixon -d postgres
SELECT pg_terminate_backend(pg_stat_activity.pid)
FROM pg_stat_activity
${where}
EOF

3 Responses
Add your response

Thanks a million!

over 1 year ago ·

how to use it?

over 1 year ago ·

andilabs: make it executable and run it like you would any other bash script.

over 1 year ago ·