MySQL CONSTRAINT

Description

MySQL CONSTRAINT is used to define rules to allow or restrict what values can be stored in columns. The purpose of inducing constraints is to enforce integrity of database.
MySQL CONSTRAINTS are used to limit the type of data that can be inserted into a table.
MySQL CONSTRAINTS can be classified into two types - column level and table level.
The column level constraints can apply only to one column where as table level constraints are applied to the entire table.
MySQL CONSTRAINT are declared at the time of creating a table.

MySQL CONSTRAINTs are :

  • NOT NULL
  • UNIQUE
  • PRIMARY KEY
  • FOREIGN KEY
  • CHECK
  • DEFAULT
CONSTRAINTDESCRIPTION
NOT NULLIn Mysql NOT NULL constraint allows to specify that a column can not contain any NULL value. MySQL NOT NULL can be used to CREATE and ALTER a table.
UNIQUEThe UNIQUE constraint in Mysql does not allow to insert a duplicate value in a column. The UNIQUE constraint maintains the uniqueness of a column in a table. More than one UNIQUE column can be used in a table.
PRIMARY KEYA PRIMARY KEY constraint for a table enforces the table to accept unique data for a specific column and this constraint create a unique index for accessing the table faster.
FOREIGN KEYA FOREIGN KEY in mysql creates a link between two tables by one specific column of both table. The specified column in one table must be a PRIMARY KEY and referred by the column of another table known as FOREIGN KEY.
CHECKA CHECK constraint controls the values in the associated column. The CHECK constraint determines whether the value is valid or not from a logical expression.
DEFAULTIn a Mysql table, each column must contain a value ( including a NULL). While inserting data into a table, if no value is supplied to a column, then the column gets the value set as DEFAULT.

Syntax:

  1. CREATE  TABLE [table name]                                     
  2. ([column name] [data type]([size]) [column constraint]….  
  3. [table constraint] ([[column name]……])……);   

Explanation

The above MySQL code shows how to create a table with some constraints. Constraints are applied on columns as well as tables.

You can replace table name, column name, data type and size with your own.

Comments

Popular posts from this blog

Java program to display triangle 1 23 456 78910

Google Invests Heavily In Canada For AI Lab