DEV Community

Ajith R
Ajith R

Posted on

7 Essential Database Constraints Every Developer Should Know

Constraints in databases are rules that enforce data integrity and ensure that data adheres to specific conditions or requirements. These rules are applied to database tables and columns to maintain consistency, accuracy, and reliability of the data stored within the database. Constraints play a crucial role in database design, preventing the entry of invalid or inconsistent data and providing a level of control over data manipulation operations. Here are some common types of constraints found in relational databases:

1. Primary Key Constraint:

  • Ensures that each row in a table is uniquely identified by a specific column or combination of columns.
  • Primary key values cannot be null and must be unique within the table.
  • Helps enforce entity integrity and facilitates efficient data retrieval through indexing.

example
Consider a table named Employees with columns EmployeeID, FirstName, LastName, and DepartmentID. In this scenario, EmployeeID serves as the primary key column. Its constraint ensures that each employee record is uniquely identified by a unique employee ID.

CREATE TABLE Employees (
    EmployeeID INT PRIMARY KEY,
    FirstName VARCHAR(50),
    LastName VARCHAR(50),
    DepartmentID INT
);

Enter fullscreen mode Exit fullscreen mode

2. Foreign Key Constraint:

  • Establishes a relationship between two tables by referencing the primary key of one table as a foreign key in another table.
  • Ensures referential integrity, meaning that values in the foreign key column must exist in the corresponding primary key column of the referenced table or be null.
  • Helps maintain data consistency and prevents orphaned records.

example
Suppose we have another table named Departments with columns DepartmentID and DepartmentName. We want to establish a relationship between the Employees table and the Departments table. The DepartmentID column in the Employees table will act as a foreign key referencing the primary key column in the Departments table.

ALTER TABLE Employees
ADD CONSTRAINT FK_DepartmentID FOREIGN KEY (DepartmentID)
REFERENCES Departments(DepartmentID);

Enter fullscreen mode Exit fullscreen mode

3. Unique Constraint:

  • Ensures that values in a column or combination of columns are unique across all rows in the table, similar to a primary key constraint.
  • Unlike primary key constraints, unique constraints allow null values, but each non-null value must be unique.
  • Useful for enforcing business rules that require uniqueness without making the column(s) a primary key.

example
Let's say we want to ensure that each employee's email address is unique across the organization. We can apply a unique constraint to the Email column in the Employees table.


`ALTER TABLE Employees
ADD CONSTRAINT UC_Email UNIQUE (Email);
`
Enter fullscreen mode Exit fullscreen mode

4. Check Constraint:

  • Specifies a condition that must be met for the data in a column.
  • Prevents insertion or updating of data that does not satisfy the specified condition.
  • Conditions can range from simple data type checks to complex business rules.

example
Suppose we have a requirement that the Salary column in the Employees table must be greater than or equal to 0. We can enforce this rule using a check constraint.


`ALTER TABLE Employees
ADD CONSTRAINT CHK_Salary CHECK (Salary >= 0);
`
Enter fullscreen mode Exit fullscreen mode

5. Not Null Constraint:

  • Ensures that a column does not accept null values.
  • Requires every row to have a value in the specified column.
  • Useful for enforcing mandatory data entry requirements.

example
For the FirstName and LastName columns in the Employees table, we want to ensure that these fields are always filled in. We can apply a not null constraint to enforce this rule.

ALTER TABLE Employees
ALTER COLUMN FirstName VARCHAR(50) NOT NULL,
ALTER COLUMN LastName VARCHAR(50) NOT NULL;

Enter fullscreen mode Exit fullscreen mode

6. Default Constraint:

  • Specifies a default value for a column if no value is provided during insertion.
  • Automatically assigns the default value to the column when a new row is inserted without explicitly specifying a value.
  • Helps ensure data consistency and simplifies data entry. example Let's assume that every new employee is initially assigned to the "General" department by default. We can set up a default constraint for the DepartmentID column in the Employees table.
ALTER TABLE Employees
ADD CONSTRAINT DF_DepartmentID DEFAULT 1 FOR DepartmentID;

Enter fullscreen mode Exit fullscreen mode

7. Check Constraints:

  • Specifies a condition that must be met for the data in a column.
  • Prevents insertion or updating of data that does not satisfy the specified condition.
  • Conditions can range from simple data type checks to complex business rules.

example
Suppose we want to ensure that the BirthDate column in the Employees table only contains dates in the past. We can use a check constraint to enforce this rule.

ALTER TABLE Employees
ADD CONSTRAINT CHK_BirthDate CHECK (BirthDate <= GETDATE());

Enter fullscreen mode Exit fullscreen mode

Constraints are essential for maintaining data integrity and consistency in a database. By enforcing these rules, constraints help ensure that the data remains accurate, valid, and reliable over time, even as it undergoes various data manipulation operations. Properly defining and implementing constraints is crucial for creating robust and reliable database schemas that meet the requirements of the application and adhere to best practices in database design.

Top comments (0)