Sub topic 1
How a SQL result becomes a DataFrame
Prerequisites
Assume you know basic Python, pandas DataFrame objects, and SQL statements such as SELECT and WHERE. You also need a database connection. A connection is an object that lets Python send SQL to a database and receive results.
From rows to columns
A SQL query returns a result set. Each selected expression becomes a column, and each returned record becomes a row. pandas.read_sql_query converts that result set into a DataFrame.
| SQL result | DataFrame |
|---|---|
| Column names | Column labels |
| Records | Rows |
| SQL values | Python or pandas values |
The conversion preserves the selected column order. SQL types are mapped to suitable pandas dtypes when possible. For example, a numeric SQL column usually becomes an integer or floating-point column.
Connecting with sqlite3 and SQLAlchemy
SQLite stores a database in a local file. Python’s standard-library sqlite3 module can open that file without an additional database server.
import sqlite3
import pandas as pd
conn = sqlite3.connect("shop.db")
df = pd.read_sql_query(
"SELECT id, customer, total FROM orders",
conn,
)
print(df)
conn.close()For other database systems, SQLAlchemy is a common connection layer. An SQLAlchemy engine manages connections using a database URL.
from sqlalchemy import create_engine
import pandas as pd
engine = create_engine("sqlite:///shop.db")
with engine.connect() as connection:
df = pd.read_sql_query(
"SELECT id, customer, total FROM orders",
connection,
)
print(df)The sqlite3 connection is convenient for SQLite. An SQLAlchemy engine is usually easier to configure when an application may use different database systems.
>``callout note > Keep connections open while pandas reads the result. Use a context manager or close the connection explicitly when finished. >``
Loading query results with `read_sql_query`
Pass the SQL statement as the first argument and the connection or engine as the second. Select only the columns and rows needed by the analysis. The returned object is a normal DataFrame, so you can inspect it with df.head(), df.dtypes, and other pandas operations.
Exercise
What does one SQL result row become in a DataFrame?
Show answer
It becomes one DataFrame row, with the selected SQL columns becoming DataFrame columns.