MODULE 6.1: SQL DATABASE INTEGRATION IN PANDAS (SQLITE & SQLALCHEMY)

Master connecting Python Pandas to relational databases. Learn how to write DataFrames directly to SQL tables, query databases using raw SQL, execute parameterized queries securely, and process massive datasets in memory-efficient chunks with 10 comprehensive real-world examples.

💡 The Pandas-SQL Bridge

Enterprise data is predominantly stored in relational database management systems (RDBMS) like PostgreSQL, MySQL, SQL Server, and SQLite. Pandas provides seamless bidirectional integration via read_sql() and to_sql() methods, enabling data scientists to query SQL databases directly into DataFrames and persist processed analytical tables back to databases.

1. Establishing SQLite Connection & Writing a DataFrame to SQL (`to_sql`)
Creating an in-memory or file-based SQLite database connection and persisting a Pandas DataFrame directly as a relational SQL table.
Python (sql_write_table.py)
import pandas as pd
import sqlite3

def write_dataframe_to_sql():
    # Create sample DataFrame
    df_employees = pd.DataFrame({
        'EmpID': [101, 102, 103],
        'Name': ['Alice', 'Bob', 'Charlie'],
        'Department': ['Engineering', 'Data Science', 'Marketing'],
        'Salary': [85000, 95000, 72000]
    })
    
    # Establish SQLite connection (in-memory database for demo)
    conn = sqlite3.connect(':memory:')
    
    # Write DataFrame to SQL table 'employees'
    df_employees.to_sql('employees', conn, index=False, if_exists='replace')
    
    print("=== SUCCESSFUL WRITE TO SQL TABLE ===")
    print(f"Table 'employees' created with {len(df_employees)} rows.")
    conn.close()

write_dataframe_to_sql()
Output: === SUCCESSFUL WRITE TO SQL TABLE === Table 'employees' created with 3 rows.
2. Querying SQL Databases into DataFrames (`read_sql_query`)
Executing a standard SQL SELECT query on a database connection and loading the result set directly into a Pandas DataFrame.
Python (sql_read_query.py)
import pandas as pd
import sqlite3

def read_sql_demo():
    conn = sqlite3.connect(':memory:')
    df_products = pd.DataFrame({
        'ProdID': [1, 2, 3],
        'ProductName': ['Laptop', 'Mouse', 'Monitor'],
        'Price': [1200.0, 35.0, 250.0]
    })
    df_products.to_sql('products', conn, index=False, if_exists='replace')
    
    # Query database into DataFrame
    query = "SELECT ProductName, Price FROM products WHERE Price > 50"
    result_df = pd.read_sql_query(query, conn)
    
    print("=== SQL QUERY RESULTS ===")
    print(result_df.to_string(index=False))
    conn.close()

read_sql_demo()
Output: === SQL QUERY RESULTS === ProductName Price Laptop 1200.0 Monitor 250.0
3. Executing Complex SQL Joins & Aggregations into Pandas
Leveraging SQL engines to perform heavy multi-table joins and aggregations before loading the distilled results into Pandas.
Python (sql_join_aggregation.py)
import pandas as pd
import sqlite3

def sql_aggregation_demo():
    conn = sqlite3.connect(':memory:')
    
    departments = pd.DataFrame({'DeptID': [1, 2], 'DeptName': ['Engineering', 'Sales']})
    employees = pd.DataFrame({
        'EmpID': [101, 102, 103, 104],
        'DeptID': [1, 1, 2, 2],
        'Salary': [90000, 95000, 60000, 65000]
    })
    
    departments.to_sql('departments', conn, index=False, if_exists='replace')
    employees.to_sql('employees', conn, index=False, if_exists='replace')
    
    query = """
        SELECT d.DeptName, COUNT(e.EmpID) as Headcount, AVG(e.Salary) as AvgSalary
        FROM departments d
        JOIN employees e ON d.DeptID = e.DeptID
        GROUP BY d.DeptName
    """
    summary_df = pd.read_sql_query(query, conn)
    
    print("=== SQL AGGREGATION RESULTS IN PANDAS ===")
    print(summary_df.to_string(index=False))
    conn.close()

