Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL How to Update only first Row

Tags:

sql

postgresql

I'm working with PostgreSQL. I have table with some elements. In last column there is 'Y' or 'N' letter. I need command which Select only first that match (I mean where last column is 'N') and change it on 'Y'.

My idea:

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

But it changes 'N' to 'Y' in every row.

like image 886
Lorn Avatar asked Jan 21 '14 12:01

Lorn


People also ask

How do I SELECT only the first row?

To return only the first row that matches your SELECT query, you need to add the LIMIT clause to your SELECT statement. The LIMIT clause is used to control the number of rows returned by your query. When you add LIMIT 1 to the SELECT statement, then only one row will be returned.

How can I UPDATE first 100 rows in SQL?

UPDATE TOP (100) table_name set column_name = value; If you want to show the last 100 records, you can use this if you need. Show activity on this post. The TOP qualifier can also be used as limit the the number of rows manually updated incorrectly.


1 Answers

Here is query

UPDATE Table SET Checked='Y' 
WHERE ID =(SELECT ID FROM Table WHERE Checked='N' ORDER BY ID LIMIT 1) 
like image 74
Akshay Avatar answered Sep 25 '22 17:09

Akshay