Database Triggers for Data Integrity: Enforcing Department IDs and Job Hierarchies
This is an example of a database schema that uses triggers to enforce data integrity. The schema includes several tables: employees
, departments
, job_hierarchies
, and department_employees
.
Here’s a breakdown of the tables and their relationships:
Employees Table
- The table has columns for employee ID, name, department ID, job title, and start date.
- The column names are
EmployeeID
,Name
,DepartmentID
,JobTitle
, andStartDate
.
Departments Table
- The table has columns for department ID and department name.
- The column names are
DepartmentID
andDepartmentName
.
Job Hierarchies Table
- The table has columns for job hierarchy ID, parent job title, and child job title.
- The column names are
JobHierarchyID
,ParentJobTitle
, andChildJobTitle
.
Department Employees Table
- The table has columns for department employee ID, department ID, employee ID, and hire date.
Here’s a breakdown of the triggers:
Check Constraint on Department ID in Employees Table
- The trigger checks that the value in the
DepartmentID
column matches an existing value in theDepartments
table. - If it doesn’t match, the update operation fails.
- The trigger checks that the value in the
Update Trigger on Department Employees Table
- When data is inserted into the
DepartmentEmployees
table, a corresponding record is also created in theJobHierarchies
table to maintain the hierarchical structure of job titles. - The new department employee ID becomes the parent ID for its respective child job title.
- When data is inserted into the
Update Trigger on Department Employees Table (Continued)
- When data is updated in the
DepartmentEmployees
table, the corresponding records are also updated in theJobHierarchies
table to maintain the hierarchical structure of job titles. - The updated department employee ID becomes the parent ID for its respective child job title.
- When data is updated in the
Delete Trigger on Department Employees Table
- When a record is deleted from the
DepartmentEmployees
table, the corresponding records are also deleted from theJobHierarchies
table to maintain the hierarchical structure of job titles. - The removed department employee ID becomes NULL for its respective child job title.
- When a record is deleted from the
Delete Trigger on Employees Table
- When a record is deleted from the
Employees
table, all corresponding records are also deleted from theDepartmentEmployees
table and theJobHierarchies
table to maintain data consistency.
- When a record is deleted from the
These triggers ensure that:
- Only valid department IDs can be used in the
Employees
table. - The hierarchical structure of job titles is maintained through the use of
JobHierarchyID
,ParentJobTitle
, andChildJobTitle
columns. - When employees are added or removed, their corresponding records are also updated or deleted from other tables to maintain data consistency.
Last modified on 2024-03-19