Data Science · मराठी आवृत्ती
24.3 pd.read_sql आणि read_sql_query
या course चे सर्व chapters (py + ch)
- How to Use This Free Data Science Course
- How to Install Python, Jupyter Notebook and VS Code for Data Science (Windows and Mac)
- Python Variables and Data Types Explained for Beginners (int, float, str, bool)
- Python Strings Tutorial: Slicing, f-strings and String Methods with Examples
- Python Lists, Tuples, Dictionaries and Sets Explained with Examples
- Python if, elif and else Statements with Real Examples for Beginners
- Python for Loops and while Loops Explained with Examples (range, break, continue)
- Python Functions Tutorial: def, return, Arguments and lambda with Examples
- Python Errors and Exceptions: How to Use try, except, else and finally
- How to Read and Write CSV, JSON and Text Files in Python (with open and with)
- Python Modules, pip and Virtual Environments (venv) Explained for Beginners
- Python Classes and Objects for Beginners: OOP Basics with Simple Examples
- NumPy Tutorial for Beginners: Arrays, Maths and Filtering in Python
- Python Mini Projects for Beginners: 5 Practice Projects Before Learning pandas
- Data Science vs Data Analytics Tutorial
- Python Jupyter Setup for Data Science
- Python Basics for Data Science Tutorial
- NumPy Essentials for Data Science Tutorial
- pandas DataFrames and Series Tutorial
- Filter and Sort Data in pandas Tutorial
- pandas GroupBy and Aggregations Tutorial
- Merge and Concat Data in pandas Tutorial
- Data Cleaning in pandas A–Z Tutorial
- Dates and Text in pandas – Free Tutorial
- Reshape Data: melt and pivot_table
- Exploratory Data Analysis in Python
- matplotlib Visualization Tutorial – Free
- seaborn Visualization Tutorial – Free
- Chart Choice and Data Storytelling
- Data Science Project: Blinkit Maharashtra
- Data Science Practice Exercises
- Data Science Interview Questions
- pandas matplotlib seaborn Cheat Sheet
- Data Science Glossary – Free Tutorial
- Stats for Data Work Mean Median IQR
- Export CSV Excel PNG from pandas Tutorial
- Common pandas Mistakes and Fixes Tutorial
- Load SQL Query Results into pandas DataFrame – Free Tutorial
- How to Rank and Running Totals in pandas
- How to Read APIs, JSON and Zipped CSVs into pandas
- How to Use Git with Jupyter Notebooks for Data Projects
- How to Merge and Join Tables in pandas for Blinkit Data
- What Is Machine Learning Simple Explanation
- Machine Learning Workflow Step by Step
- Train Test Split in Machine Learning sklearn
- Features and Labels in Machine Learning
- Linear Regression in Python with sklearn
- Classification with Logistic Regression in Python
- Decision Trees and Random Forests in Python
- K-Means Clustering in Python for Beginners
- How to Check If Your ML Model Is Good
- Overfitting and Underfitting in Machine Learning
- End-to-End ML Project India Dataset
- Data Preprocessing for ML: Impute Scale Encode
- What Is a Neural Network Simple Explanation
- Activation Loss Gradient Descent Plain English
- Backpropagation Intuition No Heavy Maths
- Install PyTorch and First Tensors
- Your First Neural Network in PyTorch
- Deep Learning vs Classical ML When to Use Which
- Convolutional Neural Networks CNNs for Images
- Small CNN Image Project in PyTorch
- What Transformers Are Text and Sequences
- Tiny Text Classifier Transformer Intro PyTorch
- What Is Natural Language Processing NLP
- Text Cleaning and TF-IDF in Python sklearn
- Sentiment Analysis Project in Python TF-IDF
- NLP vs ChatGPT Classical NLP and Generative AI
हे का शिकायचं?
एक function call ने DataFrame मिळतो. Query string स्वच्छ ठेवा.
हे काय आहे?
pd.read_sql_query(sql, con) सामान्य pattern. Parameters bind करा — string format नाही.
कसं करायचं?
Step 1. SQL text तयार करा.
Step 2. Connection object.
Step 3. read_sql_query.
Step 4. df.head() आणि dtypes.
उदाहरणं: copy करा आणि चालवा
उदाहरण A — Seed + read (copy-paste lab).
import sqlite3
import pandas as pd
from pathlib import Path
Path("data").mkdir(exist_ok=True)
con = sqlite3.connect("data/blinkit_lab.db")
con.execute("DROP TABLE IF EXISTS orders")
con.execute(
"""
CREATE TABLE orders (
order_id TEXT,
city TEXT,
status TEXT,
amount_inr REAL,
customer TEXT
)
"""
)
rows = [
("BLK-261024-001", "Pune", "Delivered", 189.0, "Ruhi Bagale"),
("BLK-261024-002", "Pune", "Cancelled", 90.0, "Amir"),
("BLK-261024-003", "Nashik", "Delivered", 95.0, "Zoya"),
("AMN-261024-004", "Kolhapur", "Delivered", 210.0, "Ravina"),
("BLK-261024-005", "Nagpur", "Returned", 150.0, "Raja"),
("BLK-261024-006", "Solapur", "Delivered", 120.0, "Salman"),
("BLK-261024-007", "Sambhaji Nagar", "Delivered", 340.0, "Rani"),
("AMN-261024-008", "Pune", "Delivered", 72.0, "Shraddha Bagale"),
]
con.executemany("INSERT INTO orders VALUES (?,?,?,?,?)", rows)
con.commit()
df = pd.read_sql_query(
"SELECT order_id, city, status, amount_inr, customer FROM orders",
con,
)
print(df.shape)
print(df.head())
con.close()
What you should see. Eight rows, five columns. amount_inr is numeric. You can now df.loc[df["city"] == "Pune"] like any other chapter.
उदाहरण B — read_sql vs read_sql_query.
import sqlite3
import pandas as pd
con = sqlite3.connect("data/blinkit_lab.db")
sql = "SELECT city, COUNT(*) AS n FROM orders GROUP BY city ORDER BY n DESC"
a = pd.read_sql(sql, con)
b = pd.read_sql_query(sql, con)
print(a.equals(b))
con.close()
For everyday SELECT work, either name is fine. Prefer read_sql_query when you want the code to shout “I am not loading a whole table blindly”.
उदाहरण C — After the pull, same pandas you know.
import sqlite3
import pandas as pd
con = sqlite3.connect("data/blinkit_lab.db")
df = pd.read_sql_query(
"SELECT city, status, amount_inr FROM orders WHERE status = 'Delivered'",
con,
)
con.close()
g = (
df.groupby("city", as_index=False)["amount_inr"]
.agg(orders="count", gmv="sum")
.sort_values("gmv", ascending=False)
)
print(g)