BenLanc
BenLanc

Reputation: 2434

Complex unique constraints with MySQL

Consider the following table:

CREATE TABLE `demo` (
  `id` BIGINT(20) NOT NULL AUTO_INCREMENT,
  `from_val` BIGINT(20) DEFAULT NULL,
  `to_val` BIGINT(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
);

Is it possible to create a constraint that prevents a second record existing in the same table with a from_val or to_val between another record's from_val and to_val? So, from an empty table the second query should fail with a constraint failure:

INSERT INTO `demo` (`from_val`, `to_val`) VALUES (1,10),(11,20);
INSERT INTO `demo` (`from_val`, `to_val`) VALUES (5,15);

Validating the data on the way in/update is trivial, I was just curious to see whether MySQL could enforce this at a RDBMS level.

Upvotes: 1

Views: 346

Answers (1)

spencer7593
spencer7593

Reputation: 108380

No, MySQL does not support (or enforce) any declarative constraint which would raise an exception given the conditions you specify.

The values in the tuple (5,15) ("the second query") do not conflict with any values in any of the rows previously inserted into the table... (1,10),(11,20), at least in terms of what is available to declarative constraints in MySQL.

The workaround is to define BEFORE INSERT and BEFORE UPDATE triggers on the table; those can perform whatever checks you need, and raise an exception.

Upvotes: 2

Related Questions