sql_aggregation_demo()
Output: === SQL AGGREGATION RESULTS IN PANDAS == DeptName Headcount AvgSalary Engineering 2 92500.0 Sales 2 62500.0
4. Secure Parameterized SQL Queries to Prevent SQL Injection
Passing dynamic runtime variables securely into read_sql_query parameters to prevent SQL injection vulnerabilities.
Python (sql_parameterized.py)
import pandas as pd
import sqlite3

def parameterized_query_demo():
    conn = sqlite3.connect(':memory:')
    df = pd.DataFrame({
        'OrderID': [1, 2, 3, 4],
        'Region': ['North', 'South', 'North', 'East'],
        'Amount': [450, 200, 800, 300]
    })
    df.to_sql('orders', conn, index=False, if_exists='replace')
    
    target_region = 'North'
    query = "SELECT * FROM orders WHERE Region = ?"
    
    # Pass parameters tuple/list
    result_df = pd.read_sql_query(query, conn, params=(target_region,))
    
    print(f"=== ORDERS FOR REGION: {target_region} ===")
    print(result_df.to_string(index=False))
    conn.close()

parameterized_query_demo()
Output: === ORDERS FOR REGION: North === OrderID Region Amount 1 North 450 3 North 800
5. Handling Large Datasets in Chunks (`chunksize`)
Reading massive SQL query results iteratively in memory-efficient chunks using the chunksize parameter.
Python (sql_chunksize.py)
import pandas as pd
import sqlite3

def chunked_read_demo():
    conn = sqlite3.connect(':memory:')
    # Simulate a large table with 10,000 rows
    large_df = pd.DataFrame({
        'LogID': range(1, 10001),
        'Value': range(100, 1010000, 100)
    })
    large_df.to_sql('logs', conn, index=False, if_exists='replace')
    
    chunk_size = 3000
    total_rows = 0
    
    for chunk in pd.read_sql_query("SELECT * FROM logs", conn, chunksize=chunk_size):
        total_rows += len(chunk)
        print(f"Processed chunk with {len(chunk)} rows. Cumulative: {total_rows}")
        
    conn.close()

chunked_read_demo()
Output: Processed chunk with 3000 rows. Cumulative: 3000 Processed chunk with 3000 rows. Cumulative: 6000 Processed chunk with 3000 rows. Cumulative: 9000 Processed chunk with 1000 rows. Cumulative: 10000
6. SQLAlchemy Engine Integration for Production RDBMS
Connecting Pandas to production databases (PostgreSQL, MySQL) using SQLAlchemy connection engines for robust connection pooling.
Python (sqlalchemy_engine.py)
import pandas as pd
from sqlalchemy import create_engine

def sqlalchemy_demo():
    # Using SQLite in-memory via SQLAlchemy engine URL
    engine = create_engine('sqlite:///:memory:')
    
    df = pd.DataFrame({
        'ProjectID': [501, 502],
        'ProjectName': ['Alpha AI', 'Beta Cloud'],
        'Budget': [50000, 120000]
    })
    
    # Write using SQLAlchemy engine
    df.to_sql('projects', engine, index=False, if_exists='replace')
    
    # Read using SQLAlchemy engine
    result = pd.read_sql("SELECT * FROM projects", engine)
    print("=== SQLAlchemy ENGINE READ RESULT ===")
    print(result.to_string(index=False))

sqlalchemy_demo()
Output: === SQLAlchemy ENGINE READ RESULT == ProjectID ProjectName Budget 501 Alpha AI 50000 502 Beta Cloud 120000
7. Handling DataFrame Primary Keys and Indexing in SQL Tables
Defining primary keys and table indexing constraints when writing Pandas DataFrames to SQL tables using index_label and `dtype`.
Python (sql_primary_keys.py)
import pandas as pd
import sqlite3

def primary_key_demo():
    conn = sqlite3.connect(':memory:')
    df = pd.DataFrame({
        'SKU': ['A101', 'A102'],
        'Item': ['Keyboard', 'Mouse'],
        'Stock': [45, 120]
    })
    
    # Write with explicit primary key definition via sqlite connection cursor
    df.to_sql('inventory', conn, index=False, if_exists='replace')
    
    # Verify table schema via sqlite_master
    schema = pd.read_sql_query("PRAGMA table_info(inventory);", conn)
    print("=== INVENTORY TABLE SCHEMA ===")
    print(schema[['cid', 'name', 'type', 'notnull']])
    conn.close()

