Beginner's Guide to SQL Joins and Table Relationships

In this article we are going to be looking at the relationships between tables in SQL databases. So what are these SQL joins?

Joins are used to combine rows from two or more tables based on a related column.

It is evident that we are going to need more than one table to use Joins. So far we have created one table called employees in our database. Please refer to the previous articles to learn more (https://themathlab.hashnode.dev/exploring-sql-concepts-for-beginners). Lets create another table called department to store details about different departments in the company.

# Create departments table
cursor.execute('''
CREATE TABLE departments (
    department TEXT PRIMARY KEY,
    location TEXT
);
''')

Lets insert some data into this table

# Insert department data
cursor.executemany('''
INSERT INTO departments (department, location) VALUES (?, ?);
''', [
    ('HR', 'New York'),
    ('IT', 'San Francisco'),
    ('Finance', 'Chicago'),
    ('Marketing', 'Los Angeles')
])

conn.commit()
print("Departments table created & data inserted successfully!")

Before we get into writing queries, lets take a look at the different types of Joins in SQL,

  • INNER JOIN - Fetches matching rows from both tables. Returns only the rows where there’s a match in both tables.

  • LEFT JOIN - Returns all rows from the left table and matching rows from the right table. Rows from the left table with no match in the right table will contain NULL in the result.

  • RIGHT JOIN - Returns all rows from the right table and matching rows from the left table. Rows from the right table with no match in the left table will contain NULL in the result.

  • FULL OUTER JOIN - Combines the result of both LEFT and RIGHT JOIN. Returns all rows from both tables, with NULL where there’s no match.

Lets try out INNER JOIN first. Lets join employees table and departments table. Here we need to be mindful of which columns need to be compared when joining the tables as we haven’t defined any primary keys yet.

query = '''
SELECT employees.name, employees.salary, departments.department, departments.location
FROM employees
INNER JOIN departments ON employees.department = departments.department;
'''
df = pd.read_sql(query,conn)
df

The LEFT JOIN and RIGHT JOIN works similarly but on opposite directions :) LEFT JOIN returns all rows from the left table and matching rows from the right table. Rows from the left table with no match in the right table will contain NULL in the result. On the other hand RIGHT JOIN returns all rows from the right table and matching rows from the left table. Rows from the right table with no match in the left table will contain NULL in the result.

FULL OUTER JOIN combines the result of both LEFT and RIGHT JOIN. Returns all rows from both tables, with NULL where there’s no match.

Before we end our lesson I would like to introduce two more very important commands in SQL. Those are UPDATE and DELETE. We already saw how to add data into a table using INSERT. If you wanted to change anything in a record you can use the UPDATE command.

query = '''
UPDATE employees SET department = 'HR' WHERE name ='Charlie';
'''
cursor.execute(query)
conn.commit()  
print("Record Updated Successfully!")

Here I have updated the department of Charlie to HR. Similarly you can delete a record using the DELETE command.

query = '''
DELETE from  employees WHERE name ='Charlie';
'''
cursor.execute(query)
conn.commit()  
print("Record Deleted Successfully!")

Lets look at a summary of all the important SQL commands we have learned so far

CommandPurpose
SELECTRetrieve data
WHEREFilter data
ORDER BYSort data
LIMITRestrict results
COUNT, SUM, AVGAggregate functions
GROUP BYSummarize data
HAVINGFilter grouped data
INNER JOINCombine tables (matching rows)
LEFT JOINKeep all rows from the left table
INSERTAdd data
UPDATEModify data
DELETERemove data

You can see the practice questions and answers in my GitHub repository at https://github.com/isuri-balasooriya2/TheMathLab/

In the next articles we will look at subqueries.