Constraints in SQL

Constraint is the rule applied on the data columns of a table.

Constraint is the rule applied on the data columns of a table. They are used to check the validity of input data, ensuring the accuracy, reliability and integrity of data in the database.

Common types of constraints

Here are some of the most common constraints used in SQL.

Constraint Meaning NOT NULL Make sure the data of the column is not NULL. DEFAULT Provides a default value for a column in case the column data is not entered or not specified. UNIQUE Ensuring that the data of the column is unique, all values ​​in a column are different without duplication. PRIMARY Key Used to set the primary key on the table, the value of the column as the primary key must be unique, not duplicated. The declaration of the primary key constraint requires columns to NOT NULL. FOREIGN Key Used to set foreign keys on the table, referring to another table through the value of the linked column. The value of the linked column must be unique in the other table. CHECK Ensure all values ​​in a column satisfy some conditions. INDEX Use to create and retrieve data from the database quickly.

Constraints can be specified when you create a table with a CREATE TABLE statement or after creating a table with the ALTER TABLE statement.

Delete binding (Drop Constraint)

Any defined constraints can be deleted using the ALTER TABLE command with the DROP CONSTRAINT option.

For example, to drop Constraint primary key in NHANVIEN table, you can use the following command.

 ALTER TABLE NHANVIEN DROP CONSTRAINT NHANVIEN_PK; 

Some databases can provide shortcuts to drop the most binding in a shorter way. For example, to remove the primary key constraint for a table in Oracle, you can use the following command.

 ALTER TABLE NHANVIEN DROP PRIMARY KEY; 

In the next section, we will learn about the JOIN clause in SQL, remember to follow it.

Previous article: Sort results in SQL

Next lesson: JOIN clause in SQL

5 ★ | 1 Vote