Joins in DBMS: Combining Data from Multiple Tables

Learn about the concept of joins in database management systems (DBMS), which allow you to combine data from different tables based on specified conditions. Explore the various types of joins, including Theta join, natural join, inner join, outer join (left, right, full), and self-join, and understand their applications in data retrieval and analysis.



DBMS - Joins

Joins allow us to combine tuples from different relations based on a specified condition, providing an alternative to the Cartesian product, which can be computationally expensive for large relations. A join operation pairs two tuples from different relations only if a given join condition is satisfied.

Theta (θ) Join

A Theta join combines tuples from different relations if they meet a specified condition, denoted by θ, which can involve any comparison operator.

Notation: R1 ⋈θ R2

Here, R1 and R2 represent relations with attributes (A1, A2, ..., An) and (B1, B2, ..., Bn), and they must not have any common attributes (R1 ∩ R2 = Φ).

Example:

Student
SIDNameStd
101Alex10
102Maria11
Subjects
ClassSubject
10Math
10English
11Music
11Sports

Join operation: STUDENT ⋈Student.Std = Subject.Class SUBJECT

Student_Detail
SIDNameStdClassSubject
101Alex1010Math
101Alex1010English
102Maria1111Music
102Maria1111Sports

Equijoin

An Equijoin is a Theta join that uses only the equality comparison operator. The example above also represents an Equijoin, as the join condition involves equality.

Natural Join (⋈)

A Natural Join does not use any comparison operators but relies on matching attributes between two relations, which must have the same name and domain. The Natural Join combines tuples with equal values in the common attribute(s) and eliminates duplicate attributes.

Example:

Courses
CIDCourseDept
CS01DatabaseCS
ME01MechanicsME
EE01ElectronicsEE
HoD
DeptHead
CSAlex
MEMaya
EEMira

Natural Join: Courses ⋈ HoD

Courses_HoD
DeptCIDCourseHead
CSCS01DatabaseAlex
MEME01MechanicsMaya
EEEE01ElectronicsMira

Outer Joins

Inner joins include only tuples with matching attributes. Outer joins, however, also include non-matching tuples, making them useful for preserving data from one or both relations. There are three types of outer joins:

Left Outer Join

All tuples from the left relation are included in the result. Non-matching tuples from the right relation are filled with NULL values.

Courses Left Outer Join HoD
ABCD
100Database100Alex
101Mechanics------
102Electronics102Maya

Right Outer Join

All tuples from the right relation are included, with non-matching tuples from the left relation filled with NULL values.

Courses Right Outer Join HoD
ABCD
100Database100Alex
102Electronics102Maya
------104Mira

Full Outer Join

All tuples from both relations are included, with unmatched attributes filled with NULL values for each relation.

Courses Full Outer Join HoD
ABCD
100Database100Alex
101Mechanics------
102Electronics102Maya
------104Mira