← Back to Pandas Course | Chapter 11: File I/O | Lesson 4 of 7

read_sql

read_sql runs a SQL query and returns the result as a DataFrame.

In this page:

  1. read_sql
Syntax
python
df = pd.read_sql("SELECT * FROM table_name", connection)

read_sql

pd.read_sql(query, connection) works with a DBAPI connection such as sqlite3 or an SQLAlchemy engine. Use params for safe parameter binding. The reverse, to_sql, writes a DataFrame into a table.

Note: Use parameters (params=) instead of building SQL with string formatting.

Example: read_sql

python
import sqlite3
import pandas as pd

con = sqlite3.connect(":memory:")
pd.DataFrame({"id": [1, 2, 3], "name": ["Ann", "Bob", "Cy"]}).to_sql("users", con, index=False)
print(pd.read_sql("SELECT * FROM users WHERE id > ?", con, params=(1,)))
con.close()

# Output:
#    id name
# 0   2  Bob
# 1   3   Cy
Related Topics
Common Mistakes
  1. Building queries with string formatting
  2. Forgetting to close the connection
  3. Not specifying if_exists in to_sql
Chapter Summary
  • read_sql runs a query into a DataFrame
  • Works with sqlite3 connections
  • to_sql writes tables
  • Use params for safety
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.