Constraints

Columns in CrateDB tables can be constrained in the following ways to enforce data integrity and consistency:

  • PRIMARY KEY

  • NULL

  • NOT NULL

  • CHECK

The values stored in constrained columns must comply with their respective constraints.


PRIMARY KEY

The PRIMARY KEY constraint enforces two important rules:

  • The column(s) must contain unique values.

  • The column(s) cannot contain NULL values.

Additionally, the primary key defines the default routing column used for sharding data across the cluster.

Example:

cr> CREATE TABLE my_table1 (
    first_column INTEGER PRIMARY KEY,
    second_column TEXT
);
CREATE OK, 1 row affected (... sec)
triangle-exclamation

Composite Primary Keys

You can define a primary key spanning multiple columns by declaring the constraint on each column individually:

Or by using an alternate syntax to declare the composite primary key as a table-level constraint:

circle-exclamation

NULL

Columns are nullable by default, meaning they can store NULL values unless specified otherwise.

You can explicitly state that a column accepts NULL values:


NOT NULL

The NOT NULL constraint prevents a column from containing NULL values, ensuring that every row has a valid value in that column.

Example:


CHECK

The CHECK constraint allows you to enforce custom rules on column values using boolean expressions. It ensures that only valid data satisfying the condition is inserted.

For example, if you have a table storing sensor metrics and want to reject negative values for a weight column:

Note: For more advanced usage, refer to the detailed CHECK documentation.

Last updated