SQL Tutorial: Employee & Client Tables with Constraints and Foreign Key

SQL Tutorial – Employee and Client Tables with Constraints and Foreign Key

This tutorial demonstrates how to create Employee and Client tables in SQL with appropriate data types, constraints, and foreign key relationships. 

1. Employee Table Schema

SQL CREATE TABLE statement:

CREATE TABLE Employee (
    Emp_id INT PRIMARY KEY,
    Name VARCHAR(50) NOT NULL,
    Department VARCHAR(50) NOT NULL,
    Salary DECIMAL(10,2) CHECK (Salary >= 0),
    Joining_Year YEAR
);

Employee Table Data Example

Emp_idNameDepartmentSalaryJoining_Year
101ArifaHR350002020
102LaboniIT550002021
103ShabnamFinance480002019
104MituIT600002022
105HasnaMarketing420002020

2. Client Table Schema with Foreign Key

SQL CREATE TABLE statement:

CREATE TABLE Client (
    Client_id INT PRIMARY KEY,
    Name VARCHAR(50) NOT NULL,
    Contact_no VARCHAR(15) UNIQUE,
    Email VARCHAR(50) UNIQUE,
    City VARCHAR(50),
    Department VARCHAR(50),
    CONSTRAINT fk_department
        FOREIGN KEY (Department)
        REFERENCES Employee(Department)
        ON DELETE SET NULL
        ON UPDATE CASCADE
);

Client Table Data Example

Client_idNameContact_noEmailCityDepartment
201Rafia017XXXXXXXXrafia@mail.comDhakaHR
202Sabrina018XXXXXXXXsabrina@mail.comChittagongIT
203Karima019XXXXXXXXkarima@mail.comDhakaFinance

3. Explanation of Data Types and Constraints

  • Emp_id / Client_id: INT, serves as PRIMARY KEY for unique identification.
  • Name: VARCHAR(50), NOT NULL to ensure a name is provided.
  • Department: VARCHAR(50), FOREIGN KEY in Client referencing Employee.Department to maintain referential integrity.
  • Salary: DECIMAL(10,2) with CHECK to prevent negative values.
  • Contact_no / Email: VARCHAR with UNIQUE to prevent duplicates.
  • Joining_Year: YEAR data type to store the joining year of employees.

4. Foreign Key Behavior

  • ON DELETE SET NULL: If a department is deleted from Employee, the Client’s Department will be set to NULL.
  • ON UPDATE CASCADE: If a department name is updated in Employee, the Client table will automatically reflect the change.


কোন মন্তব্য নেই:

একটি মন্তব্য পোস্ট করুন