Sub topic 3
Loading query results with read_sql_query
This chapter assumes you know basic Python, pandas DataFrames and dtypes, and simple SQL (SELECT, WHERE, GROUP BY). It also assumes you have a connection to a database, as covered in the previous chapter. Here you will run a query and get a DataFrame back.
What read_sql_query does
pandas.read_sql_query takes a SQL string and a connection. It runs the query, reads every row the database returns, and builds a DataFrame from them. Column names come from the result set, and each column's dtype is inferred from the Python values the driver returns.
The two required arguments are sql and con. The rest of this chapter uses only those two. Later chapters cover params, index_col, parse_dates and chunksize.
Create a sample database
The examples use a small SQLite file. Run this first. It creates shop.db and loads all rows with a plain SELECT.
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)The output is a DataFrame with three rows and the columns id, customer and total. The index is the default 0, 1, 2 range. The id column is an ordinary column, not the index.
Inspect what you got
After any load, check the shape and dtypes before you trust the result.
import sqlite3
import pandas as pd
conn = sqlite3.connect("shop.db")
df = pd.read_sql_query("SELECT id, customer, total, created_at FROM orders", conn)
print(df.shape)
print(df.dtypes)
conn.close()You should see id as int64, customer as object, total as float64, and created_at as object. SQLite stores dates as text, so created_at arrives as strings. The next chapter section on types shows how to convert it while loading.
This second block opens its own connection, so it runs on its own as long as the first block has already created shop.db.
How column names and types are decided
Pandas does not read the table schema. It uses whatever the query returns. Three consequences follow.
- Aliases set the column names.
SELECT total * 1.2 AS total_with_taxproduces a column calledtotal_with_tax. Without the alias, the name is whatever expression text your database reports, which is awkward to use. - Dtypes come from the values. A column of Python
intvalues becomesint64. A column of strings becomesobject. If an integer column containsNULL, the driver returnsNonefor that row. Pandas then typically stores the column asfloat64withNaN, or asobject, depending on the driver and data. - Duplicate names are kept.
SELECT a.id, b.id FROM ...gives a DataFrame with two columns both namedid. Alias them to avoid confusion.
Empty results
A query that matches no rows still returns a DataFrame. It has the right column names and zero rows. Every column has dtype object, because there are no values to infer types from.
import sqlite3
import pandas as pd
conn = sqlite3.connect("shop.db")
empty = pd.read_sql_query("SELECT id, total FROM orders WHERE total > 1000", conn)
print(empty.empty)
print(list(empty.columns))
print(empty.dtypes)
conn.close()Code that later does arithmetic on an empty DataFrame can fail or behave oddly because of those object columns. If an empty result is possible, test df.empty first.
Connections and cleanup
read_sql_query does not close the connection for you. With sqlite3, with conn: only commits or rolls back a transaction. It does not close the connection. Call conn.close() yourself, or wrap the connection in contextlib.closing.
import sqlite3
from contextlib import closing
import pandas as pd
with closing(sqlite3.connect("shop.db")) as conn:
df = pd.read_sql_query("SELECT customer, total FROM orders", conn)
print(df)The connection is closed when the with block ends, but the DataFrame remains available because all rows were already copied into memory.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Building the query with an f-string that includes user input | SQL injection risk, quoting bugs | Use `params` (next chapter) |
| Using `SELECT *` on a wide table | Slow load, extra memory | List only the columns you need |
| Forgetting to close the connection | Open file handles or locks | Use `closing` or call `close()` |
| Assuming dates are datetimes | Date columns are text strings | Convert with `parse_dates` |
| Running a statement that returns no result set, such as `INSERT` | An error, because there are no columns to read | Use the connection's `execute` for writes |
Exercise
You run pd.readsqlquery("SELECT customer, SUM(total) FROM orders GROUP BY customer", conn). The second column has an awkward name. How do you fix it in the query, and what does the DataFrame look like if the query matches no rows?
Show answer
Add an alias, for example SUM(total) AS revenue, so the column is named revenue. If no rows match, you get an empty DataFrame with the columns customer and revenue, zero rows, and object dtypes.