Sobes.tech
Junior

What are constraints in SQL?

sobes.tech AI

Answer from AI

Constraints in SQL are rules applied to table columns to restrict the data types that can be inserted. They ensure data integrity.

Main types of constraints:

  • PRIMARY KEY: Uniquely identifies each record in the table. Combination of UNIQUE and NOT NULL. There can be only one primary key in a table.
  • FOREIGN KEY: Establishes a relationship between tables by referencing the primary key of another table. Ensures referential integrity.
  • UNIQUE: Ensures all values in a column are unique. Can allow NULL.
  • NOT NULL: Indicates that a column cannot contain a NULL value.
  • DEFAULT: Provides a default value for a column if no explicit value is specified during insertion.
  • CHECK: Defines a condition that must be true for each value in the column.

Example of creating a table with constraints:

CREATE TABLE Customers (
    CustomerID int NOT NULL UNIQUE, -- CustomerID cannot be NULL and must be unique
    FirstName varchar(255),
    LastName varchar(255),
    Age int CHECK (Age >= 18),  -- Age must be at least 18
    City varchar(255) DEFAULT 'London', -- Default city is London
    PRIMARY KEY (CustomerID) -- Define CustomerID as the primary key
);