PostgreSQL Performance – Why COUNT Obtains an ExclusiveLock

performancepostgresqlpostgresql-performance

And what does this mean for other CRUD operations going against that table?

I have this query (actually I'm trying to write it 9 ways from Sunday to get it to return in less than an hour):

SELECT COUNT(*)
FROM (SELECT DISTINCT listing_id 
      FROM apps where subscription_id = 1298) AS temp

It churns and churns. When I look at a process list for the server, I find eight records. One for the table and six for the indexes. And apparently one for the statement itself.

It says Locked Object and the object name, and AccessShareLock next to the table and indexes. Then there is something that says LockedTransaction and next to it it says ExclusiveLock.

What does this ExclusiveLock mean, and will it keep other CRUD operations from running against that table?

Best Answer

Every transaction is born owning an ExclusiveLock on itself.

For a read-only transaction, this will only block things like CREATE INDEX CONCURRENTLY. For DML transactions, this lock will be used to block other transactions trying to update or delete the same row, or insert conflicting rows.