-- create the new image row with blank gallery_id: INSERT INTO images ... VALUES (...); -- atomically update the gallery_id field UPDATE images SET gallery_id = (SELECT 1+MAX(...) FROM images) WHERE ...;