How to Connect Python to SQL for Data Analysis with pandas and SQLAlchemy
The connection between Python and a SQL database runs through SQLAlchemy: you build an engine from the database connection string and hand that engine to pandas, which returns the query result as a DataFrame. From there, cleaning, analysis, and modeling all happen inside Python, with no manual CSV exports. This walkthrough shows the full flow, from the engine to the first query read in a notebook.
How do you connect Python to a SQL database with SQLAlchemy?
The connection happens in two steps: you create a SQLAlchemy engine with the database connection string, then pass that engine to pandas. The engine works as a reusable connection pool, so you don't open and close a connection for every query — you create it once in the notebook and reuse the same variable.
The connection string follows the format dialect+driver://user:password@host:port/database. In PostgreSQL, for example: create_engine('postgresql+psycopg2://user:password@localhost:5432/sales'). For MySQL use mysql+pymysql; for SQL Server, mssql+pyodbc; for SQLite, just the file path.
The driver has to be installed alongside SQLAlchemy. Without it, the engine is created without an error, but the first query fails when it tries to open the connection — a common mistake, and an easy one to diagnose.
- Install the libraries: pip install pandas sqlalchemy plus the driver for your database (psycopg2-binary, pymysql, or pyodbc).
- Build the connection string with user, password, host, port, and database name.
- Create the engine once with create_engine(...) and reuse the variable.
- Test with pd.read_sql('SELECT 1', engine) before writing long queries.
- Keep credentials in an environment variable or a .env file, never directly in versioned code.
How do you read a SQL query straight into a pandas DataFrame?
The function pd.read_sql_query('SELECT * FROM orders WHERE date >= ...', engine) runs the SQL on the database and returns a DataFrame with columns and types inferred. You write the query in your database's dialect and pandas handles building the table.
For large tables, use the chunksize parameter. read_sql_query(..., chunksize=100000) returns an iterator of chunks, and you process each part in a loop without loading everything into memory at once.
It's worth setting types at read time: parse_dates converts date columns and dtype forces numeric or categorical types. Doing this during extraction avoids repeated conversions later in the analysis.
When you need the whole table with no filter, pd.read_sql_table('table_name', engine) does the job. For anything with a JOIN, an aggregation, or a filter, prefer read_sql_query.
Do you need to know programming or SQL before you start?
You don't need to know how to program before you start. The Python for Data Science and Analytics course begins from zero: installing an IDE and Jupyter Notebook, basic functions, loops and conditionals, user-defined functions.
On the database side, what you need is a query that brings the right columns into Python. The course doesn't start there — it starts with Python and moves through NumPy and pandas, data visualization, data cleaning and preparation, and outlier detection.
In other words: extraction through SQLAlchemy and pandas is the start of the flow, and the rest of the path is exactly what the course covers.
What do you do with the data after you pull it from the database?
After read_sql, the work becomes pandas: data cleaning and preparation, outlier detection, visualization. That's the core of the course, which covers NumPy and pandas, data visualization, and data cleaning and preparation.
The advanced part brings in linear and logistic regression, K-Means, SVM, Naive Bayes, decision trees, Random Forest, Gradient Boosting, XGBoost, LightGBM, feature selection, and cross-validation.
The course closes with a final project: end-to-end exploratory analysis and machine learning — the same flow of extracting from a database, treating, visualizing, and modeling. Guided practice exercises and real market projects are there to build a portfolio.
Lessons are recorded in high quality and watched at the student's own pace, with unlimited access and no expiration date.
How much does the course cost and how does access work?
The course costs R$ 470, or 12 installments of R$ 20,37 on a credit card. Payment goes through the Hotmart checkout, by credit card or boleto.
The structure has three main modules — Basic, Intermediate, and Advanced — plus bonus modules. The student keeps access to the course with no expiration date, and completion comes with a certificate. There is also an exclusive community for networking.
The course is described on python.paanalytics.net, and enrollment starts at the Hotmart checkout link.
Start pulling data from SQL with Python
Secure payment via Hotmart, up to 12 installments.
Enroll now Product siteFrequently asked questions
Which driver should I install for PostgreSQL, MySQL, or SQL Server?
PostgreSQL uses psycopg2 (psycopg2-binary for the quick install), MySQL uses pymysql, and SQL Server uses pyodbc. SQLite ships with Python, so it needs no extra driver — you point the connection string at the file path. Install the driver in the same environment as pandas and SQLAlchemy; a driver installed in a different environment is the same as no driver at all.
Should I use read_sql_query or read_sql_table?
Use read_sql_table when you want the entire table and nothing else — it takes the table name and the engine. Use read_sql_query for anything with a WHERE clause, a JOIN, or an aggregation, because that version accepts a SQL string. Most analysis work starts with read_sql_query, since pulling a whole table is rarely what you actually want.
How do I handle a table that's too large to fit in memory?
Pass chunksize to read_sql_query. Instead of one DataFrame, you get an iterator of smaller DataFrames, and you process each chunk in a loop — aggregating, filtering, or appending to a file. This keeps memory use flat no matter how big the table is. Filtering in SQL first, with a date range or a set of IDs, is usually simpler than chunking.
Where should I keep database credentials in a notebook?
In an environment variable or a .env file that isn't versioned, never hard-coded in a notebook cell. A notebook with a password in it tends to get shared, committed, or pasted into a chat. Read the value with os.environ or python-dotenv and build the connection string from those variables.
Does the course cover connecting to a database, or only pandas?
The course covers Python from zero through NumPy and pandas, data visualization, data cleaning and preparation, and outlier detection, then machine learning topics such as linear and logistic regression, K-Means, SVM, Naive Bayes, decision trees, Random Forest, Gradient Boosting, XGBoost, LightGBM, feature selection, and cross-validation, closing with an end-to-end exploratory analysis and machine learning project. The extraction step shown on this page is where that flow begins.