SQL How to Update only first Row

Here is query

UPDATE Table SET Checked='Y' 
WHERE ID =(SELECT ID FROM Table WHERE Checked='N' ORDER BY ID LIMIT 1) 

Mention that if you have the concurrent requests you need to handle with transactions, for example -

UPDATE Table SET Checked='Y' WHERE ID =(SELECT ID FROM Table WHERE Checked='N' ORDER BY ID LIMIT 1 FOR UPDATE SKIP LOCKED)

if you want to skip locked rows


Why it didn't work

Others have answered the how, but you really need to understand why this was wrong:

UPDATE Table SET Checked='Y' WHERE (
  SELECT Checked FROM Table WHERE Checked='N' ORDER BY ID LIMIT 1
) = 'N'

SQL evaluates step by step in a well-defined order. In this case, the subquery evaluates first because it's uncorrelated, i.e. it doesn't refer to any variables from the outer query.

The subquery finds the first row in id order where 'Checked' is 'N', and as the SELECT list contains the field Checked, that means the subquery will be substituted for the value N. Effectively it does nothing (except it might be NULL instead of N if no rows matched).

So now you have:

UPDATE Table SET Checked='Y' WHERE 'N' = 'N';

Starting to see what went wrong?

'N' = 'N' is always going to be true. So the WHERE clause is always true, and you might as well have written an unconstrained update.

UPDATE Table SET Checked='Y';

How to fix it

You're trying to find the first row where checked is n and set checked to y. You need to connect these two parts using the primary key. Find the id you want to update, then use that to constrain the update.

Others have already written the text of that query, so I won't repeat it here. Hopefully you now understand those answers, though.

Tags:

Sql

Postgresql