Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

Pandas · Function

pd.read_sql_query

Reads a SQL query result into a pandas DataFrame, optionally selecting an index, parsing dates, setting dtypes, or streaming rows in chunks. It accepts SQL text or a SQLAlchemy Selectable and can return a DataFrame iterator when chunksize is set.

How it works

The function executes a SQL query through a supported connection and converts its result set into a DataFrame. Optional arguments control indexing, numeric coercion, date parsing, chunked iteration, explicit dtypes, and the dtype backend.

Syntax

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>)

Parameters

NameTypeDescription
sqlstr or SQLAlchemy SelectableSQL query or SQLAlchemy Selectable (select or text object) to execute.
conSQLAlchemy connectable, str, or sqlite3 connectionConnection object or database location; SQLAlchemy connectable, URI string, or sqlite3 connection.
index_colstr or list of str, optionalColumn or columns to use as the DataFrame index.
coerce_floatbool, default TrueAttempt to convert suitable non-string, non-numeric objects to floating point.
paramslist, tuple, or mapping, optionalValues passed to the database driver's execute method.
parse_dateslist-like, dict, or scalars, optionalColumns to parse as dates; supports column names, lists, or parsing dictionaries.
chunksizeint, optionalNumber of rows per returned DataFrame chunk; when set, returns an iterator.
dtypeType name or dict of column -> type, optionalColumn dtype specification for the resulting DataFrame.
dtype_backend{‘numpy_nullable’, ‘pyarrow’}, default ‘numpy_nullable’Specifies the nullable-dtype backend used for the resulting DataFrame.
returnDataFrame or Iterator[DataFrame]The executed query result, as one DataFrame or an iterator of DataFrames when chunking is requested.

Returns

DataFrame or Iterator[DataFrame]. The DataFrame contains the executed query's result set; with chunksize specified, an iterator yields DataFrame chunks.

Key points

  • The normal result is a DataFrame representing rows produced by the SQL query.
  • Use index_col to promote a result column, or columns, into the DataFrame index.
  • With coerce_float enabled, pandas attempts to convert suitable non-string, non-numeric values to floating point.
  • Supply params as a list, tuple, or mapping for values passed to query execution.

Common mistakes

  • Parameter placeholders are not portable across database drivers; use the placeholder style required by the driver.
  • For raw DBAPI2 connections, use sqlite3; use a SQLAlchemy connectable for other databases.

Example: Read a parameterized SQLite query

import sqlite3
import pandas as pd

with sqlite3.connect(":memory:") as con:
    con.executescript("CREATE TABLE users (id INTEGER, name TEXT); INSERT INTO users VALUES (1, 'Ada'), (2, 'Grace');")
    result = pd.read_sql_query(
        "SELECT id, name FROM users WHERE id > ?",
        con,
        params=(1,),
        index_col="id",
    )
    print(result)

Runs a parameterized SQLite query, uses the selected column as the DataFrame index, and prints the result.

When to use it

Query data for analysis

Load filtered or aggregated database results into pandas for analysis.

Read in chunks

Process large result sets without materializing every row at once.

Parse and coerce columns

Normalize database date and numeric values during ingestion.

Select a dtype backend

Choose nullable NumPy or PyArrow dtypes at DataFrame creation.

Interview questions

QWhat does pandas.read_sql_query return?

It accepts a SQL string or SQLAlchemy Selectable and a SQLAlchemy connectable, URI string, or sqlite3 connection. The query result is returned as a DataFrame, unless chunksize is set, in which case iteration over DataFrames is returned.

Follow-up: How would you process a result too large for memory? Set chunksize and consume the returned DataFrame iterator incrementally.

QHow does index_col affect the result?

index_col selects one or more result columns as the DataFrame index; without it, pandas uses the default integer index. A list of columns can create a MultiIndex.

Follow-up: What should be checked when choosing an index column? Verify that the selected result column or columns exist and have the intended uniqueness and ordering.

QHow are query parameters supplied?

params passes values to the underlying execute method, but its accepted placeholder syntax depends on the database driver. The documentation points to DBAPI parameter styles and the driver documentation for the supported form.

Follow-up: Why should values not be interpolated into SQL text? Driver parameters preserve driver-specific binding behavior and avoid treating values as SQL syntax.

  • pandas.read_sql
  • pandas.read_sql_table
  • pandas.DataFrame
  • pandas.read_sql_query

Source: pandas.read_sql_query — pandas 3.0.6 documentation. Checked 2026-10-15.