24. How to Load SQL Query Results into a pandas DataFrame
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
- Database holds the source of truth (orders, stores, riders).
- You ask with SQL: only the rows and columns you need.
- pandas loads the result into memory as a DataFrame.
- You analyse in Python (groupby, merge, charts).
- 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).
Ravindra Bagale's Tip – मराठी
SQL म्हणजे fridge आणि pandas म्हणजे kitchen चा counter असं समजा. तुम्हाला हवे असलेले columns आणि date range एवढंच बाहेर काढा, आणि खरं काम pandas मध्ये करा. मोठ्या table वर SELECT * चालवून पूर्ण fridge रिकामा करू नका, कारण त्यात वेळ आणि memory (RAM) वाया जाते.
Ravindra Bagale's Tip – हिंदी
SQL को fridge और pandas को kitchen का counter समझो। सिर्फ़ ज़रूरी columns और date range ही बाहर निकालो, और असली काम pandas में करो। बड़ी table पर SELECT * चलाकर पूरा fridge खाली मत करो, क्योंकि इससे समय और memory (RAM) बर्बाद होती है।