PostgreSQL – Explicit Lock with Transactions

lockingpostgresqltransaction

I am a beginner in SQL world and have some doubts regarding transaction/locking:

  • In postgres, do transaction also ensures locking of rows(preferable)/tables until it is completed?

  • Also, if there are two transactions through different queries, will second one wait for the first one to complete i.e. will it be serial or concurrent?

I think both points infers same but I am not sure so posting both.

Best Answer

In postgres, do transaction also ensures locking of rows(preferable)/tables until it is completed?

No, transactions don't ensure locking. Transactions ensure only that whatever is transacting is done atomically. That is to say, that it either all succeeds, or it all fails. How it does what it does, and what it is doing it to is totally controlled by you.

For instance, PostgreSQL currently supports three isolation levels,

  • Read committed
  • Repeatable read
  • Serializable

These three isolation levels either see and operate can see the data directly, or a snapshot of the data at the time transaction starts.

Only in the last mode serializable is any attempt to be made that the transaction commits in a serialized fashion. Whether or not enough of an attempt is made is another question.

All locking in PostgreSQL can be done explicitly or implicitly (the DDL command know how to lock efficiently to get the job done). Usually, explicit locks are shunned. But in same cases, including under serializable, it's the only way to be sure data has not been added since the transaction started.