DEV Community

Dennis Wachira
Dennis Wachira

Posted on

LEFT JOIN in SQL

A LEFT JOIN returns all records from the left table and the matching records from the right table. If no matching record exists in the right table, SQL returns NULL for those columns instead of excluding the record. This makes LEFT JOIN very useful when you want a complete view of one table, regardless of whether related data exists.

Applying LEFT JOIN to My Hospital Database

For this exercise, I worked with my normalized hospital database, specifically the doctors and visits tables. My first query displayed every doctor together with their visit details whenever a match existed. This helped me understand how SQL preserves every record from the left table while adding information from the related table.

Counting Hospital Visits

I then used LEFT JOIN together with the COUNT() aggregate function to determine how many visits each doctor had handled. This demonstrated that even if a doctor had no recorded visits, they would still appear in the results with a count of zero rather than being excluded entirely.
Although every doctor in my current dataset has at least one visit, writing the query this way prepares the database for future records where new doctors may not yet have treated any patients.

  • LEFT JOIN always keeps every record from the left table.
  • Matching records from the right table are added whenever they exist.
  • Missing matches are represented as NULL.
  • LEFT JOIN is ideal for identifying missing or incomplete relationships between tables.

GitHub link https://github.com/KratosOCS/Hospital-Records-Analysis/commit/f857bff1ce52b3bd1ba1507ee329c1a90a53b01a

Top comments (0)