Constraints

What is a Constraint?

Constraints restrict the values allowed in a column. There are multiple forms of constraints:

  1. NOT NULL or UNIQUE in the column definition

  2. Check constraints

  3. Foreign Key constraints

Simple constraints like NOT NULL and UNIQUE can be added when defining a column. These constrain the column to not be NULL and only contain unique values, respectively.

Check constraints allow the database user to define more complex constraints, like ranges on numerical values.

Foreign key constraints allow you to reference and define relations between other tables in your database.

How to use Constraints

Constraints extend the definition of the data allowed in your database. Constraints programmatically enforce data quality rules as well as communicate to other database users what data to expect in the database.

You can add constraints when running CREATE TABLE statements or add them to existing tables using ALTER statements.

Difference between MySQL Constraints and Dolt Constraints

MySQL and Dolt constraints are functionally equivalent.

Interaction with Dolt Version Control

Constraints can cause merge conflicts. If two different constraints on the same column are merged, it is a merge conflict.

Foreign key constraints can cause merged databases to become inconsistent. For instance, you have a foreign key relationship between two tables. On one branch, you add a reference to a parent value that exists. On the other branch you delete the parent value. This will be a valid merge but the parent value will no longer exist.

Another case is foreign key constraints that trigger changes on other tables like DELETE CASCADE are not triggered on merge. Merges happen at the storage layer, not at the SQL layer. This can get your database into a invalid state. Merge reports this invalid state and you must resolve it before making a Dolt commit.

Example

Inconsistent state after merge

Last updated