SQL JOINs & Relational Database: Complete Master Notes

Master SQL JOINs (INNER, LEFT, RIGHT, FULL OUTER, CROSS, SELF, MULTIPLE JOINs) from scratch to depth with clear definitions, relational table architecture, syntax highlighting in dark mode, WHERE vs HAVING filters, grouping, and a complete runnable MySQL script.

1. Database Create Karna & Select Karna

Definition

CREATE DATABASE ka use new database create karne ke liye hota hai. USE database_name; active session ke liye database ko select/activate karta hai taki saari aage wali tables us database ke andar banein.

Important Concept

USE office; execute karne ke baad, hum jo bhi CREATE TABLE ya INSERT queries chalayenge, woh automatically office database container ke andar execute honge.

</> SQL
CREATE DATABASE office;

USE office;

2. Relational Table Structure (ER Diagram)

Hum is master guide mein 4 Relational Tables banayenge: departments, employees, projects, aur employee_projects (Bridge Table).

departments | | department_id (Primary Key -> Foreign Key) | employees | | employee_id (Primary Key -> Foreign Key) | employee_projects (Bridge / Junction Table) | | project_id (Foreign Key <- Primary Key) | projects

3. Table Creation & Constraints Explanation

A. Departments Table

</> SQL
CREATE TABLE departments (
    department_id INT PRIMARY KEY AUTO_INCREMENT,
    department_name VARCHAR(50) NOT NULL,
    location VARCHAR(50)
);

B. Employees Table (with Foreign Key)

</> SQL
CREATE TABLE employees (
    employee_id INT PRIMARY KEY AUTO_INCREMENT,
    employee_name VARCHAR(50) NOT NULL,
    email VARCHAR(100) UNIQUE,
    salary DECIMAL(10,2),
    department_id INT,
    manager_id INT,
    
    FOREIGN KEY (department_id)
    REFERENCES departments(department_id)
);

C. Projects Table

</> SQL
CREATE TABLE projects (
    project_id INT PRIMARY KEY AUTO_INCREMENT,
    project_name VARCHAR(100) NOT NULL,
    project_budget DECIMAL(12,2)
);

D. Employee Projects Table (Bridge Table with Composite Primary Key)

</> SQL
CREATE TABLE employee_projects (
    employee_id INT,
    project_id INT,
    
    PRIMARY KEY (employee_id, project_id),
    
    FOREIGN KEY (employee_id)
    REFERENCES employees(employee_id),
    
    FOREIGN KEY (project_id)
    REFERENCES projects(project_id)
);

4. Sample Data Insertion

Data insert karenge standard INSERT INTO command se. Notice that employee Neha has NULL department_id (helps us understand LEFT JOIN & NULL handling).

</> SQL
-- Departments Data
INSERT INTO departments (department_name, location)
VALUES
('HR', 'Chandigarh'),
('IT', 'Mohali'),
('Sales', 'Chandigarh'),
('Finance', 'Panchkula'),
('Marketing', 'Ludhiana');

-- Employees Data (Neha has department_id NULL)
INSERT INTO employees (employee_name, email, salary, department_id, manager_id)
VALUES
('Gagan', 'gagan@gmail.com', 45000, 2, NULL),
('Rahul', 'rahul@gmail.com', 35000, 2, 1),
('Aman', 'aman@gmail.com', 40000, 3, 4),
('Priya', 'priya@gmail.com', 50000, 1, NULL),
('Simran', 'simran@gmail.com', 38000, 4, 4),
('Neha', 'neha@gmail.com', 42000, NULL, NULL);

-- Projects Data
INSERT INTO projects (project_name, project_budget)
VALUES
('Website Development', 200000),
('Data Analytics', 300000),
('CRM System', 250000),
('Marketing Campaign', 150000);

-- Employee Projects Bridge Data
INSERT INTO employee_projects (employee_id, project_id)
VALUES
(1, 1), (1, 2), (2, 1), (3, 3), (4, 4), (5, 2);

5. INNER JOIN Deep Dive

Simple Definition

INNER JOIN sirf woh records return karta hai jinka dono tables (Table 1 aur Table 2) mein matching record available ho based on the ON condition.

Why Neha is Omitted?

Neha ka department_id NULL hai, isliye employees.department_id = departments.department_id match nahi hota, aur Neha result mein nahi aati.

</> SQL
SELECT
    employees.employee_name,
    departments.department_name
FROM employees
INNER JOIN departments
ON employees.department_id = departments.department_id;
Query Result Output
employee_namedepartment_name
GaganIT
RahulIT
AmanSales
PriyaHR
SimranFinance

6. LEFT JOIN Deep Dive

Simple Definition

LEFT JOIN (ya LEFT OUTER JOIN) Left Table ke saare records return karta hai, chahe Right Table mein matching record ho ya na ho. Agar right table mein match na ho, toh NULL values aati hain.

