I have two columns (among others) in a database table: ExitDate and ExitReason. Our business logic requires that ExitReason be specified if ExitDate is specified. The ExitDate column needs to allow nulls since the value is not always known at the time of insert. Is there a way to make the ExitReason column allow nulls only if the ExitDate value is null? I could accomplish the effect by splitting these two columns into a separate ‘exit dates’ table and making them both non-nullable, but it would be nice if I wouldn’t have to.
Ideas? Thanks!
Assuming you are on SQL Server or something similar, you can do this with a
CHECKconstraint on your table. (Unfortunately, MySQL parses but ignoresCHECKconstraints, so you’d have to use a trigger for that platform.)If the table already exists:
If you are creating the table yourself:
Using a check constraint is preferable to using a trigger because: