what is sql-constraints | type of SQL Constraints

7/14/2021

What Are SQL Constraints?

Go Back

What Are SQL Constraints?

SQL constraints are used to enforce business rules and ensure data integrity in a database. They define rules to restrict or allow specific values in database columns, preventing invalid data entry.

Types of SQL Constraints

SQL provides several types of constraints to maintain accuracy and reliability in database tables:

  1. NOT NULL

    • Ensures that a column cannot contain NULL values.
    • Used during CREATE and ALTER table statements.
  2. UNIQUE

    • Ensures that all values in a column are distinct.
    • More than one UNIQUE column can exist in a table.
  3. PRIMARY KEY

    • Ensures each record in a table is unique.
    • A PRIMARY KEY constraint automatically creates a unique index to improve query performance.
  4. FOREIGN KEY (Referential Key)

    • Establishes a link between two tables using a specific column.
    • The referenced column must be a PRIMARY KEY in another table.
  5. CHECK

    • Ensures that the values in a column meet a specific condition.
    • Determines whether the value entered is valid or not based on a logical expression.
What Are SQL Constraints?

Declaring Constraints in SQL

Constraints can be declared at the column level (directly in the column definition) or at the table level (after all column declarations). Table-level constraints are useful when multiple columns participate in the constraint.

Example: PRIMARY KEY Constraint

The following SQL query demonstrates how to create a table with a PRIMARY KEY constraint:

CREATE TABLE Student (
    roll_no VARCHAR(7),
    name VARCHAR(20),
    address VARCHAR(50),
    tot_marks INT,
    branch VARCHAR(6),
    PRIMARY KEY (roll_no)
);

Conclusion

In this article, we explored SQL constraints and their importance in maintaining database integrity. By using constraints, we can restrict specific actions on table data and ensure accurate and reliable information storage.

If you have any questions, feel free to reach out to us!

Table of content