In my MySQL table, every column by itself can be NULL, but there must be at least one column with a non-NULL value. At the moment, I am wrapping an insert statement in a stored procedure which prevents insertion of all-NULL rows, but that of course does not keep anyone from using native INSERT statements, circumventing my wrapper procedure.
Is there a ‘native’ way to define the table with that constraint ?
Since MySQL doesn’t enforce check constraints, you may want to emulate one with a trigger. I suggest checking out this MySQL Forge article:
The idea is this to move your check logic to a trigger. If the check fails, call a stored procedure that fails by raising a unique key violation. This allows us to return a descriptive error message back to the client.
Your trigger will probably look something like this:
We need to make the
failsproc raise a unique key violation in order to have theINSERTaborted when the check fails. The above mentioned article suggests creating a memory table defined as follows:Then the
failsproc could be implemented as follows:The double
INSERTwill ensure that the unique key violation is raised. If the same message already exists in the table, the violation will get raised on the firstINSERT, but it doesn’t matter as long as it fails.We can try the
failsproc from the command line:The good news is that we get back a readable error message. However we don’t get back the correct error code, and we don’t really have a “duplicate entry”. This is obviously one limitation of this method, especially when updating or inserting records in a procedure which uses error handling, in particular handling the
1062 Duplicate Entryerror specifically.