Sub topic 3
Loading query results with read_sql_query
This chapter assumes you know basic Python, the pandas DataFrame and its dtypes, and SQL SELECT, WHERE, GROUP BY and JOIN. It also assumes you can open a database connection, as covered in the previous chapter. Later chapters cover parameters, index and date handling, and chunking in depth. This chapter covers the function itself: what it accepts, what it returns, and how the result's shape and types are decided.
What read_sql_query does
pandas.read_sql_query sends one SQL statement to a database and returns the rows it produces as a DataFrame. It does these steps:
- Gets a cursor from the connection and executes your SQL string.
- Reads the column names from the cursor's description.
- Fetches the rows as tuples.
- Builds a DataFrame from those names and rows, then applies options such as
index_col,parse_datesanddtype.
The database decides which rows and columns exist. pandas decides how Python and NumPy represent them.
The signature
These are the parameters in pandas 2.x:
pandas.read_sql_query(
sql,
con,
index_col=None,
coerce_float=True,
params=None,
parse_dates=None,
chunksize=None,
dtype=None,
dtype_backend=<no_default>,
)Only sql and con are required. This table summarizes the rest:
| Parameter | Purpose | Covered |
|---|---|---|
| `sql` | The SQL string, or a SQLAlchemy `text()` or selectable | This chapter |
| `con` | A `sqlite3` connection, SQLAlchemy connection or engine | Previous chapter |
| `params` | Values bound to placeholders in the query | Next chapter |
| `index_col` | Column or columns to use as the index | Index and dtypes chapter |
| `parse_dates` | Columns to convert to datetimes | Index and dtypes chapter |
| `dtype` | Dtypes to apply to result columns | Index and dtypes chapter |
| `coerce_float` | Convert non-string, non-numeric objects such as `decimal.Decimal` to float | This chapter |
| `chunksize` | Return an iterator of DataFrames instead of one DataFrame | Chunking chapter |
| `dtype_backend` | Use nullable or Arrow-backed dtypes | Index and dtypes chapter |
Everything after con should be passed by keyword. That keeps calls readable and protects you if the order changes.
A first query
This script creates a small database and reads from it. The later examples in this chapter reuse the conn object it creates.
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()
df = pd.read_sql_query("SELECT id, customer, total FROM orders", conn)
print(df)
print(df.dtypes)The output looks like this:
id customer total
0 1 Ada 120.5
1 2 Grace 80.0
2 3 Ada 200.0
id int64
customer object
total float64
dtype: objectThree things to notice:
- The columns appear in the order of the
SELECTlist. - The index is a default
RangeIndex. Theidcolumn stays an ordinary column unless you ask for it as the index. - pandas inferred dtypes from the Python values the driver returned. It did not read them from the table schema.
That last point explains most type surprises, and the "Where types come from" section below returns to it.
Column names come from the query
The DataFrame's column labels are whatever the database reports for each result column. A plain column reference keeps its name. An expression gets a name the database chooses, and that name is often awkward:
raw = pd.read_sql_query(
"SELECT customer, SUM(total) FROM orders GROUP BY customer",
conn,
)
print(raw.columns.tolist())
named = pd.read_sql_query(
"SELECT customer, SUM(total) AS revenue FROM orders GROUP BY customer ORDER BY customer",
conn,
)
print(named)
print(named.columns.tolist())The first list is ['customer', 'SUM(total)']. The second query uses AS revenue, so you can write named["revenue"]. Other databases name unaliased expressions differently, for example sum in PostgreSQL or ?column? for some expressions. Alias every computed column so your code does not depend on that.
Aliases also solve a collision problem. A join can produce two columns with the same name:
SELECT a.id, b.id
FROM orders AS a
JOIN orders AS b ON a.customer = b.customerpandas builds a DataFrame with two columns both labeled id. After that, df["id"] returns a DataFrame rather than a Series, and many operations behave unexpectedly. Give each one a distinct alias:
pairs = pd.read_sql_query(
"""
SELECT a.id AS order_id, b.id AS other_order_id
FROM orders AS a
JOIN orders AS b ON a.customer = b.customer AND a.id < b.id
""",
conn,
)
print(pairs)Only the Ada pair (orders 1 and 3) matches, so the result has one row.
Where types come from
The database driver returns Python objects, and pandas infers dtypes from them. The rules for the common cases follow.
| Database value | Python object from sqlite3 | DataFrame dtype |
|---|---|---|
| INTEGER | `int` | `int64` |
| REAL | `float` | `float64` |
| TEXT | `str` | `object` |
| NULL in a text column | `None` | `object` (stays `None`) |
| NULL in a numeric column | `None` | `float64` with `NaN` (integer columns become float) |
| Date stored as TEXT | `str` | `object` |
The most common surprise is an integer column that contains a NULL. NumPy's int64 cannot hold a missing value, so the whole column becomes float64, and 3 turns into 3.0. You can see this without any table:
nulls = pd.read_sql_query(
"SELECT 1 AS n UNION ALL SELECT NULL",
conn,
)
print(nulls)
print(nulls.dtypes)The column n has the values 1.0 and NaN, with dtype float64. If you need integers that allow missing values, the index and dtypes chapter shows dtype and dtype_backend. If the NULLs are not meaningful, handle them in SQL with COALESCE(n, 0).
SQLite is an unusual case because it has no real date type. A column declared as DATE still holds text, so you get strings back. PostgreSQL and MySQL drivers return datetime objects for their date and timestamp types, which pandas converts to datetime64. The same code can therefore give different dtypes on different databases. That is why parse_dates exists.
The coerce_float=True default matters for databases that return decimal.Decimal values, such as NUMERIC columns in PostgreSQL. With the default, those values become float64. Set coerce_float=False to keep them as Decimal objects when you need exact arithmetic. The result is an object column, and you lose vectorized speed.
Empty results
A query that matches no rows still returns a DataFrame. It has the right columns and zero rows:
empty = pd.read_sql_query(
"SELECT id, customer, total FROM orders WHERE total > 1000",
conn,
)
print(empty.empty)
print(empty.columns.tolist())
print(empty.dtypes)empty.empty is True and the column labels are present. The dtypes are object for every column, because there were no values to infer from. If later code assumes float64 for total, an empty result can break it, for instance when you call a string method or merge on mismatched dtypes. When a result may be empty, pass dtype explicitly so the types do not depend on the data:
typed = pd.read_sql_query(
"SELECT id, customer, total FROM orders WHERE total > 1000",
conn,
dtype={"id": "int64", "total": "float64"},
)
print(typed.dtypes)Check for emptiness with df.empty or len(df) == 0. Do not test for None, because the function never returns None.
Passing the SQL
The sql argument is usually a plain string. Triple-quoted strings keep long queries readable, and the database ignores the extra whitespace:
report = pd.read_sql_query(
"""
SELECT customer,
COUNT(*) AS n_orders,
SUM(total) AS revenue,
AVG(total) AS avg_order
FROM orders
GROUP BY customer
HAVING COUNT(*) >= 1
ORDER BY revenue DESC
""",
conn,
)
print(report)Some rules apply to what you pass:
- Send one statement that returns rows. A
SELECT, aWITH ... SELECT, or aPRAGMAthat returns rows all qualify. Writes such asINSERT,UPDATEandDELETEreturn no rows, so useconn.executeorDataFrame.to_sqlfor those. - Do not rely on row order unless the query has an
ORDER BY. SQL tables have no inherent order, and a database may return rows differently after an update or an index change. - With SQLAlchemy you can pass
text("...")or aselect()construct instead of a string. Thetext()form is needed when you use named parameters such as:name. - Never build the string by inserting user input yourself. The next chapter shows how
paramsdoes this safely.
Connection types and the warning
read_sql_query accepts three kinds of con:
- A standard-library
sqlite3.Connection. pandas supports this one directly. - A SQLAlchemy
EngineorConnection, which works for any database SQLAlchemy supports. - Any other DBAPI2 connection, such as one from
psycopg2orpymysql. pandas does not officially support these. It works for simple cases, but pandas emits aUserWarningrecommending SQLAlchemy.
If you see that warning, the cause is the connection type, not your query. Switching to a SQLAlchemy engine removes it.
Closing connections is your responsibility. A sqlite3 connection used in a with block commits or rolls back a transaction when the block ends, but it does not close the connection. contextlib.closing handles that:
from contextlib import closing
import sqlite3
import pandas as pd
with closing(sqlite3.connect("shop.db")) as connection:
snapshot = pd.read_sql_query("SELECT * FROM orders", connection)
print(len(snapshot))The DataFrame is fully built before the connection closes, so you can keep using snapshot afterward. That holds as long as you did not set chunksize. With chunksize the function returns a lazy iterator, and reading from it after the connection closes fails.
Choosing options for a typical call
A realistic call combines several parameters. This one uses the options with the largest effect on the result:
df = pd.read_sql_query(
"SELECT id, customer, total, created_at FROM orders ORDER BY created_at",
conn,
index_col="id",
parse_dates=["created_at"],
)
print(df)
print(df.dtypes)id becomes the index and is no longer a column. created_at is datetime64[ns] instead of object, so df["created_at"].dt.month works. The following chapters explain each option in detail.
Where the work happens
read_sql_query transfers every row your query returns into Python memory. That means the amount of data you pull is set by the SQL, not by what you later keep. The two queries below produce the same revenue figures, but they transfer different amounts of data:
# Transfers every order row, then aggregates in pandas
all_rows = pd.read_sql_query("SELECT customer, total FROM orders", conn)
local = all_rows.groupby("customer", as_index=False)["total"].sum()
# Transfers one row per customer
remote = pd.read_sql_query(
"SELECT customer, SUM(total) AS total FROM orders GROUP BY customer",
conn,
)
print(local)
print(remote)On three rows the difference is invisible. On three hundred million rows, the first version may exhaust memory or spend most of its time on the network. Select only the columns you need, filter with WHERE, and aggregate with GROUP BY when the result you want is a summary. The pushdown chapter covers when pandas is still the better place to compute something.
Common mistakes
| Symptom | Likely cause | Fix |
|---|---|---|
| `UserWarning` about DBAPI2 connections | Non-SQLite DBAPI connection | Use a SQLAlchemy engine |
| `df["id"]` returns a DataFrame | Duplicate column names from a join | Alias columns in SQL |
| Integer column shows `1.0`, `NaN` | NULLs in an integer column | Use `COALESCE`, or set `dtype` or `dtype_backend` |
| Date column has dtype `object` | Dates stored as text | Pass `parse_dates` |
| Empty frame breaks later code | Types inferred from zero rows | Pass `dtype` explicitly |
| Odd column name such as `SUM(total)` | Unaliased expression | Add `AS name` |
| Error when passing an `INSERT` | Statement returns no rows | Use `conn.execute` and commit |
| Out-of-memory on a big table | Loading all rows at once | Filter or aggregate in SQL, or use `chunksize` |
Exercises
Exercise
A query selects a.id, b.id from a self-join and you then call df["id"].sum(). It fails or returns something that is not a number. Why, and what is the fix?
Show answer
Both result columns are labeled id, so df["id"] returns a two-column DataFrame instead of a Series. Alias the columns in the SQL, for example a.id AS order_id, b.id AS other_order_id, so each label is unique.
Exercise
A table has an integer column qty with some NULL values. After read_sql_query, the column shows values like 3.0 and NaN. Why does this happen, and name one way to avoid it?
Show answer
NumPy's int64 cannot store missing values, so pandas converts the column to float64, with NaN for NULL. You can avoid it by replacing NULLs in SQL with COALESCE(qty, 0), or by requesting a nullable integer type through dtype={"qty": "Int64"} or dtype_backend="numpy_nullable".
Exercise
You run pd.read_sql_query("SELECT id, total FROM orders WHERE total > 1000", conn) and no rows match. What does the function return, and what is a risk for code that uses the result?
Show answer
It returns an empty DataFrame with columns id and total and zero rows, not None. Because there are no values to infer from, both columns have dtype object, so code that expects numeric dtypes may break. Passing dtype={"id": "int64", "total": "float64"} fixes the types regardless of the data.
Exercise
Write a call that returns one row per customer with the number of orders as n_orders, ordered by customer name, using the orders table from this chapter.
Show answer
pd.readsqlquery("SELECT customer, COUNT(*) AS n_orders FROM orders GROUP BY customer ORDER BY customer", conn)