DEV Community

Young Odhiambo
Young Odhiambo

Posted on

SQL Joins: How to Connect Tables Without Losing Your Mind

Introduction

Working with databases often means dealing with multiple tables of information. To extract meaningful insights, we need a way to combine related data. That’s where SQL joins come in.

Join is an operation in DBMS(Database Management System) that combines the rows of two or more tables based on related columns between them. The main purpose of join is to retrieve the data from multiple tables in other words Join is used to perform multi-table queries. It is denoted by .

In this post, we’ll break down the four main types of SQL joins — Inner Join, Left Join, Right Join, and Full Outer Join — using a simple example and visual references.

1. Inner Join

The Inner Join returns only the rows where there is a match in both tables. If the key exists in both Table A and Table B, it will be included in the result.

SELECT A.Key, A.Val_A, B.Val_B
FROM Table_A A
INNER JOIN Table_B B
ON A.Key = B.Key;

Enter fullscreen mode Exit fullscreen mode

Result: Only the common keys from both tables.

2. Left Join

The Left Join keeps all the rows from the left table (Table A), and matches them with rows from the right table (Table B). If there’s no match, you’ll see NULL values for the right table’s columns.

SELECT A.Key, A.Val_A, B.Val_B
FROM Table_A A
LEFT JOIN Table_B B
ON A.Key = B.Key;

Enter fullscreen mode Exit fullscreen mode

Result: All rows from Table A, matched where possible, otherwise NULL.

3. Right Join

The Right Join is the mirror opposite of the Left Join. It keeps all rows from the right table (Table B) and matches them with Table A. Missing values from the left side will show as NULL.

SELECT A.Key, A.Val_A, B.Val_B
FROM Table_A A
RIGHT JOIN Table_B B
ON A.Key = B.Key;

Enter fullscreen mode Exit fullscreen mode

Result: All rows from Table B, matched where possible, otherwise NULL.

4. Full Outer Join

The Full Outer Join returns all rows from both tables, regardless of whether there is a match. If a key exists in only one table, the other side will be filled with NULL.

SELECT A.Key, A.Val_A, B.Val_B
FROM Table_A A
FULL OUTER JOIN Table_B B
ON A.Key = B.Key;

Enter fullscreen mode Exit fullscreen mode

Result: All keys from both tables, matched where possible, otherwise NULL.

Why SQL Joins Matter?

SQL Joins are fundamental for:

  • Data analysis
  • Business reporting
  • Building APIs
  • Working with relational databases

Conclusion

Think of SQL joins as the “glue” that binds your data together. Once you understand how they work, you’ll have the power to combine and analyze information across multiple sources with ease.

Top comments (0)