We are always asked by a client or our manager about how fragmented a table, an index, a schema or whole database is in PostgreSQL database. The following code will answer this question with the following information reported for a schema.
-- get all index names of table testuser.test
testdb=>\d testuser.test
...
..
.
-- get size of index
testdb=> select pg_size_pretty( pg_relation_size('testuser.ix_test_id'));
pg_size_pretty
----------------
942 MB
(1 row)
This is often used script to kill PostgreSQL session(s).
pg_terminate_backend() AND pg_cancel_backend()
1) kill all connections of a specified database name.
-- List all available databases
postgres=>\l
postgres=> SELECT pg_terminate_backend(pg_stat_activity.pid)
FROM pg_stat_activity
WHERE datname = 'DATABASE NAME'
AND pid <> pg_backend_pid();
2) kill all connections of a specified user name.
postgres=> SELECT pg_terminate_backend(pg_stat_activity.pid)
FROM pg_stat_activity
WHERE usename = 'testuser'
AND pid <> pg_backend_pid();
3) kill all sessions of current database.
postgres=> SELECT pg_terminate_backend(pg_stat_activity.pid)
FROM pg_stat_activity
WHERE datname = current_database()
AND pid <> pg_backend_pid();
4) kill a connection of a specified pid.
postgres=> SELECT pg_terminate_backend(pid);
5) kill a running SQL of a session, but does not kill the session.
postgres=> SELECT pg_cancel_backend( pid );
It is useful when a running SQL is taking long time than expected.