In SQL, constraints are rules applied to table columns that ensure the integrity, validity, and accuracy of the data stored within the database. Constraints define the data that can enter a table and help maintain data consistency. SQL supports various types of constraints to enforce these rules, and they can be applied at the column level or the table level.
Here are the most commonly used constraints in SQL:
CREATE TABLE Employees (
EmployeeID INT NOT NULL,
FirstName VARCHAR(50) NOT NULL,
LastName VARCHAR(50) NOT NULL,
HireDate DATE
);
In this example, the columns EmployeeID, FirstName, and LastName cannot contain NULL values. They must always have a value when a new record is inserted.
CREATE TABLE Employees (
EmployeeID INT NOT NULL,
Email VARCHAR(100) UNIQUE,
FirstName VARCHAR(50),
LastName VARCHAR(50)
);
In this example, the Email column must contain unique values for every row. No two employees can have the same email address.
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50)
);
Here, EmployeeID is the PRIMARY KEY. This means no two employees can have the same EmployeeID, and it cannot be NULL.
CREATE TABLE Orders (
OrderID INT,
ProductID INT,
PRIMARY KEY (OrderID, ProductID)
);
In this example, the PRIMARY KEY is made up of two columns, OrderID and ProductID, meaning that the combination of both must be unique.
CREATE TABLE Departments (
DepartmentID INT PRIMARY KEY,
DepartmentName VARCHAR(100)
);
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
DepartmentID INT,
FOREIGN KEY (DepartmentID) REFERENCES Departments(DepartmentID)
);
In this example, DepartmentID in the Employees table is a FOREIGN KEY referencing the DepartmentID in the Departments table. This means that an employee can only be assigned to a department that already exists in the Departments table.
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
Age INT CHECK (Age >= 18)
);
In this example, the CHECK constraint ensures that the value of Age must be 18 or greater. Any attempt to insert a record with an Age less than 18 will fail.
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
HireDate DATE DEFAULT CURRENT_DATE
);
In this example, if no hire date is provided when inserting a new employee, the HireDate will default to the current date.