Python SQLite – JOIN Clause
In SQLite, the `JOIN` clause is used to combine rows from two or more tables based on a related column between them. It allows you to retrieve data from multiple tables simultaneously by specifying a condition that determines how the tables are related. Python’s SQLite module enables you to perform `JOIN` operations when querying data from SQLite database tables.
Here’s how to use the `JOIN` clause in SQLite with Python:
1. Establish Connection: Begin by establishing a connection to the SQLite database file using the `connect()` function from the `sqlite3` module.
2. Create Cursor: After establishing the connection, create a cursor object using the `cursor()` method.
3. Execute SQL Statement: Use the cursor’s `execute()` method to execute an SQL statement that includes a `JOIN` clause to combine data from multiple tables.
4. Fetch Data: After executing the SQL statement, fetch the data from the cursor using one of the fetch methods (`fetchone()`, `fetchall()`, or `fetchmany()`).
5. Process Data: Process the fetched data as needed.
6. Close Cursor and Connection: Finally, close the cursor and connection using the `close()` method to release any resources associated with them.
Here’s an example of how to use the `JOIN` clause to retrieve data from two tables named `employees` and `departments`, where `employees` table has a foreign key `dept_id` referencing the `id` column in the `departments` table:
“`python
import sqlite3
# Establish connection to SQLite database
connection = sqlite3.connect(‘example.db’)
# Create a cursor object
cursor = connection.cursor()
# Execute SQL statement with JOIN clause
cursor.execute(”’
SELECT employees.name, departments.name
FROM employees
JOIN departments ON employees.dept_id = departments.id
”’)
# Fetch data
rows = cursor.fetchall()
# Process fetched data
for row in rows:
print(row)
# Close cursor and connection
cursor.close()
connection.close()
“`
In this example:
– We establish a connection to an SQLite database file named `example.db`.
– We create a cursor object using the `cursor()` method.
– We execute an SQL statement with a `JOIN` clause that combines data from the `employees` and `departments` tables based on the `dept_id` foreign key relationship.
– We fetch the data using the `fetchall()` method and store it in the `rows` variable.
– We iterate over the rows and print each row, which contains the employee’s name and their department’s name.
– Finally, we close the cursor and connection.