Python MySQL JOIN

🐍 Python MySQL JOIN — Complete Guide

In MySQL, JOINs are used to combine rows from two or more tables based on a related column.
Python can execute JOIN queries using the mysql-connector-python module.


 1️⃣ Types of JOINs in MySQL

JOIN TypeDescription
INNER JOINReturns rows with matching values in both tables
LEFT JOIN / LEFT OUTER JOINReturns all rows from left table, matching from right table or NULL
RIGHT JOIN / RIGHT OUTER JOINReturns all rows from right table, matching from left table or NULL
FULL OUTER JOINReturns all rows when there is a match in one of the tables (MySQL requires workaround)

 2️⃣ Example: Setup Two Tables


 

Insert sample data:

INSERT INTO students (name, age) VALUES ('Vipul', 25), ('Riya', 22), ('Amit', 24);

INSERT INTO courses (student_id, course_name) VALUES (1, ‘Python’), (1, ‘Java’), (2, ‘C++’);


 3️⃣ INNER JOIN in Python


 

Output:

('Vipul', 25, 'Python')
('Vipul', 25, 'Java')
('Riya', 22, 'C++')

Only students who have courses appear (INNER JOIN).


 4️⃣ LEFT JOIN in Python


 

Output:

('Vipul', 25, 'Python')
('Vipul', 25, 'Java')
('Riya', 22, 'C++')
('Amit', 24, None)

Shows all students; if no course, None is returned.


 5️⃣ RIGHT JOIN in Python


 

Output: Only rows where courses exist, with corresponding students.


 6️⃣ JOIN Multiple Tables

You can JOIN more than two tables:



 

Python query:


 


 7️⃣ Summary Table of JOINs

JOIN TypePurposePython Usage
INNER JOINOnly matching rowsINNER JOIN table2 ON table1.id = table2.fk
LEFT JOINAll rows from left tableLEFT JOIN table2 ON ...
RIGHT JOINAll rows from right tableRIGHT JOIN table2 ON ...
FULL OUTER JOINAll rows from both tablesUse UNION in MySQL
Multiple JOINsJoin 3+ tablesChain JOIN statements

💡 Tips:

  • Always use aliases (s, c, etc.) for readability.

  • fetchall() returns all results; use fetchone() for one row.

  • JOIN queries in Python are executed same as in MySQL, just pass them as a string to cursor.execute().

You may also like...