SQL update WHERE xx AND most recent record SQL update WHERE xx AND most recent record sql sql

SQL update WHERE xx AND most recent record


You can limit to update only the most recent record

UPDATE your_tableSET some_column = 1order by date_time_column desclimit 1

where date_time_column can be any column indicating the order of the records. It could be an auto-increment ID too.


UPDATE tableSET column = valueWHERE primary_key =(SELECT primary_keyFROM table WHERE date_time_column = (select max(date_time_column) FROM table WHERE other_conditions))AND other_conditions

This query does not use order by or limit clause and therefore will be portable. Note that other_conditions have to be same in the inner query and outer query.

(Since this was posted in a comment) Why does the inner query need to have the same condition as the outer one?

  • If the inner condition fetches a broader resultset than the outer one, you could end up with a date_time_column that is earlier than those contained in the rows satisfying the outer condition. ANDing them will then result in a fetch of 0 rows.

  • If the inner condition fetches a narrower result set than the outer one, you could end up missing out on any of the records that are newer, not part of the inner set yet satisfied as part of the outer condition.

Hope this clarifies.