Skip to content

BUG: Sql select from database type cast issue #62013

@Closius

Description

@Closius

Pandas version checks

  • I have checked that this issue has not already been reported.

  • I have confirmed this bug exists on the latest version of pandas.

  • I have confirmed this bug exists on the main branch of pandas.

Reproducible Example

from pathlib import Path
import tempfile
import shutil
import datetime

import pandas as pd

from sqlalchemy import (
    create_engine, MetaData, Table, Column, Integer,
    Float, DateTime, select, insert
)


class DB:

    def __init__(self, db_file_path: str | Path):
        self.engine = create_engine(f"sqlite:///{db_file_path}", echo=False)
        self.metadata = MetaData()
        self._table = Table(
            "main_table", self.metadata,

            Column('time', DateTime, unique=True),
            Column('a', Float, nullable=False),
            Column('b', Float, nullable=False),
            Column('c', Integer, nullable=True),
            Column('d', Float, nullable=True),

            keep_existing=True
        )

        self.metadata.create_all(self.engine)

    def populate(self):
        data = [
            {"time": datetime.datetime.fromisoformat('2025-07-26T04:11:00Z'), "a": 1.1, "b": 1.2, "c": None, "d": None},
            {"time": datetime.datetime.fromisoformat('2025-07-26T05:22:00Z'), "a": 2.1, "b": 2.2, "c": None, "d": None},
            {"time": datetime.datetime.fromisoformat('2025-07-26T06:33:00Z'), "a": 3.1, "b": 3.2, "c": None, "d": None},
            {"time": datetime.datetime.fromisoformat('2025-07-26T07:44:00Z'), "a": 4.1, "b": 4.2, "c": None, "d": None},
            {"time": datetime.datetime.fromisoformat('2025-07-26T08:55:00Z'), "a": 5.1, "b": 5.2, "c": None, "d": None},
        ]
        with self.engine.connect() as conn:
            conn.execute(insert(self._table), data)
            conn.commit()

    def read_records(self):
        _select = select(self._table)
        with self.engine.connect() as conn:
            df = pd.read_sql(_select, conn)
        return df

    def __del__(self):
        self.engine.dispose()


if __name__ == '__main__':
    temp_folder = Path(tempfile.mkdtemp(prefix="pandas_bug_"))
    db_file_path = temp_folder / "collected_data_binance.db"
    print(db_file_path)
    if db_file_path.exists():
        db_file_path.unlink()

    db = DB(db_file_path=db_file_path)
    db.populate()
    df = db.read_records()
    print(df.info())

    del(db)
    shutil.rmtree(temp_folder)

Issue Description

Db types:

Image

Db data:

Image

After reading data using pd.read_sql(_select, conn) we see:

Image

Expected Behavior

The columns with NULL should inherit type from column type of DB instead of "object"

Installed Versions

INSTALLED VERSIONS

commit : 2cc3762
python : 3.13.3
python-bits : 64
OS : Windows
OS-release : 11
Version : 10.0.22631
machine : AMD64
processor : Intel64 Family 6 Model 183 Stepping 1, GenuineIntel
byteorder : little
LC_ALL : None
LANG : None
LOCALE : English_United States.1252
pandas : 2.3.0
numpy : 1.26.4
pytz : 2025.2
dateutil : 2.9.0.post0
pip : 25.1.1
Cython : None
sphinx : None
IPython : None
adbc-driver-postgresql: None
adbc-driver-sqlite : None
bs4 : None
blosc : None
bottleneck : None
dataframe-api-compat : None
fastparquet : None
fsspec : 2025.5.1
html5lib : None
hypothesis : None
gcsfs : None
jinja2 : 3.1.6
lxml.etree : None
matplotlib : None
numba : None
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
psycopg2 : None
pymysql : None
pyarrow : 20.0.0
pyreadstat : None
pytest : 8.4.1
python-calamine : None
pyxlsb : None
s3fs : None
scipy : None
sqlalchemy : 2.0.41
tables : None
tabulate : 0.9.0
xarray : None
xlrd : None
xlsxwriter : None
zstandard : None
tzdata : 2025.2
qtpy : None
pyqt5 : None

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugNeeds TriageIssue that has not been reviewed by a pandas team member

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions