PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, October 24, 2022

[FIXED] How to select a row, lock it, update it, then select again?

 October 24, 2022     concurrency, postgresql, queue, sql, sql-update     No comments   

Issue

I have a table with these 3 columns:

  1. task (string)
  2. status (string)
  3. date (datetime)

I want to write a query that does the following:

  1. Selects the first row WHERE status != "In-Progress" Sorted by Date (oldest first), and Locks it - so other computers running this query concurrently can't read it.
  2. Updates the Status column so status = "In-Progress".
  3. Return the row's columns (like a regular Select * statement).

How do I write this query?

My main concern is that the row is only fetched by 1 computer, no matter how many concurrent instances are running.


Solution

Assuming a table named "tbl" with a PK named "tbl_id":

UPDATE tbl
SET    status = 'In-Progress' 
WHERE  tbl_id = (
         SELECT tbl_id
         FROM   tbl
         WHERE  status <> 'In-Progress'
         ORDER  BY date
         LIMIT  1
         FOR    UPDATE SKIP LOCKED
         )
RETURNING *;

For an in-depth discussion of every step, see this related answer on dba.SE:

  • Postgres UPDATE ... LIMIT 1


Answered By - Erwin Brandstetter
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing