1. SQL Constraints:

SQL constraints are rules that define certain properties of the data in a database. Constraints ensure the accuracy and reliability of data stored in the database. The most common types of SQL constraints are:

a) NOT NULL Constraint
  • Ensures that a column cannot have a NULL value.
  • Example:
CREATE TABLE Employees (
    ID INT NOT NULL,
    Name VARCHAR(100) NOT NULL
);
b) UNIQUE Constraint
    • Ensures that all values in a column are distinct.
    • Example:
CREATE TABLE Employees (
    ID INT PRIMARY KEY,
    Email VARCHAR(100) UNIQUE
);
c) PRIMARY KEY Constraint
  • A combination of NOT NULL and UNIQUE.
  • Ensures that a column (or a combination of columns) uniquely identifies each row in a table.
  • Example:
CREATE TABLE Employees (
    ID INT PRIMARY KEY,
    Name VARCHAR(100)
);
d) FOREIGN KEY Constraint
  • Ensures that a column’s value matches a value in another table, creating a relationship between tables.
  • Example:
CREATE TABLE Orders (
    OrderID INT PRIMARY KEY,
    CustomerID INT,
    FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)
);
e) CHECK Constraint
  • Ensures that the values in a column satisfy a specific condition.
  • Example:
CREATE TABLE Employees (
    Age INT CHECK (Age >= 18)
);
f) DEFAULT Constraint
  • Provides a default value for a column when no value is specified.
  • Example:
CREATE TABLE Employees (
    JoiningDate DATE DEFAULT CURRENT_DATE
);