LOCK is a PostgreSQL command that lets you take an explicit table-level lock inside an open transaction. While the database normally acquires locks implicitly, explicit locking is useful when you need predictable ordering of locks, stronger protection than the default isolation level, or to prevent deadlocks. LOCK blocks until the requested lock can be granted, unless you add NOWAIT or SKIP LOCKED. The lock is held until the transaction ends (COMMIT or ROLLBACK). Choosing the correct lock mode is critical because stronger modes block more concurrent activity. Common modes include ACCESS SHARE, ROW SHARE, ROW EXCLUSIVE, SHARE UPDATE EXCLUSIVE, SHARE, SHARE ROW EXCLUSIVE, EXCLUSIVE, and ACCESS EXCLUSIVE. Because LOCK does not start a transaction for you, running it outside BEGIN...COMMIT raises an error. Use it sparingly because table-level locks can severely reduce concurrency.
table_name
(regclass) - One or more tables to locklock_mode
(enum) - One of the supported lock modes (default ACCESS EXCLUSIVE)NOWAIT
(keyword) - Raise error instead of waiting if lock unavailableSKIP LOCKED
(keyword) - Return immediately without locking unavailable tablesSELECT ... FOR UPDATE, BEGIN, COMMIT, ROLLBACK, Transaction Isolation Levels, Advisory Locks
PostgreSQL 7.0
No. You must call LOCK inside an explicit BEGIN ... COMMIT or ROLLBACK block.
The lock persists until the transaction that acquired it ends.
Without NOWAIT the session waits. With NOWAIT PostgreSQL raises an error immediately. With SKIP LOCKED it returns without locking the busy table.
No. LOCK is table-level. Use SELECT ... FOR UPDATE or FOR SHARE for row-level locks.