Sobes.tech
Junior

How to add constraints to a database?

sobes.tech AI

Answer from AI

Constraints in a database are added when creating a table (ALTER TABLE) or modifying an existing table (ALTER TABLE).

Main types of constraints in SQL:

  • NOT NULL: Ensures that a column cannot contain missing values.
  • UNIQUE: Ensures that all values in a column (or a combination of columns) are unique.
  • PRIMARY KEY: A combination of NOT NULL and UNIQUE. Uniquely identifies each row in a table.
  • FOREIGN KEY: Links tables by referencing the PRIMARY KEY in another table. Ensures referential integrity.
  • CHECK: Ensures that all values in a column satisfy a specific condition.
  • DEFAULT: Sets a default value for a column if no value is specified during insertion.

Examples:

-- Adding a NOT NULL constraint when creating a table
CREATE TABLE Users (
    UserID INT NOT NULL,
    UserName VARCHAR(255) NOT NULL
);
-- Adding a UNIQUE constraint to an existing column
ALTER TABLE Emails
ADD UNIQUE (EmailAddress);
-- Adding a PRIMARY KEY constraint when creating a table
CREATE TABLE Products (
    ProductID INT PRIMARY KEY,
    ProductName VARCHAR(255)
);
-- Adding a FOREIGN KEY constraint to an existing column
ALTER TABLE Orders
ADD FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID);
-- Adding a CHECK constraint when creating a table
CREATE TABLE Products (
    ProductID INT PRIMARY KEY,
    Price DECIMAL(10, 2) CHECK (Price > 0)
);
-- Adding a DEFAULT constraint when creating a table
CREATE TABLE Statuses (
    StatusID INT,
    StatusName VARCHAR(50) DEFAULT 'Pending'
);
How to add constraints to a database? — Java - sobes.tech