CBSERanker

Loading

Class Notes: Table Joins in SQL

Class Notes: Table Joins in SQL

Introduction to Joins

  • A join combines rows from two or more tables
  • Multiple tables are listed in the FROM clause
  • Types of joins in MySQL:
    1. CROSS JOIN (Cartesian Product)
    2. EQUI-JOIN
    3. NATURAL JOIN
    4. LEFT JOIN
    5. RIGHT JOIN

Cross Join (Cartesian Product)

  • Returns all possible combinations of rows from both tables
  • Each row from first table is joined with all rows of second table
  • Formula: Total rows = rows in first table × rows in second table

Example:

SELECT * FROM Shades, Color;
-- or
SELECT * FROM Shades CROSS JOIN Color;

Output Table Example:

shade_idshade_namecolor_idcolor_name
1Light1Red
1Light2Green
1Light3Blue
2Dark1Red

Equi-Join

  • Columns are compared for equality
  • Common column appears twice in output
  • Uses WHERE clause with equality condition

Example:

SELECT * FROM emp, dept 
WHERE emp.deptno = dept.deptno;

Using Table Aliases:

SELECT e.empno, e.name, d.dname 
FROM emp e, dept d 
WHERE e.deptno = d.deptno;

Output Table Example:

empnonamedeptnodnamedeptnolocation
101Alam10Sales10Delhi
102Ravi20HR20Mumbai

Natural Join

  • Similar to Equi-Join but eliminates duplicate columns
  • Only one copy of common column appears

Example:

SELECT empno, name, dname, location 
FROM emp NATURAL JOIN dept;

Handling Ambiguous Columns:

SELECT emp.empno, emp.name, dept.dname 
FROM emp NATURAL JOIN dept;

Additional Conditions in Joins

SELECT e.empno, e.name, d.dname 
FROM emp e JOIN dept d ON e.deptno = d.deptno 
WHERE e.salary > 50000;

LEFT JOIN

  • Returns all rows from left table (first table)
  • Returns NULL for non-matching rows from right table

Example:

SELECT e.empno, e.name, p.pname 
FROM emp e LEFT JOIN project p ON e.empno = p.empno;

Output Table Example:

empnonamepname
101AlamWebsite
102RaviDatabase
103PriyaNULL

RIGHT JOIN

  • Returns all rows from right table (second table)
  • Returns NULL for non-matching rows from left table

Example:

SELECT p.pid, p.pname, e.name 
FROM emp e RIGHT JOIN project p ON e.empno = p.empno;

Output Table Example:

pidpnamename
P1WebsiteAlam
P2DatabaseRavi
P3AppNULL

Key Differences Summary

Join TypeDescriptionDuplicate ColumnsNULL Handling
CROSS JOINAll combinations of rowsNoN/A
EQUI-JOINMatches based on equality, shows all columnsYesOnly matching rows
NATURAL JOINMatches based on equality, hides duplicate columnsNoOnly matching rows
LEFT JOINAll rows from left table + matching from rightDependsNULL for non-matching right rows
RIGHT JOINAll rows from right table + matching from leftDependsNULL for non-matching left rows

Leave a Reply

Your email address will not be published. Required fields are marked *