MySQL 8.0 - Data Loss When Using REPLACE INTO with Composite Primary Keys
I'm performance testing and I've looked through the documentation and I'm still confused about I'm working on a project and hit a roadblock... I have a table with a composite primary key defined on two columns: `user_id` and `item_id`. When using the `REPLACE INTO` statement to insert new records, I'm encountering unexpected data loss where some rows seem to disappear. My table structure is as follows: ```sql CREATE TABLE user_items ( user_id INT, item_id INT, quantity INT, PRIMARY KEY (user_id, item_id) ); ``` Hereβs the code snippet I'm using for the `REPLACE INTO` operation: ```sql REPLACE INTO user_items (user_id, item_id, quantity) VALUES (1, 100, 5); REPLACE INTO user_items (user_id, item_id, quantity) VALUES (1, 100, 10); REPLACE INTO user_items (user_id, item_id, quantity) VALUES (2, 200, 3); ``` When I execute these statements, I expect to see the `user_items` table updated with the new `quantity` values, replacing the old ones when the primary key matches. However, after running this, I noticed that the first replace does update the quantity for `user_id = 1` and `item_id = 100` to 5, but the second replace does not seem to update it correctly. Instead, it gets removed from the table entirely, and I end up with only the record for `user_id = 2`. I checked for triggers or foreign key constraints that might affect this operation, but I didn't find anything related. I also considered whether using `INSERT ... ON DUPLICATE KEY UPDATE` might give me more control, but I really need to understand why `REPLACE INTO` is causing this data loss in my case. Am I missing something in my understanding of how `REPLACE INTO` works with composite keys? Any insights would be appreciated. This is part of a larger application I'm building. Thanks for taking the time to read this! Could this be a known issue?