SQL with Python — pandas and SQLite
Query databases directly from Python using pandas and run SQL on DataFrames with DuckDB
Data analysts often need to pull data from SQL databases into Python for further analysis. You can query SQL Server, MySQL, PostgreSQL, and SQLite from Python — loading results directly into Pandas DataFrames. You can also run SQL queries ON Pandas DataFrames using DuckDB or pandasql — letting you use familiar SQL syntax on in-memory data.
Examples
Key Points
- ✓pd.read_sql(query, connection) loads SQL query results directly into a DataFrame
- ✓sqlalchemy.create_engine() connects to SQL Server, MySQL, PostgreSQL
- ✓DuckDB runs SQL directly on Pandas DataFrames — no database server needed
- ✓df.to_sql() writes a DataFrame to a database table
- ✓Combining SQL + Python is the most powerful analyst stack: SQL for extraction, Python for analysis
Practice Question
Which function loads the results of a SQL query directly into a Pandas DataFrame?
Related Topics
Merging DataFramesCombine DataFrames with merge and concat — the Pandas equivalent of SQL JOINsgroupby and Pivot TablesAggregate data by category with groupby — the Pandas equivalent of Excel pivot tablesReading CSV and Excel FilesLoad data from CSV, Excel, and multiple sheets into Pandas DataFrames