Sample Header Ad - 728x90

MySQL adding constraint fails for unrelated column, then succeeds

0 votes
1 answer
69 views
EDIT: I did clean up the invalid data in column Y, and then I was able to add the FK to column X in one go. If anybody comes across this, it would still be interesting to know why it happened in the first place? --- This question is regarding MySQL 8.0. All tables are InnoDB. I am adding a column X to a table T1, and the column needs to have a foreign key constraint to a column in table T2. (The two columns have matching types and collations.) This is being done programatically by a script. When I run the script in our remote testing environment, the column is added successfully, but the constraint cannot be added. The command fails with a typical constraint error -- SQLSTATE: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails. However, it is not failing on column X; it is failing on a constraint for a different column, column Y. Column Y actually does have data that fails its own FK constraint, but I am surprised that this comes up when I attempt to add a constraint to column X. This did not occur when I tested the script against my own locally-running copy of the database. I even recreated the circumstances locally (putting invalid data into column Y), and the FK was still added to column X successfully. The most surprising part is that I am able to work around this in our remote test environment by removing column X and re-running the script. This time, it successfully creates the column and then adds the FK constraint to it. A difference between local and remote is that remote has quite a bit more data. Adding the column takes about 23 seconds in remote, vs. 1 second locally. In remote, when I run the script the second time without refreshing the db in between, and it successfully adds both the column and the constraint, it takes about 287 seconds. The sql_mode is identical between the local and remote. The part where it works the second time makes me suspect some sort of buffer that hasn't flushed in time for the constraint to be added the first time. I have tried updating the script to perform FLUSH TABLES between creating the column and adding the constraint, but that had no apparent impact. My main question is: why is it failing the first time and succeeding the second time. Any ideas? EDIT: the column is create with one statement and the FK is added with a separate statement. --- Note: I have been able to perform this test repeatedly in the remote environment because I'm running it on a clone, so each time I refresh it from the original data source and run the script again.
Asked by Charles Wood (101 rep)
Apr 2, 2025, 12:46 AM
Last activity: Apr 2, 2025, 11:43 PM