Sub topic 1
How a SQL result becomes a DataFrame
A relational database stores data in tables and sends it back as query results. A pandas DataFrame is an in-memory table with labeled columns and one dtype per column. This chapter covers what happens between the two. You will see which parts of a result the DataFrame keeps, which parts change, and which parts are lost. Later chapters cover connections, parameters, type options and chunking in detail. Here you build the mental model that explains their behavior.
Prerequisites
This chapter assumes you already know:
- Basic Python, including functions and context managers.
- Basic pandas: what a DataFrame is, how to select columns, and what
dtypesshows. - Basic SQL:
SELECT,WHERE,GROUP BYandJOIN.
You need Python 3 with pandas installed. The examples use the sqlite3 module from the standard library, so no database server is required.
What a query result is
A query result is a sequence of rows. Every row has the same columns, and the query decides which columns exist and what they are called. The result is not the table. A SELECT with a WHERE, a JOIN or a GROUP BY returns a new, temporary table that exists only for that query.
Python database drivers follow the DB-API standard (PEP 249). With it, a query result reaches Python in three parts:
- A cursor object represents the executed statement.
cursor.descriptionlists the result columns. The first item of each entry is the column name.cursor.fetchall()returns the rows, usually as a list of tuples.
pandas builds a DataFrame from exactly these parts. It uses the names from description as column labels and the tuples as row data. It then infers a dtype for each column.
The mapping looks like this:
| SQL result | DataFrame |
|---|---|
| Result set | One DataFrame |
| Column name or alias | Column label |
| Row | Row, labeled by the index |
| Row order | Row order (position) |
| Value in a column | Element of a Series with one dtype |
| `NULL` | `NaN`, `None` or `NaT`, depending on the column |
| Declared column type | Not carried over. pandas infers dtypes from the Python values |
| Primary key, constraints, foreign keys | Not carried over |
The last two rows cause most surprises. A DataFrame does not remember the schema. It only has the values that came back.
The pipeline from query to DataFrame
The database does the filtering, joining and aggregating. pandas never sees rows that the query did not return.
Doing it by hand first
The following script creates the example database used throughout this tutorial and loads a query result in two ways. The first way builds the DataFrame manually from the cursor. The second uses pandas.read_sql_query.
import sqlite3
import pandas as pd
conn = sqlite3.connect("shop.db")
conn.executescript("""
DROP TABLE IF EXISTS orders;
CREATE TABLE orders (id INTEGER PRIMARY KEY, customer TEXT, total REAL, created_at TEXT);
INSERT INTO orders VALUES
(1, 'Ada', 120.5, '2024-01-05'),
(2, 'Grace', 80.0, '2024-01-09'),
(3, 'Ada', 200.0, '2024-02-01');
""")
conn.commit()
sql = "SELECT id, customer, total FROM orders ORDER BY id"
# Manual route: cursor -> description + rows -> DataFrame
cur = conn.execute(sql)
rows = cur.fetchall()
columns = [d[0] for d in cur.description]
print(columns)
print(rows)
manual = pd.DataFrame(rows, columns=columns)
# Shortcut: pandas does the same steps for you
df = pd.read_sql_query(sql, conn)
print(df)
print(manual.equals(df))The printed lists show the raw material:
['id', 'customer', 'total']
[(1, 'Ada', 120.5), (2, 'Grace', 80.0), (3, 'Ada', 200.0)]The DataFrame holds the same values. The last line prints True, because the manual DataFrame and the one from read_sql_query have the same labels, values and dtypes.
read_sql_query does a little more than the manual route. It also handles bound parameters, converts selected columns to dates, can set an index, and can return results in chunks. Later chapters cover those options. The core conversion is the one shown above.
Column names come from the query
The DataFrame's column labels are whatever the database reports for each result column. For a plain column reference, that is the column name. For an expression, the name is database-specific and often awkward, for example SUM(total). Give every computed column an alias:
df = pd.read_sql_query(
"SELECT customer, SUM(total) AS revenue FROM orders GROUP BY customer",
conn,
)
print(df)
print(df.columns.tolist())The labels are customer and revenue. Without AS revenue, you would have to select the column with a label such as SUM(total), and that label can differ between databases.
Duplicate names are a related trap. When two joined tables both have an id column, the database returns two result columns named id. pandas keeps both:
dup = pd.read_sql_query(
"SELECT a.id, b.id FROM orders a JOIN orders b ON a.customer = b.customer AND a.id < b.id",
conn,
)
print(dup.columns.tolist())This prints ['id', 'id']. Selecting dup["id"] then returns a DataFrame with two columns instead of one Series. Alias the columns in SQL (a.id AS order_id, b.id AS other_id) so every label is unique.
Where dtypes come from
The database does not tell pandas which dtype to use. The driver converts each value to a Python object, and pandas inspects the objects in each column and picks a dtype.
With sqlite3, the Python types are:
| SQLite storage class | Python type | Typical DataFrame dtype |
|---|---|---|
| INTEGER | `int` | `int64` |
| REAL | `float` | `float64` |
| TEXT | `str` | `object` (or `str` in pandas 3) |
| BLOB | `bytes` | `object` |
| NULL | `None` | depends on the column, see below |
Check the example result:
df = pd.read_sql_query("SELECT id, customer, total, created_at FROM orders", conn)
print(df.dtypes)The id column is int64 and total is float64. The created_at column is text in SQLite, so it arrives as strings. It is not a datetime column. Converting it is a separate step covered in the chapter on indexes, dates and dtypes.
Other databases return richer Python objects. PostgreSQL drivers typically return datetime.datetime for timestamps and decimal.Decimal for NUMERIC columns. read_sql_query has a coerce_float option, which is true by default. It converts Decimal values to floating point. That is convenient, but it loses exact decimal precision. Keep this in mind if you handle money values.
Inference works on values, not on declarations
SQLite uses dynamic typing. A column declared REAL can still hold a string if someone inserted one. pandas sees the actual values. If a column mixes numbers and strings, pandas gives it the object dtype. A declared column type is therefore a hint about the data, not a guarantee about the dtype.
NULL values
NULL becomes None in Python. pandas then decides how to store it, and the result depends on the other values in the column.
df = pd.read_sql_query(
"""
SELECT id,
CASE WHEN id = 2 THEN NULL ELSE id END AS maybe_id,
CASE WHEN id = 2 THEN NULL ELSE customer END AS maybe_customer,
NULL AS nothing
FROM orders
ORDER BY id
""",
conn,
)
print(df)
print(df.dtypes)You can expect these results:
maybe_idbecomesfloat64. The integer values turn into floats, and theNULLbecomesNaN. A standard NumPy integer array cannot hold a missing value.maybe_customerstaysobject. TheNULLappears asNone.nothinghas onlyNULLvalues, so there is nothing to infer a type from. It is anobjectcolumn filled withNone.
Using COALESCE(column, 0) in the query keeps an integer column as int64, but it also replaces "unknown" with 0. Decide whether that is acceptable for your data before doing it.
Row order and the index
SQL tables have no guaranteed row order. Without an ORDER BY, the database may return rows in any order, and that order can change between runs, after updates or after the database builds a new index. The DataFrame keeps whatever order arrives.
By default, the DataFrame gets a RangeIndex (0, 1, 2, ...). The values in id are an ordinary column and are not used as labels. This is a common surprise for people who expect the primary key to become the index. pandas does not know which column is the primary key, because the schema is not part of the result. The index_col option lets you choose a column explicitly. Chapter 5 covers it.
If your analysis depends on order, for example when you compute running totals or take the first row per customer, put an explicit ORDER BY in the query.
A DataFrame is a snapshot
The DataFrame is a copy of the result at the moment the query ran. It has no link back to the database:
df = pd.read_sql_query("SELECT id, total FROM orders ORDER BY id", conn)
df["total"] = df["total"] * 2
print(df["total"].tolist())
again = pd.read_sql_query("SELECT id, total FROM orders ORDER BY id", conn)
print(again["total"].tolist())The first line prints [241.0, 160.0, 400.0]. The second prints [120.5, 80.0, 200.0]. Editing the DataFrame does not change the table. Writing changes back is a separate task, done with DataFrame.to_sql or with SQL UPDATE statements. It is outside the scope of this tutorial.
The reverse also holds. If another process updates the table after your query, your DataFrame stays as it was until you query again.
Memory and the shape of the result
Because the whole result is copied into memory, its size matters. A DataFrame needs memory for every row and column, and Python objects such as strings cost more than numbers. A query that returns 50 million rows can exhaust memory even if the database handles it easily. Three habits keep results manageable:
- Select only the columns you need.
- Filter and aggregate in SQL, so fewer rows cross into Python. The chapter on deciding what to do in SQL and what in pandas covers this.
- Read in pieces with
chunksizewhen the result is too big for memory.
Empty results
A query that matches no rows still gives you a DataFrame. It has the right columns and zero rows:
empty = pd.read_sql_query("SELECT id, customer FROM orders WHERE id < 0", conn)
print(empty.shape)
print(empty.columns.tolist())
print(empty.dtypes)The shape is (0, 2). The column labels come from cursor.description, which exists even when there are no rows. With no values to inspect, pandas cannot infer meaningful dtypes, so the columns are typically object. If later code assumes int64 or float64, an empty result may behave differently from a non-empty one. Test that case.
Where this model helps you debug
Several common problems follow directly from the pipeline above:
- A column has the wrong dtype. The cause is either dynamic typing in the database or inference from values. Check the raw values first, then convert.
- An integer column became float. The result contains
NULLvalues. - A date column is full of strings. The database stored text, or the driver returned text. pandas does not convert it unless you ask.
- Rows come back in a different order. The query has no
ORDER BY. df["id"]returns a DataFrame. The query returned duplicate column names.- The DataFrame does not reflect a recent change. It is a snapshot. Run the query again.
Summary
A SQL result arrives as a list of rows plus a description of its columns. pandas turns the names into column labels and the rows into data, then infers one dtype per column from the Python values. The schema, keys and constraints do not come along. Row order, NULL handling and column names depend on what your query asks for, so write queries with explicit columns, aliases and ordering.
Exercise
A query returns the columns id (INTEGER) and discount (REAL). In the table, discount is NULL for some rows, and id has no NULLs. After loading the result with pd.read_sql_query, what dtype does each column have? What would change if the query selected CASE WHEN total > 100 THEN id END AS big_id FROM orders instead of plain id?
Show answer
id is int64 and discount is float64, with NaN where the database has NULL. The plain id column has no NULLs, so it stays an integer. The big_id column contains NULL for rows where the condition is false, so it becomes float64 with NaN. To keep integers, filter the rows in SQL, use COALESCE, or convert to the nullable Int64 dtype after loading.
Exercise
You run SELECT a.id, b.id FROM orders a JOIN orders b ON a.customer = b.customer AND a.id < b.id and then call df["id"].sum(). Why does this misbehave, and how do you fix it?
Show answer
Both result columns are named id, so pandas keeps two columns with the same label. df["id"] returns a DataFrame with two columns instead of a Series, so .sum() returns one value per column instead of a single number. Fix it by aliasing in SQL, for example SELECT a.id AS order_id, b.id AS other_id ..., so each label is unique.