Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

182
Views
PostgreSQL Gap lock by SELECT ... FOR UPDATE

There is a query with a Gap Lock used at MySQL/InnoDB:

SELECT id, time, count
FROM table_a
WHERE time
    BETWEEN DATE_SUB(NOW(), INTERVAL 24 HOUR)
    AND NOW()
FOR UPDATE

It locks the time range and returns a recent record if present (during last 24 hrs). If not - the session still owns a lock over the duration of last 24 hours to safely insert a new record.

Is is possible to make the same gap lock for entire 24 hours duration (even if there are no records) in PostgreSQL?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

The way to do that in PostgreSQL is to use the SERIALIZABLE isolation level for all transactions.

Then you don't need the FOR UPDATE at all. PostgreSQL won't prevent rows from being inserted in the gap, but if two transactions both read and write values in the same gap simultaneously, one of them will get a serialization error and have to redo the transaction (on the second try, it will find the gap not empty).

The concept at work here is serializability: it is acceptable if someone else inserts into the gap without reading (that transaction is logically after the one with your SELECT). But if two transactions both find the gap empty and then insert something, that would create an anomaly that is prevented by SERIALIZABLE.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!