Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select For Update statement in PostgreSql

Tags:

sql

postgresql

I want to select fields in a record of a table and update just one of these fields. How can I do?

I try this:

SELECT v.idvideo, v.title 
FROM video v  WHERE v.schedulingflag IS FALSE AND v.errorflag IS FALSE 
ORDER BY v.idvideo  LIMIT 1 FOR UPDATE ;

UPDATE video  SET schedulingflag = true;

But in this way it sets field "schedulingflag" true in all record!

like image 316
Emanuele Mazzoni Avatar asked Feb 05 '13 14:02

Emanuele Mazzoni


People also ask

What is SELECT for UPDATE in Postgres?

FOR SHARE , which provides a weaker form of row-locking in some database systems. In PostgreSQL, SELECT … FOR UPDATE completely locks the relevant rows, whereas SELECT … FOR SHARE locks the relevant rows only for updates and deletes.

How do I write a selected PostgreSQL statement?

PostgreSQL SELECT Syntax The simplest form of the SELECT statement syntax is: SELECT expressions FROM tables WHERE conditions; The expressions are all the columns and fields you want in the result. The tables syntax is the table or tables from which you want to extract the results.

How UPDATE works in Postgres?

PostgreSQL implements multiversioning by keeping the old version of the table row in the table – an UPDATE adds a new row version (“tuple”) of the row and marks the old version as invalid. In many respects, an UPDATE in PostgreSQL is not much different from a DELETE followed by an INSERT .


1 Answers

The SELECT FOR UPDATE syntax tells PG that you're going to be updating those records and locks them against concurrent access. However you still need to issue the appropriate UPDATE call to change the particular records you've locked.

In this case, just use the same WHERE clause in your UPDATE, e.g:

UPDATE video  SET schedulingflag = true 
WHERE schedulingflag IS FALSE AND errorflag IS FALSE;
like image 161
Dave S. Avatar answered Oct 13 '22 00:10

Dave S.