Python Central HubSign in

Data Analytics with Python / Phase 9: SQL for Data Analytics

SQL from Python (pandas + sqlite3)

Run SQL queries from Python, load results into pandas, and build reproducible analysis scripts.

Why integrate SQL + Python

A common workflow:

  1. Use SQL to extract/aggregate data efficiently
  2. Load into pandas
  3. Visualize/model

Using SQLite locally

SQLite is file-based and great for learning.

Create a small demo database

Python
import sqlite3
import pandas as pd
 
conn = sqlite3.connect("demo.db")
 
# Example: create a table
conn.execute("""
CREATE TABLE IF NOT EXISTS users (
  user_id INTEGER PRIMARY KEY,
  country TEXT,
  plan TEXT
)
""")
 
conn.execute("DELETE FROM users")
conn.executemany(
    "INSERT INTO users(user_id, country, plan) VALUES (?, ?, ?)",
    [(1, "IN", "free"), (2, "IN", "pro"), (3, "US", "pro")],
)
conn.commit()

Query into pandas

Python
import pandas as pd
 
q = """
SELECT country, COUNT(*) AS users
FROM users
GROUP BY country
"""
 
df = pd.read_sql_query(q, conn)
print(df)

Good practice

  • Keep SQL in triple-quoted strings or .sql files.
  • Parameterize user inputs (avoid SQL injection).
  • Version-control your analysis scripts.

Two ways to get from SQL to a DataFrame

McKinney's Python for Data Analysis covers exactly this workflow in §6.4, "Interacting with Databases." There are two paths, and it's worth seeing both:

diagram SQL -> DataFrame, two paths mermaid
The raw sqlite3 driver returns tuples you must pair with column names yourself; pandas.read_sql does that munging for you.

The manual way (what the book shows first)

Python
import sqlite3
import pandas as pd
 
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE test (a TEXT, b TEXT, c REAL, d INTEGER)")
data = [
    ("Atlanta", "Georgia", 1.25, 6),
    ("Tallahassee", "Florida", 2.6, 3),
    ("Sacramento", "California", 1.7, 5),
]
conn.executemany("INSERT INTO test VALUES (?, ?, ?, ?)", data)
conn.commit()
 
cursor = conn.execute("SELECT * FROM test")
rows = cursor.fetchall()
columns = [col[0] for col in cursor.description]
 
df = pd.DataFrame(rows, columns=columns)
print(df)
Python
             a           b     c  d
0      Atlanta     Georgia  1.25  6
1  Tallahassee     Florida  2.60  3
2   Sacramento  California  1.70  5

The shortcut (what you'll actually use)

Python
df = pd.read_sql_query("SELECT * FROM test", conn)
print(df)

Same result, one line. read_sql_query works with a plain sqlite3 connection; the book's pd.read_sql example additionally shows connecting through SQLAlchemy (sqla.create_engine), which is the more general path once you move beyond SQLite to Postgres, MySQL, or a warehouse.

Check your understanding

quizCheck yourself
  1. Which pandas call turns a SQL query result into a labeled DataFrame in one line?

    Show answer

    A — pd.read_sql_query(q, conn) — read_sql_query works with a plain sqlite3 connection and does the column labeling for you.

  2. What must you do manually when building a DataFrame from a raw sqlite3 cursor?

    Show answer

    A — Pull column names from cursor.description — fetchall returns a list of tuples with no names, so you build columns from cursor.description.

  3. Why does the lesson use placeholders such as (?, ?, ?) and advise parameterizing inputs?

    Show answer

    A — To avoid SQL injection — Parameterized queries keep user input from being executed as SQL.

  4. Which sequence matches the common workflow?

    Show answer

    A — Extract with SQL, load into pandas, then visualize or model — SQL extracts and aggregates efficiently, then pandas handles the analysis.

🧪 Try It Yourself

Exercise 1 – Build column names from cursor.description

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

Exercise 2 – pd.DataFrame from rows + columns

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

Exercise 3 – The read_sql_query shortcut

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

Next

Put everything from this phase together in the SQL Mini Project (Build a KPI Dashboard Query Set) — a small, reusable pack of queries you can point at any similar dataset.

Was this page helpful?

Let us know how we did