I am new to Postgres(even to SQL). I am building a key DB which has a table named Key. My question is how can I perform the following on pg.
If one connection is reading the first record and simultaneously the second connection comes in, it should read 2nd record rather than 1st. Its the same thing for the 3rd 4th and so on.
You can do it using
select for update.FOR UPDATEcauses the rows retrieved by theSELECTstatement to be locked as though for update. This prevents them from being locked, modified or deleted by other transactions until the current transaction ends.ATTENTION:
Now I will write for you query samples and explain how to do it: Suppose we have one such table:
After the
selectcommand selected row will be locked. And this row cannot be selected by user in any other session until be updated. All users will be waiting for this update when selecting this row. Afterupdatecommand users can be shown next row which is_used = false