LEFT JOIN  and RIGHT JOIN, what's the difference?

LEFT JOIN and RIGHT JOIN, what's the difference?

Part 1 - LEFT JOIN

A couple of months ago I got a phone interview from a company and part of the prescreening was to know my experience with databases. The interviewer asked about the difference between LEFT JOIN and RIGHT JOIN in the relational database of my choice. At this moment, I realised that despite knowing the difference between the two and having used it for the last 5 years it was still hard for me to explain to someone else the difference.

I gave myself the challenge to dig deeper into the two concepts and here is a step by step guide to help you hack it in case you're asked! The two MYSQL clauses are used to query data from two or more tables

LEFT JOIN

Syntax

SELECT columns_to_be_selected FROM left_table 
LEFT JOIN right_table ON  join_condition;

Key points

  1. The LEFT JOIN clause selects data starting from the left_table and matches each row from the left_table with every row from the right_table based on the join_condition.
  2. LEFT JOIN returns all rows from the left_table regardless of whether a row from the left_table has a matching row from the right_table or not. If there is no match, the columns of the row from the right table will contain NULL.
  3. That means if left_table has 100 rows and right_table has 1000 rows, the query result will contain at least 1000 rows. Take note of this.

Example

In this example we have two tables: oc_customer - Customers table image.png oc_order - Customer Orders table image.png

First, let's get the count of records in each table:

SELECT COUNT(customer_id) as total FROM oc_customer

Total Customers: 4

SELECT COUNT(order_id) as total FROM oc_order

Total Orders: 365

Each order belongs to one customer only, but one customer can zero or more orders. We can use LEFT JOIN to get all customers and their orders with this query.

SELECT oc_customer.customer_id, oc_customer.firstname, oc_order.total 
FROM oc_customer 
LEFT JOIN oc_order 
ON oc_order.customer_id = oc_customer.customer_id

The result image.png

From the result, you will notice the query returned 368 records and not 365 or 4. Reason: LEFT JOIN clause returns all customers including the customers who have no order. If a customer has no order, the values in the column total are NULL. This is the most basic use of the LEFT JOIN clause to illustrate how it works and I'm sure the result would be different if you applied some conditions.

That it guys, I hope you've learned something and looking forward to your ideas.