In This Article, You Will Know About SQL Constraints.
Before moving ahead, let’s know a bit about the SQL ALTER TABLE Statement.
Table of Contents
SQL Constraints
The SQL Constraints are used to assign a specified rule on the data in a table.
SQL Create Constraints
There are mainly two ways to implement SQL Constraints –
- When the table is created with the CREATE TABLE statement
- After creating the table with the ALTER TABLE statement
Syntax
CREATE TABLE table_name (
Column_name1 column_datatype constraint,
Column_name2 column_datatype constraint,
Column_name3 column_datatype constraint,
....
);
Different SQL Constraints
The SQL Constraints are used to specify the rules on the data.
The Constraints represent the maximum number of data types a table can have. It helps to make data more readable as well as accurate to understand. If any rule doesn’t match with Constraints and data action, then action will be canceled.
Constraints can have two types of levels –
- Column level constraints apply to a column.
- Table level constraints apply to the whole table.
The following constraints are commonly used in SQL:
NOT NULL – Ensures that a column cannot have a NULL value
UNIQUE – Ensures that all values in a column are different
PRIMARY KEY – A combination of NOT NULL and UNIQUE. Uniquely identifies each row in a table
FOREIGN KEY – Prevents actions that would destroy links between tables
CHECK – Ensures that the values in a column satisfy a specific condition
DEFAULT – Sets a default value for a column if no value is specified
CREATE INDEX – Used to create and retrieve data from the database very quickly.
If you find anything incorrect in the above-discussed topic and have further questions, please comment below.
Connect on: