-- Clear any dangling cover references before adding the constraint. UPDATE albums SET cover_photo_id = NULL WHERE cover_photo_id IS NOT NULL AND cover_photo_id NOT IN (SELECT id FROM photos); ALTER TABLE albums ADD CONSTRAINT albums_cover_photo_fk FOREIGN KEY (cover_photo_id) REFERENCES photos(id) ON DELETE SET NULL;