What are database constraints

· Category: SQL & Databases

Short answer

Constraints enforce rules on data columns to ensure accuracy and reliability. Common constraints include PRIMARY KEY, FOREIGN KEY, NOT NULL, UNIQUE, and CHECK.

How it works

  • NOT NULL prevents missing values.
  • UNIQUE ensures no duplicate values in a column.
  • PRIMARY KEY uniquely identifies each row.
  • FOREIGN KEY enforces referential integrity between tables.
  • CHECK validates that a condition is true for each row.

Example

CREATE TABLE products (
  id INT PRIMARY KEY,
  sku VARCHAR(50) UNIQUE NOT NULL,
  price DECIMAL(10,2) CHECK (price > 0)
);

Why it matters

Constraints act as the last line of defense against invalid data. They protect against application bugs and enforce business rules consistently.r