SQL constraints for data integrity in CockroachDB - PRIMARY KEY, FOREIGN KEY, UNIQUE, CHECK, and more
Constraints enforce data integrity rules at the database level. CockroachDB supports all standard SQL constraints plus additional features for distributed systems.
Control what happens when referenced rows are updated or deleted.
-- Delete child rows when parent is deletedCREATE TABLE orders ( id INT PRIMARY KEY, user_id INT REFERENCES users(id) ON DELETE CASCADE);-- Deleting a user also deletes their ordersDELETE FROM users WHERE id = 1;
Foreign key checks can impact write performance in distributed systems. Each foreign key validation requires a read from the referenced table.
-- For better performance, ensure foreign key columns are indexedCREATE TABLE orders ( id INT PRIMARY KEY, user_id INT REFERENCES users(id));-- Create index on foreign key columnCREATE INDEX orders_user_id_idx ON orders (user_id);
Validates column values against a boolean expression.
Simple Check
Named Check
Multi-Column Check
Complex Expressions
CREATE TABLE products ( id INT PRIMARY KEY, name TEXT, price DECIMAL(10, 2) CHECK (price > 0), stock INT CHECK (stock >= 0));-- This insert failsINSERT INTO products VALUES (1, 'Widget', -10, 5);-- ERROR: check constraint "products_price_check" violated
CREATE TABLE users ( id INT PRIMARY KEY, age INT, email VARCHAR(255), CONSTRAINT chk_adult_age CHECK (age >= 18), CONSTRAINT chk_valid_email CHECK (email LIKE '%@%'));
CREATE TABLE date_ranges ( id INT PRIMARY KEY, start_date DATE, end_date DATE, CHECK (end_date > start_date));CREATE TABLE discounts ( id INT PRIMARY KEY, percent_off DECIMAL(5, 2), flat_amount DECIMAL(10, 2), CHECK ( (percent_off IS NOT NULL AND flat_amount IS NULL) OR (percent_off IS NULL AND flat_amount IS NOT NULL) ));
CREATE TABLE orders ( id INT PRIMARY KEY, status TEXT CHECK (status IN ('pending', 'processing', 'shipped', 'delivered')), total DECIMAL(10, 2), tax DECIMAL(10, 2), CHECK (tax >= 0 AND tax <= total * 0.5));CREATE TABLE coordinates ( id INT PRIMARY KEY, latitude DECIMAL(10, 8), longitude DECIMAL(11, 8), CHECK (latitude BETWEEN -90 AND 90), CHECK (longitude BETWEEN -180 AND 180));
CHECK constraints cannot reference other tables or use subqueries. They are evaluated per row only.
Provides default values when no value is specified.
Constant Defaults
Function Defaults
Expression Defaults
Named Default
CREATE TABLE users ( id INT PRIMARY KEY, username VARCHAR(50) NOT NULL, status VARCHAR(20) DEFAULT 'active', role VARCHAR(20) DEFAULT 'user', login_count INT DEFAULT 0);-- Uses defaultsINSERT INTO users (id, username) VALUES (1, 'alice');
Disabling constraints can lead to data inconsistency. Use only for data migration or repair scenarios.
-- Foreign key constraint checking cannot be disabled in CockroachDB-- Instead, drop and recreate the constraint:ALTER TABLE orders DROP CONSTRAINT fk_orders_user;-- Perform data operations-- ...-- Recreate constraint with validationALTER TABLE orders ADD CONSTRAINT fk_orders_user FOREIGN KEY (user_id) REFERENCES users(id);
-- Comments can belong to posts or photosCREATE TABLE comments ( id INT PRIMARY KEY, commentable_type TEXT NOT NULL, commentable_id INT NOT NULL, content TEXT, CHECK (commentable_type IN ('Post', 'Photo')), UNIQUE (commentable_type, commentable_id));
CREATE TABLE users ( id INT PRIMARY KEY, type TEXT CHECK (type IN ('individual', 'business')), ssn VARCHAR(11), tax_id VARCHAR(20), -- Individuals must have SSN, businesses must have TAX_ID CHECK ( (type = 'individual' AND ssn IS NOT NULL) OR (type = 'business' AND tax_id IS NOT NULL) ));
CREATE TABLE audit_log ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), table_name TEXT NOT NULL, operation TEXT NOT NULL CHECK (operation IN ('INSERT', 'UPDATE', 'DELETE')), changed_by TEXT NOT NULL, changed_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, CHECK (changed_at <= CURRENT_TIMESTAMP));