Maintaining Data Integrity in MYSQL
Maintaining Data Integrity in MYSQL
Maintaining Data Integrity in MYSQL
The NOT NULL constraint enforces a column to NOT accept NULL values. The NOT NULL constraint enforces a field to always contain a value. This means that you cannot insert a new record, or update a record without adding a value to this field. The following example enforces the "P_Id" column and the "LastName" column to not
UNIQUE Constraint:
The UNIQUE constraint uniquely identifies each record in a database table. Column on which UNIQUE constraint is defined can be null or empty.
The UNIQUE and PRIMARY KEY constraints both provide a guarantee for uniqueness for a column or set of columns. A PRIMARY KEY constraint automatically has a UNIQUE constraint defined on it. We can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per table. The following example enforces the "P_Id" column must contain unique value:
mysql>CREATETABLEPersons( P_Idint,
mysql>ALTERTABLEPersons ADDUNIQUE(P_Id);
To allow naming of a UNIQUE constraint, and for defining a UNIQUE constraint on multiple columns, use the following SQL syntax:
mysql>ALTERTABLEPersons ADDCONSTRAINTuc_PersonIDUNIQUE(P_Id,LastName);
To drop a UNIQUE constraint, use the following command:
mysql>ALTERTABLEPersons DROPINDEXuc_PersonID;
mysql>ALTERTABLEPersons ADDPRIMARYKEY(P_Id);
To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY constraint on multiple columns, use the following SQL syntax:
mysql>ALTERTABLEPersons ADDCONSTRAINTpk_PersonIDPRIMARYKEY(P_Id,LastName);
To drop a PRIMARY KEY constraint, use the following syntax:
mysql>ALTERTABLEPersons DROPPRIMARYKEY;
Note that the "P_Id" column in the "Orders" table points to the "P_Id" column in the "Persons" table. The "P_Id" column in the "Persons" table is the PRIMARY KEY in the "Persons" table. The "P_Id" column in the "Orders" table is a FOREIGN KEY in the "Orders" table. The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables. The FOREIGN KEY constraint also prevents that invalid data from being inserted into the foreign key column, because it has to be one of the values contained in the table it points to. The following SQL creates a FOREIGN KEY on the "P_Id" column when the "Orders" table is created:
mysql>ALTERTABLEOrders DROPFOREIGNKEYfk_PerOrders;
DEFAULT Constraint:
The DEFAULT constraint is used to insert a default value into a column. The default value will be added to all new records, if no other value is specified. The following example creates a DEFAULT constraint on the "City" column when the "Persons" table is created:
mysql>ALTERTABLEPersons ALTERCitySETDEFAULT'SANDNES';
To drop a DEFAULT constraint, use the following syntax:
mysql>ALTERTABLEPersons ALTERCityDROPDEFAULT;