Why Neha Appears Here?

Left table employees mein Neha hai. Right table departments mein match na hone ki wajah se department_name column mein NULL display hoga.

</> SQL
SELECT
    employees.employee_name,
    departments.department_name
FROM employees
LEFT JOIN departments
ON employees.department_id = departments.department_id;
Query Result Output
employee_namedepartment_name
GaganIT
RahulIT
AmanSales
PriyaHR
SimranFinance
NehaNULL

7. RIGHT JOIN Deep Dive

Simple Definition

RIGHT JOIN (ya RIGHT OUTER JOIN) Right Table ke saare records return karta hai, chahe Left Table mein matching record ho ya nahi.

Why Marketing Appears Here?

Right table departments mein Marketing department hai jisme koi employee nahi hai. Right Join execution mein Marketing department aayega aur employee_name NULL dikhayega.

</> SQL
SELECT
    employees.employee_name,
    departments.department_name
FROM employees
RIGHT JOIN departments
ON employees.department_id = departments.department_id;
Query Result Output
employee_namedepartment_name
GaganIT
RahulIT
AmanSales
PriyaHR
SimranFinance
NULLMarketing

8. FULL OUTER JOIN (using UNION in MySQL)

Simple Definition

FULL OUTER JOIN dono tables ke saare records ko combine karke dikhata hai. Jinka match hota hai woh match hote hain, baaki jagah NULL show hota hai.

MySQL Solution (LEFT JOIN + RIGHT JOIN + UNION)

MySQL mein direct FULL OUTER JOIN syntax supported nahi hota. Isliye hum LEFT JOIN aur RIGHT JOIN queries ko UNION se combine karte hain.

</> SQL
SELECT
    employees.employee_name,
    departments.department_name
FROM employees
LEFT JOIN departments
ON employees.department_id = departments.department_id

UNION

SELECT
    employees.employee_name,
    departments.department_name
FROM employees
RIGHT JOIN departments
ON employees.department_id = departments.department_id;
Query Result Output
employee_namedepartment_name
GaganIT
RahulIT
AmanSales
PriyaHR
SimranFinance
NehaNULL
NULLMarketing

9. CROSS JOIN (Cartesian Product)

CROSS JOIN pehli table ke har single record ko doosri table ke har single record ke sath combine karta hai (Cartesian Product).

Row Calculation Formula

Agar Table 1 mein 6 records hain aur Table 2 mein 5 records hain, toh CROSS JOIN total 6 × 5 = 30 rows return karega.

No ON Condition Needed

CROSS JOIN mein koi ON condition nahi di jaati kyunki yeh matching par nahi balki har possible combination par kaam karta hai.

</> SQL
SELECT
    employees.employee_name,
    departments.department_name
FROM employees
CROSS JOIN departments;

10. SELF JOIN (Manager-Employee Relationship)

Simple Definition

Jab hum same table ko khud ke saath JOIN karte hain, use SELF JOIN kehte hain. Yeh hierarchical data (jaise Employee and Manager) ke liye exact requirement hoti hai.

Table Aliases (e and m)

Table aliases e (for Employee view) aur m (for Manager view) ka use karke hum same table ko do alag roles mein treat karte hain: e.manager_id = m.employee_id.

</> SQL
SELECT
    e.employee_name AS Employee,
    m.employee_name AS Manager
FROM employees e
LEFT JOIN employees m
ON e.manager_id = m.employee_id;
Query Result Output
EmployeeManager
GaganNULL
RahulGagan
AmanPriya
PriyaNULL
SimranPriya
NehaNULL

11. Multiple Tables JOIN (Connecting 4 Tables)

Hum ek hi SQL query mein 3, 4 ya usse zyada tables ko multi-level JOINs se connect kar sakte hain.

</> SQL
SELECT
    e.employee_name,
    d.department_name,
    p.project_name
FROM employees e

INNER JOIN departments d
ON e.department_id = d.department_id

INNER JOIN employee_projects ep
ON e.employee_id = ep.employee_id

INNER JOIN projects p
ON ep.project_id = p.project_id;
Query Result Output
employee_namedepartment_nameproject_name
GaganITWebsite Development
GaganITData Analytics
RahulITWebsite Development
AmanSalesCRM System
PriyaHRMarketing Campaign
SimranFinanceData Analytics

12. JOIN + WHERE, ORDER BY & GROUP BY Clauses

A. JOIN + WHERE (Filtering IT Department Only)

</> SQL
SELECT
    e.employee_name,
    d.department_name
FROM employees e
INNER JOIN departments d
ON e.department_id = d.department_id
WHERE d.department_name = 'IT';

B. JOIN + ORDER BY (Sorting Salaries Descending)

