SQL Constraints

SQL Constraints

SQL Constraints

SQL constraints are used to specify rules for the data(Information) in a table.

Constraints are the principles enforced on the data columns of a table. These are used to limit the sort of knowledge which will enter into a table. This ensures the accuracy and reliability of the data within the database.

Constraints are often divided into the subsequent two types:

  1. Column level constraints: Limits only column data.
  2. Table level constraints: Limits whole table data.

Some of the most commonly used constraints available in SQL are:

    • NOT NULL: This constraint tells us that we cannot store a null value in a column. That is, if a column is specified as NOT NULL then we’ll not be able to store null in this particular column anymore.
    • UNIQUE: This constraint when specified with a column, tells that all the values within the column must be unique. That is, the values in any row of a column must not be repeated.
    • PRIMARY KEY: A primary key’s a field that can uniquely identify each row in a table. And this constraint is used to specify a field in a table as a primary key.
    • FOREIGN KEY: A Foreign key is a field that can uniquely identify each row in another table. And this constraint is used to specify a field as Foreign key.
    • CHECK: This constraint helps to validate the values of a column to satisfy a specific condition. That is, it helps to ensure that the value stored in a column satisfies a specific condition.
    • DEFAULT: This constraint specifies a default value for the column when no value is specified by the user.
    • INDEX– Used to create and retrieve data from the database very quickly

#How to specify constraints?

We can specify constraints at the time of creating the table using the CREATE TABLE statement. We can also specify the constraints after creating a table using the ALTER TABLE statement.

Syntax:

CREATE TABLE table_name (
    column1 datatype constraint,
    column2 datatype constraint,
    column3 datatype constraint,
    ....
);

I hope this post helps you to understand all the SQL constraints in Database Management System and its implementation.

Keep learning 🙂

1 thought on “SQL Constraints”

Leave a Reply

Your email address will not be published. Required fields are marked *