Activity 14: Database Constraints

Introduction

In relational databases, constraints are rules applied to database tables to ensure data integrity and consistency. These constraints restrict the types of data that can be inserted into a table and ensure the reliability of the data within the database. Constraints help prevent invalid data from being stored in the database, ensuring that the relationships between tables are maintained and that database operations follow the necessary business rules.

There are several types of database constraints, each serving a different purpose in maintaining the accuracy and consistency of data.


Types of Database Constraints

1. Primary Key Constraint

The Primary Key constraint uniquely identifies each record in a database table. It ensures that no two rows have the same primary key value, and the values for the primary key cannot be NULL. Every table can have only one primary key, which may consist of one or more columns.

  • Example:

      CREATE TABLE employees (
          employee_id INT PRIMARY KEY,
          first_name VARCHAR(50),
          last_name VARCHAR(50)
      );
    

    In this example, the employee_id field is the primary key and must be unique for each employee.

2. Foreign Key Constraint

A Foreign Key constraint is used to establish a relationship between two tables. It ensures that the value in one table corresponds to a value in another table, thereby enforcing referential integrity. The foreign key is a field in one table that is linked to the primary key of another table.

  • Example:

      CREATE TABLE departments (
          department_id INT PRIMARY KEY,
          department_name VARCHAR(100)
      );
    
      CREATE TABLE employees (
          employee_id INT PRIMARY KEY,
          first_name VARCHAR(50),
          last_name VARCHAR(50),
          department_id INT,
          FOREIGN KEY (department_id) REFERENCES departments(department_id)
      );
    

    In this case, the department_id in the employees table is a foreign key that references the department_id in the departments table.

3. Unique Constraint

The Unique constraint ensures that all values in a column are different from one another. This is similar to the primary key constraint, but a table can have multiple unique constraints (while it can only have one primary key). Unlike a primary key, a column with a unique constraint can still allow NULL values, but only one NULL value is allowed.

  • Example:

      CREATE TABLE users (
          user_id INT PRIMARY KEY,
          username VARCHAR(50) UNIQUE
      );
    

    Here, the username field must be unique for each user, meaning no two users can have the same username.

4. Not Null Constraint

The Not Null constraint ensures that a column cannot have a NULL value. This constraint is important when the field is required for the integrity of a record. For example, if a customer must always provide a name, the name column should be set as NOT NULL.

  • Example:

      CREATE TABLE products (
          product_id INT PRIMARY KEY,
          product_name VARCHAR(100) NOT NULL,
          price DECIMAL(10, 2) NOT NULL
      );
    

    In this case, the product_name and price fields must have values and cannot be left empty (NULL).

5. Check Constraint

The Check constraint ensures that all values in a column satisfy a specific condition. This is useful for applying business rules to the data entered in the database. For example, if a product's price must be a positive number, you can use the check constraint to enforce that rule.

  • Example:

      CREATE TABLE products (
          product_id INT PRIMARY KEY,
          product_name VARCHAR(100) NOT NULL,
          price DECIMAL(10, 2) CHECK (price > 0)
      );
    

    Here, the price column must always have a value greater than 0, ensuring that products cannot be entered with a negative or zero price.

6. Default Constraint

The Default constraint automatically assigns a default value to a column if no value is specified during an insert operation. This is useful when certain fields are optional but should have a predefined value if no input is provided.

  • Example:

      CREATE TABLE orders (
          order_id INT PRIMARY KEY,
          order_date DATE DEFAULT CURRENT_DATE,
          status VARCHAR(20) DEFAULT 'Pending'
      );
    

    In this example, if no value is provided for order_date, the current date will be used, and if no status is provided, the default status will be set to 'Pending.'


Importance of Constraints in Databases

1. Data Integrity

Constraints enforce rules at the database level, ensuring that the data entered is valid, consistent, and follows the business rules. This prevents the storage of invalid data.

2. Avoiding Redundancy

With constraints like unique keys and foreign keys, you ensure that data is not duplicated unnecessarily and maintain normalized relationships between tables.

3. Improving Query Performance

Indexes are automatically created for primary and unique key constraints, which can significantly improve query performance by speeding up lookups for these columns.

4. Enforcing Business Rules

Constraints like check constraints and foreign keys help enforce specific business logic directly in the database. This ensures that certain rules (e.g., price cannot be negative) are always followed, regardless of how data is inserted into the database.

5. Security

By applying constraints, you can prevent malicious or unintended data from being inserted, thus securing your data from corruption or errors.


Examples of Common Database Constraints

Constraint TypeDescriptionExample SQL Code
Primary KeyEnsures unique identification for each record.PRIMARY KEY (id)
Foreign KeyEnforces referential integrity between two tables.FOREIGN KEY (dept_id) REFERENCES departments(dept_id)
UniqueEnsures all values in a column are unique.UNIQUE (email)
Not NullEnsures a column cannot have NULL values.first_name VARCHAR(50) NOT NULL
CheckEnforces a condition on values entered into a column.CHECK (salary > 0)
DefaultAssigns a default value to a column if no value is provided.DEFAULT 'Pending'