Ravindra BagaleCourses & study guides मराठी Track your progress

24. How to Load SQL Query Results into a pandas DataFrame

Data Science

24.1 Why Pull SQL into pandas

Why. Shraddha Bagale (Pune ops) gets a nightly dump as CSV. By 11 am the dump is stale. The live orders table in MySQL already has today’s Diwali spike. Ruhi needs a fresh Pune vs Nashik delivered GMV in pandas for a WhatsApp chart (Chapter 22). SQL → DataFrame is the bridge.

What. You run a SELECT (or a short query) against a database. pandas returns a DataFrame — same object you already know from Chapters 5–23. Then you clean, group, plot, and export as usual.

How.

Mental model

  1. Database holds the source of truth (orders, stores, riders).
  2. You ask with SQL: only the rows and columns you need.
  3. pandas loads the result into memory as a DataFrame.
  4. You analyse in Python (groupby, merge, charts).
  5. You export CSV / Excel / PNG for managers — you do not write back to ops tables from this course.

Worked example A — When CSV is enough.

Raja downloads last month’s closed orders once for a training notebook. CSV is fine. No live connection needed.

Worked example B — When SQL is better (fictional).

Amir’s manager asks at 4 pm IST: “Delivered GMV today for Pune dark stores only.” The morning CSV missed the afternoon rush. A small SELECT … WHERE order_date = CURRENT_DATE AND city = 'Pune' into pandas answers in one cell.

Worked example C — Stack sketch.

Store of truth You pull with You analyse in
MySQL / Postgres / SQLite SQL SELECT pandas DataFrame
Shared drive CSV pd.read_csv same DataFrame tools

Ravindra Bagale's Tip

Think of SQL as the fridge and pandas as the kitchen counter. Take out only the columns and the date range you need, and do the real work in pandas. Do not empty the whole fridge with SELECT * on a huge table, because it wastes time and memory (RAM).