Is it possible to have a unique constraint such that one particular column has a value only once?
For instance
-----------------------
name | pri
Putting a simple unique constraint over all three columns would not work because it would allow the following:
name | price | default
-----------------------
XYZ | 20 | TRUE
XYZ | 30 | TRUE
XYZ | 40 | FALSE
ABC | 50 | FALSE
In other SQL engines, you could just create a check constraint that ensures that for every set of name
rows, the number of those rows with default = TRUE
is <= 1. However, MySQL does not support enforcing check constraints.
In MySQL you could implement this via insert
and update
triggers instead:
CREATE TRIGGER `before_insert` BEFORE INSERT ON `tableName`
FOR EACH ROW
BEGIN
DECLARE @sum INT
SELECT @sum = SUM(CASE WHEN [default] = TRUE THEN 1 ELSE 0 END)
FROM tableName
WHERE [name] = new.[name]
IF (@sum = 0 OR new.default = FALSE)
BEGIN
INSERT INTO tableName (name, price, default)
VALUES (new.[name], new.[price], new.[defaul]t)
END
END
And similarly for the update
.