Skip to the workspace
Pebellslearn by building
Loading Data  ›  Capstone Project

From a SQL Database into pandas

sqlite3 14 minpandas can send a SQL query through a database connection and receive the result as a DataFrame, and the database should filter and summarise before data crosses over.

python data analysis / From a SQL Database into pandas

Explore each scene at your own pace.

01 · The rule

The rule

From a SQL Database into pandas

The bookshop's till does not really write CSV files: it stores every sale in a database, and the CSV is an export someone remembers to run. Going straight to the database means fresher data and no middle step. pandas can send a SQL query and receive the answer as a DataFrame.

The rule

Connect, send a query, get a DataFrame; let the database filter first.

Python ships with sqlite3, a small database stored in a single file. No server needed:

import sqlite3
import pandas as pd

conn = sqlite3.connect("shop.db")

delhi = pd.read_sql(
    "SELECT branch, genre, copies FROM sales WHERE branch = 'Delhi'",
    conn,
)
conn.close()

read_sql runs the query and builds a DataFrame from the result, using the SQL column names as column names. Writing works too: sales.to_sql("sales", conn, if_exists="replace", index=False) creates a table from a DataFrame.

When a value comes from a variable, do not glue it into the string. Pass it as a parameter so the database treats it purely as data:

pd.read_sql("SELECT * FROM sales WHERE branch = ?", conn, params=("Delhi",))

For other databases, such as PostgreSQL or MySQL, you connect through SQLAlchemy, which gives every database the same connection style:

from sqlalchemy import create_engine
engine = create_engine("postgresql://user:password@host/shop")
pd.read_sql("SELECT * FROM sales", engine)

DuckDB is a third option built for analysis. It can run SQL directly on DataFrames and files already on your machine:

import duckdb
duckdb.sql("SELECT branch, SUM(copies) FROM sales GROUP BY branch").df()
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.