SQL Tutorial

SQL Introduction SQL Aggregate Functions SQL Aliases SQL And SQL Any All SQL Avg SQL Between SQL Case SQL Comments SQL Count SQL Delete SQL Distinct SQL Exists SQL Groupby SQL Having SQL In SQL Insert_into SQL Is Not Null SQL Join SQL Full Outer Join SQL Inner Join SQL Left Join SQL Right Join SQL Self Join SQL Like SQL Min Max SQL NOT Operator SQL Null SQL Operators SQL OR operator SQL OrderBy SQL Select SQL Select Into SQL Top Limit Fetch SQL Store Procedures SQL Sum SQL Union SQL Update SQL Where SQL Wildcards

SQL Database

SQL Alter Table SQL Auto increment SQL BackupDB SQL Check SQL Constrains SQL Create View SQL CreateDB SQL CreateTable SQL Data types SQL Dates SQL DefaultConstrain SQL DropDB SQL DropTable SQL Foreign Key SQL Hosting SQL Index SQL injections SQL Not NULL SQL PrimaryKey SQL Unique SQL Views

SQL FOREIGN KEY Tutorial

Example Tables

We will create two tables named departments and employees to demonstrate the SQL FOREIGN KEY constraint:


    CREATE TABLE departments (
        department_id INT PRIMARY KEY,
        department_name VARCHAR(100)
    );

    CREATE TABLE employees (
        employee_id INT PRIMARY KEY,
        employee_name VARCHAR(100),
        department_id INT,
        FOREIGN KEY (department_id) REFERENCES departments(department_id)
    );
    

Creating the Tables

To create the tables, use the following SQL commands:


    CREATE TABLE departments (
        department_id INT PRIMARY KEY,
        department_name VARCHAR(100)
    );

    CREATE TABLE employees (
        employee_id INT PRIMARY KEY,
        employee_name VARCHAR(100),
        department_id INT,
        FOREIGN KEY (department_id) REFERENCES departments(department_id)
    );
    

Result:

Command CREATE TABLE departments (department_id INT PRIMARY KEY, department_name VARCHAR(100));
Result
  • A table named departments is created.
Command CREATE TABLE employees (employee_id INT PRIMARY KEY, employee_name VARCHAR(100), department_id INT, FOREIGN KEY (department_id) REFERENCES departments(department_id));
Result
  • A table named employees is created with a foreign key constraint on department_id.

Inserting Data

To insert data into the tables, use the following SQL commands:


    INSERT INTO departments (department_id, department_name) VALUES (1, 'HR'), (2, 'Engineering');

    INSERT INTO employees (employee_id, employee_name, department_id) VALUES (1, 'John Doe', 1), (2, 'Jane Smith', 2);
    

Result:

Command INSERT INTO departments (department_id, department_name) VALUES (1, 'HR'), (2, 'Engineering');
Result
  • Data is inserted into the departments table.
Command INSERT INTO employees (employee_id, employee_name, department_id) VALUES (1, 'John Doe', 1), (2, 'Jane Smith', 2);
Result
  • Data is inserted into the employees table.

Important Considerations

When using foreign keys, ensure that: