I am new in SQL (Yes, just 1 week) and I am learning this on my own. So, I really need help in solving this problem:
How do I set a column (in a table) to be NULL when another column is also NULL?
Example:
A person table with Name and Gender as its columns. In order to have a gender, the ‘Name’ column must also have an entry. If the Name is NULL, then do not allow insertion under Gender.
Oh and yes, this is related to my homework question but I have modified the example above to be different. I don’t want answers (although they’re welcomed, but I want to learn), I just want guidance. Thanks in advance.
SQL supports a feature called “check constraints” so that you can declare an expression that must be true or else the row is invalid and can’t be inserted. I.e.
CHECK Name IS NULL AND Gender IS NULL OR Name IS NOT NULL AND Gender IS NOT NULL.But unfortunately, MySQL doesn’t support check constraints. Many features of SQL are optional from the standard’s perspective and not all RDBMS implementations support all features. There are even a few features of SQL that none of the brands of RDBMS support.
The only way to do this in MySQL is to use a trigger. Before insert or update, if Name is null, then force the Gender to be null as well.
If Name is not null and Gender is null, then I assume the row is invalid, so you’ll have to use a signal to abort the insert or update.