Python SQLite - JOIN Clause - GeeksforGeeks

23 May, 2021
In this article, we discuss the JOIN clause in SQLite using the sqlite3 module in Python. But at first let’s see a brief about join in SQLite.
 A JOIN clause combines the records from two tables on the basis of common attributes. The different types of joins are as follows:
INNER JOIN (OR JOIN) – Gives the records that have common attributes in both tables.
LEFT JOIN – Gives all records from the left table and only the common records from the right table.
RIGHT JOIN – Gives all records from the right table and only the common records from the left table.
FULL OUTER JOIN – Gives all records when there is a common attribute in either the left or the right table.
CROSS JOIN – Gives records of one table with all other records of another table.
Note: 
Unlike other types of joins, it does not include a join condition.
SQLite does not directly support the RIGHT JOIN and FULL OUTER JOIN. 
Here, we will create a simple database having two tables Advisor(AdvisorID, AdvisorName) and Student(StudentID, StudentName, AdvisorID) where AdvisorID of the Student table is the foreign key referencing AdvisorID of the Advisor table.
Python3
# Import required librariesimport sqlite3  # Connect to SQLite database# New file created if it doesn't already existconn = sqlite3.connect(r'C:\Users\SQLite\Geeks.db')  # Create cursor objectcursor = conn.cursor()  # Create and populate tablescursor.executescript('''CREATE TABLE Advisor(AdvisorID INTEGER NOT NULL,AdvisorName TEXT NOT NULL,PRIMARY KEY(AdvisorID));  CREATE TABLE Student(StudentID NUMERIC NOT NULL,StudentName NUMERIC NOT NULL,AdvisorID INTEGER,FOREIGN KEY(AdvisorID) REFERENCES Advisor(AdvisorID),PRIMARY KEY(StudentID));  INSERT INTO Advisor(AdvisorID, AdvisorName) VALUES(1,"John Paul"), (2,"Anthony Roy"), (3,"Raj Shetty"),(4,"Sam Reeds"),(5,"Arthur Clintwood");  INSERT INTO Student(StudentID, StudentName, AdvisorID) VALUES(501,"Geek1",1),(502,"Geek2",1),(503,"Geek3",3),(504,"Geek4",2),(505,"Geek5",4),(506,"Geek6",2),(507,"Geek7",2),(508,"Geek8",3),(509,"Geek9",NULL),(510,"Geek10",1);  ''')  #Commit changes to databaseconn.commit()  # Closing the connectionconn.close()
Tables Created:
Advisor Table
Student Table
Now, let’s perform different types of join on the above-created database.
Inner join also represented as join which gives the records that have common attributes in both tables.
Syntax:
   SELECT columns
   FROM table1
   [INNER] JOIN table2
   ON table1.column = table2.column;
INNER keyword is optional
Python3
# Import required librariesimport sqlite3  # Connect to SQLite databaseconn = sqlite3.connect(r'C:\Users\SQLite\Geeks.db')  # Create cursor objectcursor = conn.cursor()  # Query for INNER JOINsql = '''SELECT StudentID, StudentName, AdvisorName FROM Student INNER JOIN AdvisorON Student.AdvisorID = Advisor.AdvisorID;'''  # Executing the querycursor.execute(sql)  # Fetching rows from the result tableresult = cursor.fetchall()for row in result:    print(row)  # Closing the connectionconn.close()
Output:
Gives all records from the left table, and only the common records from the right table.
Syntax:
  SELECT columns
  FROM table1
  LEFT [OUTER] JOIN table2 
  ON table1.column = table2.column;
OUTER keyword is optional
Python3
# Import required librariesimport sqlite3  # Connect to SQLite databaseconn = sqlite3.connect(r'C:\Users\SQLite\Geeks.db')  # Create cursor objectcursor = conn.cursor()  # Query for LEFT JOINsql = '''SELECT StudentID, StudentName, AdvisorName FROM Student LEFT JOIN AdvisorUSING(AdvisorID) ;'''  # Executing the querycursor.execute(sql)  # Fetching rows from the result tableresult = cursor.fetchall()for row in result:    print(row)  # Closing the connectionconn.close()
Since the column name (AdvisorID) of joined tables is same, the clause USING(AdvisorID) can be used instead of ON Student.AdvisorID = Advisor.AdvisorID.
Output:
Gives all records from the right table, and only the common records from the left table. As mentioned before, SQLite does not directly support RIGHT JOIN. However, it can be emulated using LEFT JOIN by switching the positions of the student and advisor table.
Syntax:
  SELECT columns
  FROM table1
  RIGHT [OUTER] JOIN table2
  ON table1.column = table2.column;
OUTER keyword is optional
Python3
# Import required librariesimport sqlite3  # Connect to SQLite databaseconn = sqlite3.connect(r'C:\Users\SQLite\Geeks.db')  # Create cursor objectcursor = conn.cursor()  # Query for RIGHT JOINsql = '''SELECT StudentID, StudentName, AdvisorName FROM Advisor LEFT JOIN StudentUSING(AdvisorID);'''  # Executing the querycursor.execute(sql)  # Fetching rows from the result tableresult = cursor.fetchall()for row in result:    print(row)  # Closing the connectionconn.close()
Output:
Gives all records when there is a common attribute in either left or the right table. As mentioned before, SQLite does not directly support FULL OUTER JOIN. However, it can be emulated using LEFT JOIN. In this query, the second SELECT statement has the positions of the student and advisor table switched. The UNION ALL clause retains the duplicate rows from the result of both SELECT queries. And the WHERE clause in the second SELECT statement removes rows that already included in the result set of the first SELECT statement.
Syntax:
  SELECT columns
  FROM table1
  FULL [OUTER] JOIN table2
  ON table1.column = table2.column;
OUTER keyword is optional
Python3
# Import required librariesimport sqlite3  # Connect to SQLite databaseconn = sqlite3.connect(r'C:\Users\SQLite\Geeks.db')  # Create cursor objectcursor = conn.cursor()  # Query for FULL OUTER JOINsql = '''SELECT StudentID, StudentName, AdvisorName FROM Student LEFT JOIN AdvisorUSING(AdvisorID)UNION ALLSELECT StudentID, StudentName, AdvisorName FROM Advisor LEFT JOIN StudentUSING(AdvisorID)WHERE Student.AdvisorID IS NULL;'''  # Executing the querycursor.execute(sql)  # Fetching rows from the result tableresult = cursor.fetchall()for row in result:    print(row)  # Closing the connectionconn.close()
Output:
CROSS JOIN 
It combines all records of one table with all other records of another table, that is, it creates a Cartesian product of records from the join tables.
Syntax:
  SELECT columns 
  FROM table1
  CROSS JOIN table2;
Python3
# Import required librariesimport sqlite3  # Connect to SQLite databaseconn = sqlite3.connect(r'C:\Users\SQLite\Geeks.db')  # Create cursor objectcursor = conn.cursor()  # Query for CROSS JOINsql = '''SELECT StudentID, StudentName, AdvisorName FROM Student CROSS JOIN Advisor;'''  # Executing the querycursor.execute(sql)  # Fetching rows from the result tableresult = cursor.fetchall()for row in result:    print(row)  # Closing the connectionconn.close()
Output:
Picked
Python-SQLite
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Convert integer to string in Python