S

Understanding SQL Joins: Inner, Outer, Left, and Right

PinoyFreeCoder
Wed Dec 04 2024
PinoyFreeCoder
Wed Dec 04 2024

Understanding SQL Joins: Inner, Outer, Left, and Right

SQL joins are fundamental for combining data from multiple tables. Understanding the different types of joins—Inner, Outer, Left, and Right—can significantly enhance your ability to write efficient and meaningful queries. In this guide, we break down each type of join with explanations and examples.

1. Inner Join

An inner join returns rows where there is a match in both tables.


      SELECT a.name, b.salary
      FROM employees a
      INNER JOIN salaries b ON a.employee_id = b.employee_id;
      

Example Tables:

Employees Salaries
Alice $50,000

2. Left Join

A left join returns all rows from the left table, and the matching rows from the right table. If there is no match, NULL values are returned for the right table's columns.


      SELECT a.name, b.salary
      FROM employees a
      LEFT JOIN salaries b ON a.employee_id = b.employee_id;
      

3. Right Join

A right join returns all rows from the right table, and the matching rows from the left table. If there is no match, NULL values are returned for the left table's columns.


      SELECT a.name, b.salary
      FROM employees a
      RIGHT JOIN salaries b ON a.employee_id = b.employee_id;
      

4. Full Outer Join

A full outer join returns all rows from both tables, with NULLs in columns where there is no match.


      SELECT a.name, b.salary
      FROM employees a
      FULL OUTER JOIN salaries b ON a.employee_id = b.employee_id;
      

Conclusion

Understanding the differences between SQL join types enables you to combine data effectively and write optimized queries. Which type of join do you use the most? Share your experience in the comments below!

Start Your Online Store with Shopify

Build your e-commerce business with the world's leading platform. Get started today and join millions of successful online stores.

🎉 3 MONTHS FREE for New Users! 🎉
Get Started
shopify