🔥Limited Offer: Get 50% OFFon AI & Full Stack Courses🔥
Back to Python Notes
Topic #183

MySQL Join


Join Two or More Tables

You can combine rows from two or more tables, based on a related column between them, by using a JOIN statement.

Consider you have a "users" table and a "products" table:

users

{ id: 1, name: 'John', fav: 154},
{ id:
  2, name: 'Peter', fav: 154},
{ id: 3, name: 'Amy', fav: 155},
{ id: 4, name: 'Hannah', fav:},
{ id: 5, name: 'Michael', fav:}

products

{ id: 154, name:
  'Chocolate Heaven' },
{ id: 155, name: 'Tasty Lemons' },
{
  id: 156, name: 'Vanilla Dreams' }

These two tables can be combined by using users' fav field and products' id field.

Example

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",

user="yourusername",
  password="yourpassword",
  database="mydatabase"
)

mycursor = mydb.cursor()

sql = "SELECT \
  users.name AS user,
\
  products.name AS favorite \
  FROM users \
  INNER JOIN
products ON users.fav = products.id"

mycursor.execute(sql)

myresult = mycursor.fetchall()

for x in myresult:
  print(x)

Note: You can use JOIN instead of INNER JOIN. They will both give you the same result.


LEFT JOIN

In the example above, Hannah, and Michael were excluded from the result, that is because INNER JOIN only shows the records where there is a match.

If you want to show all users, even if they do not have a favorite product, use the LEFT JOIN statement:

Example

sql = "SELECT \
  users.name AS user,
\
  products.name AS favorite \
  FROM users \
  LEFT JOIN
products ON users.fav = products.id"

RIGHT JOIN

If you want to return all products, and the users who have them as their favorite, even if no user have them as their favorite, use the RIGHT JOIN statement:

Example

sql = "SELECT \
  users.name AS user,
\
  products.name AS favorite \
  FROM users \
  RIGHT JOIN
products ON users.fav = products.id"

Note: Hannah and Michael, who have no favorite product, are not included in the result.

Want to go beyond the notes?

Join CodingNow 2.0's Python course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

MySQL Join – FAQs

Quick answers about learning MySQL Join in Python.

This free note from CodingNow 2.0 explains MySQL Join in Python — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every Python topic on CodingNow 2.0, including MySQL Join, is 100% free with no signup required.
With focused practice, most students grasp MySQL Join in 1–3 days from these notes; pairing it with CodingNow 2.0's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the CodingNow 2.0 Community (/community) — expert instructors answer within 24 hours.
WhatsApp
Call NowEnroll Now