Wednesday, December 18, 2024

SQL Constraints

 SQL constraints are rules that define certain properties for the data in a database. They help ensure data integrity, accuracy, and reliability. Here are the main types of SQL constraints:

  1. NOT NULL: Ensures that a column cannot have a NULL value. Every row must have a value for that column.

    CREATE TABLE Employees (
        ID INT NOT NULL,
        Name VARCHAR(100) NOT NULL
    );
    
  2. UNIQUE: Ensures that all values in a column or a set of columns are distinct across all rows.

    CREATE TABLE Employees (
        ID INT UNIQUE,
        Email VARCHAR(100) UNIQUE
    );
    
  3. PRIMARY KEY: A combination of NOT NULL and UNIQUE that uniquely identifies each row in a table. There can only be one primary key in a table.

    CREATE TABLE Employees (
        ID INT PRIMARY KEY,
        Name VARCHAR(100)
    );
    
  4. FOREIGN KEY: Ensures that a value in one table matches a value in another table, thereby maintaining referential integrity.

    CREATE TABLE Orders (
        OrderID INT PRIMARY KEY,
        CustomerID INT,
        FOREIGN KEY (CustomerID) REFERENCES Customers(ID)
    );
    
  5. CHECK: Ensures that values in a column meet a specified condition.

    CREATE TABLE Employees (
        Age INT CHECK (Age >= 18)
    );
    
  6. DEFAULT: Provides a default value for a column when no value is specified.

    CREATE TABLE Employees (
        ID INT,
        Name VARCHAR(100),
        HireDate DATE DEFAULT CURRENT_DATE
    );
    
  7. INDEX: An index improves the speed of data retrieval. It can be created on one or more columns.

    CREATE INDEX idx_name ON Employees (Name);
    

These constraints are typically defined during table creation but can also be added or modified using ALTER TABLE. Constraints help ensure that the data adheres to specific rules, making the database more consistent and reliable.

No comments:

Post a Comment