-- 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 ...; #### INSERT INTO images (gallery_id, title, description, fstop) SELECT 1+MAX(...), 'title', 'description', 'fstop' FROM images;