Skip to content
Advertisement

Constraints using If structure

I got a data table and require some custom constraints. The data table is as following:

ID    int
Val_1 int
Val_2 int
Val_3 int

What i need is the following:

If (Val_1 == A)
{
    Val_2 cant be NULL;
} 
else if (Val_1 == B)
{
    Val_3 cant be NULL;
}
else if (Val_1 == C)
{
    Val_2 AND Val_3 cant be NULL;
}
else if (Val_1 == D)
{
    Val_2 OR Val_3 cant be NULL;
}

Is something like this even possible?

Advertisement

Answer

Please note that MySQL CHECK constraints are only enforced starting on MySQL 8.0.16. Before that, they are accepted and silently ignored.

Assuming you are using MySQL 8.0.16 or newer, you can do:

create table t (
  id varchar(1),
  val_1 int,
  val_2 int,
  val_3 int,
  constraint my_extra_constraint check (
    val_1 = 'A' and val_2 is not null or
    val_1 = 'B' and val_3 is not null or
    val_1 = 'C' and val_2 is not null and val_3 is not null or
    val_1 = 'D' and (val_2 is not null or val_3 is not null)
    or val_1 not in ('A', 'B', 'C', 'D') -- remove this line if needed
  )
);
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement