Not Null Constraint

The NOT NULL constraint specifies a column may not contain NULL values.

Details

  • INSERT or UPDATE statements containing NULL values are rejected. This includes INSERT statements that do not include values for any columns that do not have a DEFAULT value constraint.
    For example, if the table foo has columns a and b (and b does not have a DEFAULT VALUE), when you run the following command:
  1. > INSERT INTO foo (a) VALUES (1);

CockroachDB tries to write a NULL value into column b. If that column has the NOT NULL constraint, the INSERT statement is rejected.

  • You can only define the NOT NULL constraint when creating a table; you cannot add it to an existing table. However, you can migrate data from your current table to a new table with the constraint you want to use.

Note:
In the future we plan to support adding the NOT NULL constraint to existing tables.

Syntax

You can only apply the NOT NULL constraint to individual columns.

CREATETABLEtable_name(column_namecolumn_typeNOT NULLcolumn_constraints,column_deftable_constraints))
ParameterDescription
table_nameThe name of the table you're creating.
column_nameThe name of the constrained column.
column_typeThe constrained column's data type.
column_constraintsAny other column-level constraints you want to apply to this column.
column_defDefinitions for any other columns in the table.
table_constraintsAny table-level constraints you want to apply.

Usage example

  1. > CREATE TABLE IF NOT EXISTS customers (
  2. customer_id INT PRIMARY KEY,
  3. cust_name STRING(30) NULL,
  4. cust_email STRING(100) NOT NULL
  5. );
  1. > INSERT INTO customers (customer_id, cust_name, cust_email) VALUES (1, 'Smith', NULL);
  1. pq: null value in column "cust_email" violates not-null constraint
  1. > INSERT INTO customers (customer_id, cust_name) VALUES (1, 'Smith');
  1. pq: null value in column "cust_email" violates not-null constraint

See also

Was this page helpful?
YesNo