xhaz_a
Last Updated: February 25, 2016
·
6.669K
· 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

12130

Thanks a million!

over 1 year ago ·
14093

how to use it?

over 1 year ago ·
17496

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

over 1 year ago ·