Sobes.tech
Junior — Middle

What constraints and integrity constraints are applicable in PostgreSQL?

sobes.tech AI

Answer from AI

PostgreSQL uses various constraints and integrity restrictions that help maintain data correctness and consistency:

  • NOT NULL — prohibits storing NULL in the specified column.
  • UNIQUE — ensures all values in a column or group of columns are unique.
  • PRIMARY KEY — a unique identifier for a row, combining UNIQUE and NOT NULL.
  • FOREIGN KEY — enforces referential integrity between tables, ensuring that a value in a column exists in another table.
  • CHECK — allows setting an arbitrary condition that values in a column must satisfy.
  • EXCLUSION — ensures that for specified columns, there are no overlapping values based on a certain condition (e.g., for time intervals).

Example of a constraint:

CREATE TABLE employees (
    id SERIAL PRIMARY KEY,
    email VARCHAR(255) UNIQUE NOT NULL,
    department_id INT REFERENCES departments(id),
    salary NUMERIC CHECK (salary > 0)
);

Here, email cannot be NULL and must be unique, department_id references the departments table, and salary must be a positive number.

These constraints help prevent errors during data entry and ensure database integrity.

What constraints and integrity constraints are… - sobes.tech