Skip to content
Advertisement

SQL check constraint with multiple conditions

I have a table called timesheets. In that table there are 4 columns for which I want to create a constraint so that only the following combinations are possible:

  • If user_is is set then task_schedule_id must be null.
  • If location_id or customer_id is set, then require user_id to be not null and ensure that not both location_id and customer_id are set.
  • If task_schedule_id is set then require user_id, customer_id and location_id to be null.

This is the table:

And this is what I have so far:

The context is that a task_schedule links to a task which can contain a location_id and or a customer_id. The idea is that timesheets can be created globally or in combination with tasks.

Advertisement

Answer

You can write the constraints as:

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement