Hello! Today we want to talk about SQL constraints, which can be used in all data storage systems. These constraints help us ensure that our data interactions are logical and accurate, and they prevent storing invalid data. In essence, constraints are rules that are applied to the columns of tables so that we can have greater accuracy in the information we hold.
One of the primary constraints we often encounter is the NOT NULL
constraint. This constraint ensures that a particular column must have a value and cannot be empty. This is particularly relevant for cases where a data field must always be present.
Another significant constraint is UNIQUE
. This constraint prevents duplicate values from being entered into a column. This feature allows us to ensure that each record has a unique identifier, and the structure of the data remains intact.
The PRIMARY KEY
constraint is a combination of NOT NULL
and UNIQUE
. This constraint specifically identifies the primary key of a table and means that every table must have at least one column that can serve as the main key.
The FOREIGN KEY
constraint is also highly useful and defines the relationship between two tables. This constraint ensures that a column in one table refers to a valid record in another table, which helps maintain integration between data.
Ultimately, the CHECK
constraint allows us to place a condition on data entries. This means that a specific condition can be defined that must be met for the data to be accepted.
CREATE TABLE Students (
ID INT NOT NULL PRIMARY KEY,
Name VARCHAR(100) NOT NULL,
Email VARCHAR(100) UNIQUE,
Age INT CHECK (Age >= 18),
SchoolID INT,
FOREIGN KEY (SchoolID) REFERENCES Schools(ID)
);
This is an example of how constraints are defined in SQL.
ID INT NOT NULL PRIMARY KEY
: Ensures that the ID
column cannot be NULL
and must contain a value.
Name VARCHAR(100) NOT NULL
: The Name
column must contain a value and cannot be empty.
Email VARCHAR(100) UNIQUE
: Ensures that the values in the Email
column are not duplicated.
Age INT CHECK (Age >= 18)
: Adds a condition that the student's age must be at least 18.
FOREIGN KEY (SchoolID) REFERENCES Schools(ID)
: Ensures that the value of SchoolID
points to a valid ID in the Schools
table.