mysql – INSERT date range into date columns IF dates don’t overlap with existing ones

Sadly, using just MySQL this is impossible. Or at least, practically. The preferred way would be using SQL CHECK constraints, these are in the SQL language standard. However, MySQL does not support them.

See: https://dev.mysql.com/doc/refman/5.7/en/create-table.html

The CHECK clause is parsed but ignored by all storage engines.

It seems PostgreSQL does support CHECK constraints on tables, but I’m not sure how viable it is for you to switch database engine or if that’s even worth the trouble just to use that feature.

In MySQL a trigger could be used to solve this problem, which would check for overlapping rows before the insert/update occurs and throw an error using the SIGNAL statement. (See: https://dev.mysql.com/doc/refman/5.7/en/signal.html) However, to use this solution you’d have to use an up-to-date MySQL version.

Apart from pure SQL solutions, this typically is done in application logic, so whichever program is accessing the MySQL database typically checks for these kind of constraints by requesting every row that is violated by the new entry in a SELECT COUNT(id) ... statement. If the returned count is larger than 0 it simply doesn’t to the insert/update.

Leave a Comment