Sub topic 5
Controlling the index, dates and dtypes
pandas.read_sql_query infers a type for every column and gives you a default RangeIndex. The inferred types are often not the ones you want. A date stored as text stays text. An integer column that contains NULL becomes floating point. This chapter shows how to override those defaults with index_col, parse_dates, dtype, coerce_float and dtype_backend.
This chapter assumes you can open a connection (sqlite3 or a SQLAlchemy engine) and call read_sql_query with a query string. It also assumes you know the common pandas dtypes (int64, float64, object, datetime64, category).
What read_sql_query infers on its own
A database driver hands pandas plain Python values, one tuple per row. pandas builds columns from those tuples and guesses a dtype for each column. It does not see the column types declared in your CREATE TABLE statement.
Run this setup block first. It uses an in-memory SQLite database, so it does not touch shop.db. The later examples in this chapter reuse conn.
import sqlite3
import pandas as pd
conn = sqlite3.connect(":memory:")
conn.executescript("""
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
customer TEXT,
total REAL,
quantity INTEGER,
created_at TEXT,
shipped_at TEXT
);
INSERT INTO orders VALUES
(1, 'Ada', 120.5, 2, '2024-01-05', '2024-01-07'),
(2, 'Grace', 80.0, NULL, '2024-01-09', NULL),
(3, 'Ada', 200.0, 5, '2024-02-01', '2024-02-03'),
(4, NULL, 35.25, 1, '2024-02-14', NULL);
""")
conn.commit()
df = pd.read_sql_query("SELECT * FROM orders", conn)
print(df)
print(df.dtypes)The default result looks like this:
| Column | SQL content | Inferred dtype | Why |
|---|---|---|---|
| `id` | integers | `int64` | No missing values. |
| `customer` | text, one `NULL` | `object` (or `str` in pandas 3) | Python strings, with `None` for `NULL`. |
| `total` | floats | `float64` | No missing values. |
| `quantity` | integers, one `NULL` | `float64` | `NULL` becomes `NaN`, which only floats can hold. |
| `created_at` | ISO date text | `object` | SQLite stores dates as text. pandas does not guess dates. |
| `shipped_at` | date text, two `NULL` | `object` | Same, plus `None` values. |
The sections below fix the last four rows.
The order of operations
pandas applies the options in a fixed order after it builds the raw columns. The order matters when you combine options.
Three consequences follow from this order:
- A column named in
index_colmust exist in the query result. Otherwise you get aKeyError. dtyperuns beforeparse_dates, so do not list the same column in both.- Columns moved into the index are no longer available as ordinary columns.
Choosing the index with index_col
By default pandas numbers the rows 0, 1, 2 and so on. If the result has a natural key, pass its name to index_col:
df = pd.read_sql_query("SELECT * FROM orders", conn, index_col="id")
print(df.index)
print(df.loc[3, "customer"])The id column becomes the index and disappears from the columns. This is the same as calling set_index("id") afterwards, but it is shorter and it happens inside the read.
A list of names builds a MultiIndex:
df = pd.read_sql_query(
"SELECT id, customer, total FROM orders WHERE customer IS NOT NULL",
conn,
index_col=["customer", "id"],
)
print(df.loc["Ada"])parse_dates runs before index_col, so you can use a date column as the index and get a real DatetimeIndex:
df = pd.read_sql_query(
"SELECT created_at, total FROM orders ORDER BY created_at",
conn,
index_col="created_at",
parse_dates=["created_at"],
)
print(df.index.dtype)
print(df.loc["2024-01"])Partial-string selection such as df.loc["2024-01"] works because the index holds datetimes. With a text index it would look for the literal string "2024-01".
The index is not checked for uniqueness. If you use a non-unique column such as customer, pandas accepts it, but label lookups return several rows.
Parsing dates with parse_dates
Most databases have date types, but SQLite does not. It stores whatever text you give it. Other drivers may also return dates as strings if the column is VARCHAR. Use parse_dates to convert such columns to datetime64.
The simplest form is a list of column names:
df = pd.read_sql_query(
"SELECT id, created_at, shipped_at FROM orders",
conn,
parse_dates=["created_at", "shipped_at"],
)
print(df.dtypes)
print(df)Both columns become datetime64. NULL becomes NaT (not a time), the datetime version of NaN. The unit of the datetime64 dtype (ns, us, and so on) depends on your pandas version.
Giving a format
A dictionary maps a column name to a strftime format string. An explicit format is faster than letting pandas guess, and it avoids day/month confusion in dates like 03/04/2024:
df = pd.read_sql_query(
"SELECT id, created_at FROM orders",
conn,
parse_dates={"created_at": "%Y-%m-%d"},
)
print(df.dtypes)Integer timestamps
If the column holds numbers, the dictionary value is a time unit ("s", "ms", "us" or "ns") instead of a format. A numeric column listed in parse_dates without a unit is read as seconds since 1970, which is wrong for millisecond values. Always give the unit.
conn.executescript("""
DROP TABLE IF EXISTS clicks;
CREATE TABLE clicks (id INTEGER PRIMARY KEY, clicked_ms INTEGER);
INSERT INTO clicks VALUES (1, 1704448800000), (2, 1704535200000);
""")
clicks = pd.read_sql_query(
"SELECT * FROM clicks",
conn,
parse_dates={"clicked_ms": "ms"},
)
print(clicks)The two values become 2024-01-05 10:00:00 and 2024-01-06 10:00:00, both in UTC.
Time zones and extra options
If the value is a dictionary of options, pandas passes them to pandas.to_datetime. This is the way to ask for UTC. It also handles text that carries a UTC offset:
conn.executescript("""
DROP TABLE IF EXISTS logins;
CREATE TABLE logins (id INTEGER PRIMARY KEY, logged_in TEXT);
INSERT INTO logins VALUES
(1, '2024-03-01T09:30:00+02:00'),
(2, '2024-03-01T09:45:00+01:00');
""")
logins = pd.read_sql_query(
"SELECT * FROM logins",
conn,
parse_dates={"logged_in": {"utc": True}},
)
print(logins["logged_in"])The result has dtype datetime64[ns, UTC] (or another unit), with values 07:30 and 08:45 UTC. Without utc=True, mixed offsets cannot be held in one datetime column, and you may get an object column or a warning, depending on your pandas version.
Setting dtypes with dtype
dtype accepts a single dtype for every column, or a dictionary for selected columns. It is available in pandas 1.3 and later.
df = pd.read_sql_query(
"SELECT id, customer, total, quantity FROM orders",
conn,
dtype={
"customer": "category",
"total": "float32",
"quantity": "Int64",
},
)
print(df.dtypes)
print(df)This does three things:
customerbecomescategory, which stores each distinct name once. It is useful for columns with few distinct values and many rows.totalbecomesfloat32, which uses half the memory offloat64but keeps about seven significant digits.quantitybecomesInt64(capital I), the nullable integer type. It stores the integers as integers and shows the missing value as<NA>instead of turning the whole column into floats.
dtype is applied with astype, so it follows the rules of astype. If a conversion is impossible, you get an error instead of a quiet fallback. For example, dtype={"quantity": "int64"} fails on this data because of the NULL.
Dtypes and dates
Do not use dtype for dates. Use parse_dates, which understands formats and units. You can combine both options when they name different columns:
df = pd.read_sql_query(
"SELECT id, customer, quantity, created_at FROM orders",
conn,
index_col="id",
parse_dates={"created_at": "%Y-%m-%d"},
dtype={"customer": "category", "quantity": "Int64"},
)
print(df.dtypes)Handling NULL values
NULL arrives in Python as None. What pandas does with it depends on the column:
| Column content | Default result | Missing value shown as |
|---|---|---|
| Integers with `NULL` | `float64` | `NaN` |
| Floats with `NULL` | `float64` | `NaN` |
| Text with `NULL` | `object` | `None` |
| Dates after `parse_dates` | `datetime64` | `NaT` |
| `Int64` via `dtype` | `Int64` | `<NA>` |
The most surprising row is the first. A quantity of 5 turns into 5.0 just because another row is NULL. Two fixes exist.
The first is a per-column dtype="Int64", shown above.
The second is dtype_backend, available in pandas 2.0 and later. It asks pandas to use nullable types for every column at once:
df = pd.read_sql_query(
"SELECT id, customer, total, quantity FROM orders",
conn,
dtype_backend="numpy_nullable",
)
print(df.dtypes)You get Int64, Float64 and string columns, and all of them use <NA> for missing values. The value "pyarrow" selects Arrow-backed dtypes instead, if the pyarrow package is installed.
Decimal values and coerce_float
Some databases, such as PostgreSQL with NUMERIC columns, return decimal.Decimal objects. By default (coerce_float=True) pandas converts them to float64, which is convenient but not exact. If you need exact decimal arithmetic, for example for money, pass coerce_float=False. The column then keeps its Decimal objects in an object column. SQLite does not return Decimal, so you will not see a difference in this chapter's examples.
Keeping types stable across chunks
When you read with chunksize, pandas infers types separately for every chunk. A column that has no NULL in one chunk and a NULL in the next changes dtype between chunks:
for chunk in pd.read_sql_query("SELECT id, quantity FROM orders", conn, chunksize=2):
print(chunk["quantity"].dtype)The first chunk contains a NULL and is float64. The second chunk has only integers and is int64. Concatenating them silently produces float64 and hides the inconsistency. Passing dtype pins the type for every chunk:
chunks = pd.read_sql_query(
"SELECT id, quantity FROM orders",
conn,
chunksize=2,
dtype={"quantity": "Int64"},
)
df = pd.concat(chunks, ignore_index=True)
print(df.dtypes)parse_dates and index_col are also applied to each chunk, so the combined frame has a consistent index and datetime columns.
Converting in SQL instead
You can also fix types in the query. A CAST or a date function changes the value before it reaches pandas:
df = pd.read_sql_query(
"""
SELECT id,
COALESCE(quantity, 0) AS quantity,
strftime('%Y-%m', created_at) AS month
FROM orders
""",
conn,
)
print(df.dtypes)COALESCE(quantity, 0) removes the NULL, so quantity stays int64. Use this only when a default value is meaningful. A missing quantity is not the same as zero, so replacing it can hide a data problem. Date functions differ between databases (strftime is SQLite, date_trunc is PostgreSQL), so SQL-side conversion makes the query less portable.
Common mistakes
| Symptom | Cause | Fix |
|---|---|---|
| `KeyError` for an `index_col` name | The column is not in the `SELECT` list, or an alias changed its name. | Select the column, or use the alias in `index_col`. |
| Date column still shows `object` | The column was not listed in `parse_dates`, or the format did not match. | Add it, and give a `format` that matches the text. |
| Timestamps show year 1970 | Millisecond integers parsed as seconds. | Use `parse_dates={"col": "ms"}`. |
| Error: cannot convert NaN to integer | `dtype="int64"` on a column with `NULL`. | Use `Int64`, or fill the `NULL` in SQL. |
| Integer column became floats | A `NULL` appeared in the data. | Use `dtype` with `Int64`, or `dtype_backend`. |
| Column set in both `dtype` and `parse_dates` fails | `dtype` runs first and may already have altered the text. | Use only `parse_dates` for date columns. |
| Dtypes differ between chunks | Inference runs per chunk. | Pass `dtype` for the affected columns. |
Exercise
A table readings has an integer column sensor_id, a NULL-able integer column count, and an integer column taken_ms that stores milliseconds since 1970. Write the arguments you would add to pd.read_sql_query("SELECT * FROM readings", conn, ...) so that sensor_id is the index, count keeps integer values with missing entries shown as <NA>, and taken_ms becomes datetimes.
Show answer
Use index_col="sensor_id", dtype={"count": "Int64"} and parse_dates={"taken_ms": "ms"}. The Int64 dtype keeps whole numbers next to missing values. The "ms" unit stops pandas from reading the numbers as seconds. taken_ms appears only in parse_dates, not in dtype.
Exercise
You read a table in chunks of 10,000 rows and concatenate the results. The quantity column is int64 in most chunks and float64 in a few, and the combined column is float64. Why does this happen, and how do you stop it?
Show answer
pandas infers dtypes separately for each chunk. A chunk that contains a NULL in quantity gets float64 (with NaN), and other chunks get int64. Concatenation then promotes everything to float64. Passing dtype={"quantity": "Int64"} to read_sql_query gives every chunk the same nullable integer type.
Exercise
After pd.read_sql_query("SELECT id, created_at FROM orders", conn, parse_dates=["created_at"]), the column is datetime64, but you expected 1,000 rows and find 40 NaT values, although the table has no NULL in created_at. What happened, and how would you find the cause?
Show answer
Text that does not match the date format becomes NaT without an error. Query the raw text with pd.read_sql_query("SELECT id, created_at FROM orders", conn) and then inspect the rows whose parsed value is NaT, for example with raw[parsed.isna()]. Fix the data, or pass a format with parse_dates={"created_at": "%Y-%m-%d"} that matches the real text.