In SQL, constraints are used to define rules for the data in a table. These rules ensure the accuracy, integrity, and reliability of the data within the database.
SQL provides several types of constraints that can be applied to columns in a table:
Letβs take a look at an example of how to apply constraints to a table:
CREATE TABLE Employees (
employee_id INT PRIMARY KEY,
employee_name VARCHAR(100) NOT NULL,
salary DECIMAL(10, 2) CHECK (salary > 0),
department_id INT,
FOREIGN KEY (department_id) REFERENCES Departments(department_id)
);
In this example:
The PRIMARY KEY constraint uniquely identifies each record in a table. A primary key column cannot have duplicate or NULL values.
CREATE TABLE Students (
student_id INT PRIMARY KEY,
student_name VARCHAR(100)
);
Here, the student_id column is a primary key, ensuring each student has a unique ID.
The FOREIGN KEY constraint ensures that the value in a column matches one of the values in another table's primary key. It establishes a link between the tables and maintains referential integrity.
CREATE TABLE Orders (
order_id INT PRIMARY KEY,
order_date DATE,
customer_id INT,
FOREIGN KEY (customer_id) REFERENCES Customers(customer_id)
);
In this example, the customer_id column is a foreign key that references the customer_id column in the Customers table.
The NOT NULL constraint ensures that a column cannot have NULL values. This is important when you want to ensure that every row in a column has a valid value.
CREATE TABLE Employees (
employee_id INT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
department VARCHAR(50) NOT NULL
);
Here, the name and department columns cannot be NULL, ensuring that every employee has these details.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!