![]() |
VOOZH | about |
In this article, we will explore the JOIN clause in SQLite using Python's sqlite3 module. The JOIN clause combines records from two tables based on a related column, allowing us to perform complex queries.
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.
Tables Created:
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.
SELECT columns
FROM table1
[INNER] JOIN table2
ON table1.column = table2.column;
INNER keyword is optional
Output:
π ImageGives all records from the left table, and only the common records from the right table.
SELECT columns
FROM table1
LEFT [OUTER] JOIN table2
ON table1.column = table2.column;
OUTER keyword is optional
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:
π ImageGives 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.
SELECT columns
FROM table1
RIGHT [OUTER] JOIN table2
ON table1.column = table2.column;
OUTER keyword is optional
Output:
π ImageSQLite doesnβt support FULL OUTER JOIN directly either. However, you can emulate it using a combination of LEFT JOIN and RIGHT JOIN with UNION ALL to combine the results.
SELECT column1, column2, ...
FROM table1
LEFT JOIN table2
USING (common_column)
UNION ALL
SELECT column1, column2, ...
FROM table2
LEFT JOIN table1
USING (common_column)
WHERE table1.common_column IS NULL;
Steps to simulate Full Outer Join in SQLite.
Output:
π ImageIt 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.
SELECT columns
FROM table1
CROSS JOIN table2;