Labs ICT
⭐ Pro Login

JOINs

Combining data from multiple tables.

Combining Data from Multiple Tables

In a well-designed database, data is spread across multiple tables to avoid redundancy. JOINs allow you to combine rows from two or more tables based on related columns.

Types of JOINs


  Students                     Enrollments
  β”Œβ”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”            β”Œβ”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”
  β”‚ ID β”‚ Name    β”‚            β”‚SID β”‚CourseID β”‚Grade β”‚
  β”œβ”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€            β”œβ”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€
  β”‚ 1  β”‚ Alice   β”‚            β”‚ 1  β”‚ 101     β”‚ A    β”‚
  β”‚ 2  β”‚ Bob     β”‚            β”‚ 2  β”‚ 101     β”‚ B    β”‚
  β”‚ 3  β”‚ Charlie β”‚            β”‚ 3  β”‚ 102     β”‚ A    β”‚
  β”‚ 4  β”‚ Diana   β”‚            β””β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”˜
  β””β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

INNER JOIN β€” Only rows that match in both tables:


  SELECT Students.Name, Enrollments.CourseID, Enrollments.Grade
  FROM Students
  INNER JOIN Enrollments ON Students.ID = Enrollments.SID;

  Result:
  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”
  β”‚ Name    β”‚CourseID β”‚Grade β”‚
  β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€
  β”‚ Alice   β”‚ 101     β”‚ A    β”‚
  β”‚ Bob     β”‚ 101     β”‚ B    β”‚
  β”‚ Charlie β”‚ 102     β”‚ A    β”‚
  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”˜
  (Diana excluded β€” no enrollment)

LEFT JOIN β€” All rows from the left table, matching rows from right (NULL if no match):

RIGHT JOIN β€” All rows from the right table, matching rows from left.

FULL OUTER JOIN β€” All rows from both tables (NULL where no match).

Self Join


  -- Find employees and their managers
  SELECT E.Name AS Employee, M.Name AS Manager
  FROM Employees E
  LEFT JOIN Employees M ON E.ManagerID = M.ID;

πŸ§ͺ Quick Quiz

What type of JOIN returns all rows from both tables?