Skip to content
Middle+69 views

На каких уровнях можно брать блокировки в базе данных? Какие есть блокировки, не привязанные к таблице?

Practice

Asked at

AI answer

The granularity and available types of locks depend on the DBMS. In general, locks can apply to rows, pages, tables, and database objects; some DBMSs also support locks on individual fields. The finer the granularity, the greater the concurrency—but the higher the overhead.

For example, in PostgreSQL, application code can lock rows (SELECT ... FOR UPDATE) and relations—tables, indexes, and other objects (LOCK TABLE). Page locks are mostly internal. Row locks are usually held until the end of the transaction.

Locks that aren’t tied to a specific table are primarily advisory locks: the application chooses a key and uses it to coordinate tasks, for example, to ensure that only one process performs a periodic calculation. PostgreSQL provides both transaction-level and session-level variants (pg_advisory_xact_lock, pg_advisory_lock). It’s important to explicitly release a session-level lock; a transaction-level lock is released when the transaction ends. The DBMS also uses internal locks on transactions and objects, but these aren’t the same as application-level table locks.