</> SQL
SELECT
    e.employee_name,
    d.department_name,
    e.salary
FROM employees e
INNER JOIN departments d
ON e.department_id = d.department_id
ORDER BY e.salary DESC;

C. JOIN + GROUP BY (Department Average Salary)

</> SQL
SELECT
    d.department_name,
    AVG(e.salary) AS average_salary
FROM departments d
LEFT JOIN employees e
ON d.department_id = e.department_id
GROUP BY d.department_id, d.department_name;

13. JOIN + HAVING (Group-Level Filters)

WHERE vs HAVING Difference

WHERE: Individual rows ko filter karta hai pehle (before grouping).

HAVING: Aggregated groups ko filter karta hai (after GROUP BY execution).

Query Goal

Sirf woh departments list karo jinme 1 se zyada employees (total_employees > 1) kaam karte hain.

</> SQL
SELECT
    d.department_name,
    COUNT(e.employee_id) AS total_employees
FROM departments d
LEFT JOIN employees e
ON d.department_id = e.department_id
GROUP BY d.department_id, d.department_name
HAVING COUNT(e.employee_id) > 1;
Query Result Output
department_nametotal_employees
IT2

14. JOINs & Important SQL Keywords Cheat Sheet

JOIN Type Returned Records Summary
INNER JOINSirf matching records return karta hai dono tables se.
LEFT JOINLeft table ke saare records + matching right table records.
RIGHT JOINRight table ke saare records + matching left table records.
FULL OUTER JOINDono tables ke saare records (MySQL mein LEFT + RIGHT + UNION).
CROSS JOINCartesian Product (m × n combinations).
SELF JOINSame table ko khud se connect karna (Aliases e, m).

21 Important SQL Keywords

KeywordSimple Definition
CREATE DATABASECreates a new database container.
USESelects and activates database session.
CREATE TABLECreates a new table with column specifications.
INSERT INTOInserts rows into a table.
SELECTRetrieves records from tables.
FROMSpecifies the primary source table.
JOINCombines rows from multiple tables.
ONSpecifies joining condition between key columns.
WHEREFilters individual rows before grouping.
GROUP BYGroups identical rows into summary categories.
HAVINGFilters aggregated groups after GROUP BY.
ORDER BYSorts result rows ascending or descending.
ASAssigns a temporary alias name to columns or tables.
UNIONCombines distinct result sets of two SELECT queries.

15. Primary Key, Foreign Key & Relational Constraints

16. Complete Full Runnable MySQL Script

Aap is poore code script ko copy karke directly MySQL Workbench ya Command Line mein execute kar sakte hain:

</> SQL
CREATE DATABASE office;

USE office;

CREATE TABLE departments (
    department_id INT PRIMARY KEY AUTO_INCREMENT,
    department_name VARCHAR(50) NOT NULL,
    location VARCHAR(50)
);

CREATE TABLE employees (
    employee_id INT PRIMARY KEY AUTO_INCREMENT,
    employee_name VARCHAR(50) NOT NULL,
    email VARCHAR(100) UNIQUE,
    salary DECIMAL(10,2),
    department_id INT,
    manager_id INT,

    FOREIGN KEY (department_id)
    REFERENCES departments(department_id)
);

CREATE TABLE projects (
    project_id INT PRIMARY KEY AUTO_INCREMENT,
    project_name VARCHAR(100) NOT NULL,
    project_budget DECIMAL(12,2)
);

CREATE TABLE employee_projects (
    employee_id INT,
    project_id INT,

    PRIMARY KEY (employee_id, project_id),

    FOREIGN KEY (employee_id)
    REFERENCES employees(employee_id),

    FOREIGN KEY (project_id)
    REFERENCES projects(project_id)
);

INSERT INTO departments (department_name, location)
VALUES
('HR', 'Chandigarh'),
('IT', 'Mohali'),
('Sales', 'Chandigarh'),
('Finance', 'Panchkula'),
('Marketing', 'Ludhiana');

INSERT INTO employees (employee_name, email, salary, department_id, manager_id)
VALUES
('Gagan', 'gagan@gmail.com', 45000, 2, NULL),
('Rahul', 'rahul@gmail.com', 35000, 2, 1),
('Aman', 'aman@gmail.com', 40000, 3, 4),
('Priya', 'priya@gmail.com', 50000, 1, NULL),
('Simran', 'simran@gmail.com', 38000, 4, 4),
('Neha', 'neha@gmail.com', 42000, NULL, NULL);

INSERT INTO projects (project_name, project_budget)
VALUES
('Website Development', 200000),
('Data Analytics', 300000),
('CRM System', 250000),
('Marketing Campaign', 150000);

INSERT INTO employee_projects (employee_id, project_id)
VALUES
(1, 1), (1, 2), (2, 1), (3, 3), (4, 4), (5, 2);