How to tell if `CLUSTER table USING index` finished? I want to use an AWS scheduled Lambda function to update my PostgreSQL table indexes every month. I am not on psql bash and I am not leaving Lambda function up until CLUSTER finishes.

How can I tell if the CLUSTER finished?
To find out whether or not you have any executing CLUSTER commands, simply run this..

SELECT * FROM pg_stat_activity
WHERE query ~ '^CLUSTER'
  AND state = 'active';


However, that doesn't tell you if it already finished on a table. I don't think you can figure that out. You can only see


whether or not a CLUSTER is running.

SELECT * FROM pg_stat_activity AS psa
WHERE query ~* '^CLUSTER'
  AND state = 'active';

if one is currently running, what table it was running on. This requires more work, we look at the locked tables the transaction is using to figure this out.

SELECT *
FROM pg_stat_activity AS psa
JOIN pg_locks AS pl
  ON (pl.pid = psa.pid)
WHERE query ~* '^CLUSTER'
  AND state = 'active'
  -- replace with table
  AND relation::regclass = 'MyTable'::regclass
  AND mode = 'AccessExclusiveLock';