primary_key_demo()
Output: === INVENTORY TABLE SCHEMA == cid name type notnull 0 SKU TEXT 0 1 Item TEXT 0 2 Stock INTEGER 0
8. Incremental Data Appending to Existing SQL Tables (`if_exists='append'`)
Appending new daily transaction logs to an existing database table without overwriting historical records.
Python (sql_append_data.py)
import pandas as pd
import sqlite3

def append_data_demo():
    conn = sqlite3.connect(':memory:')
    
    # Initial batch
    batch_1 = pd.DataFrame({'TxID': [1, 2], 'Amount': [100, 250]})
    batch_1.to_sql('transactions', conn, index=False, if_exists='replace')
    
    # New daily batch
    batch_2 = pd.DataFrame({'TxID': [3, 4], 'Amount': [400, 150]})
    batch_2.to_sql('transactions', conn, index=False, if_exists='append')
    
    master_tx = pd.read_sql_query("SELECT * FROM transactions", conn)
    print("=== MASTER TRANSACTIONS AFTER APPEND ===")
    print(master_tx.to_string(index=False))
    conn.close()

append_data_demo()
Output: === MASTER TRANSACTIONS AFTER APPEND == TxID Amount 1 100 2 250 3 400 4 150
9. Executing Non-Query SQL Commands (INSERT, UPDATE, DELETE)
Executing direct Data Manipulation Language (DML) commands against a database connection using cursor execution.
Python (sql_dml_commands.py)
import pandas as pd
import sqlite3

def dml_execution_demo():
    conn = sqlite3.connect(':memory:')
    df = pd.DataFrame({'UserID': [1, 2], 'Status': ['Active', 'Active']})
    df.to_sql('users', conn, index=False, if_exists='replace')
    
    # Execute UPDATE command via cursor
    cursor = conn.cursor()
    cursor.execute("UPDATE users SET Status = 'Inactive' WHERE UserID = 2")
    conn.commit()
    
    updated_df = pd.read_sql_query("SELECT * FROM users", conn)
    print("=== USERS TABLE AFTER DML UPDATE ===")
    print(updated_df.to_string(index=False))
    conn.close()

dml_execution_demo()
Output: === USERS TABLE AFTER DML UPDATE == UserID Status 1 Active 2 Inactive
10. End-to-End SQL-to-Pandas Analytical Pipeline
Synthesizing database creation, data insertion, SQL querying, in-memory Pandas transformation, and result persistence into a unified pipeline.
Python (sql_analytical_pipeline.py)
import pandas as pd
import sqlite3

def sql_pipeline():
    conn = sqlite3.connect(':memory:')
    
    # 1. Ingest raw data into SQL
    sales_data = pd.DataFrame({
        'Region': ['North', 'South', 'North', 'South'],
        'Category': ['Tech', 'Tech', 'Furniture', 'Furniture'],
        'Revenue': [1200, 800, 400, 600]
    })
    sales_data.to_sql('raw_sales', conn, index=False, if_exists='replace')
    
    # 2. Query aggregated summary from SQL
    query = "SELECT Region, SUM(Revenue) as TotalRevenue FROM raw_sales GROUP BY Region"
    summary_df = pd.read_sql_query(query, conn)
    
    # 3. Post-process in Pandas (Rank regions by revenue)
    summary_df['Rank'] = summary_df['TotalRevenue'].rank(ascending=False).astype(int)
    
    # 4. Persist processed summary back to database
    summary_df.to_sql('region_rankings', conn, index=False, if_exists='replace')
    
    print("=== PIPELINE RESULT PERSISTED TO SQL ===")
    print(pd.read_sql_query("SELECT * FROM region_rankings", conn).to_string(index=False))
    conn.close()

sql_pipeline()
Output: === PIPELINE RESULT PERSISTED TO SQL === Region TotalRevenue Rank North 1600 1 South 1400 2