Data analysts spend much of their day writing SQL to answer business questions: How much did we sell this month? Which category grows fastest? Who are our best customers? This tutorial shows the query patterns behind those answers, and how to pull the results into pandas.
What You Will Learn
- Monthly revenue and order counts
- Month-over-month growth with LAG
- Share of total by category
- Top customers and average order value
- Running SQL from Python into a pandas DataFrame
Prerequisites
SQL Basics and Advanced SQL.
Sample Data
CREATE TABLE orders (order_id INTEGER, customer TEXT, order_date TEXT, category TEXT, amount INTEGER);
INSERT INTO orders VALUES
(1,'Aman','2026-01-05','Books',1200),(2,'Riya','2026-01-18','Electronics',15000),
(3,'Aman','2026-02-02','Electronics',8000),(4,'Karan','2026-02-14','Books',600),
(5,'Neha','2026-02-20','Clothing',2500),(6,'Riya','2026-03-03','Books',900),
(7,'Karan','2026-03-15','Electronics',22000),(8,'Aman','2026-03-28','Clothing',1800);
1. Monthly Revenue
SELECT strftime('%Y-%m', order_date) AS month,
COUNT(*) AS orders,
SUM(amount) AS revenue
FROM orders
GROUP BY month
ORDER BY month;
Explanation: strftime('%Y-%m', ...) turns a date into “year-month” in SQLite. In MySQL use DATE_FORMAT(order_date, '%Y-%m'), in PostgreSQL TO_CHAR(order_date, 'YYYY-MM') or DATE_TRUNC('month', order_date).
month | orders | revenue 2026-01 | 2 | 16200 2026-02 | 3 | 11100 2026-03 | 3 | 24700
2. Month-over-Month Growth
WITH m AS (
SELECT strftime('%Y-%m', order_date) AS month, SUM(amount) AS revenue
FROM orders GROUP BY month
)
SELECT month, revenue,
LAG(revenue) OVER (ORDER BY month) AS prev_month,
ROUND(100.0 * (revenue - LAG(revenue) OVER (ORDER BY month))
/ LAG(revenue) OVER (ORDER BY month), 1) AS growth_pct
FROM m;
Explanation: LAG brings the previous month’s revenue onto the same row so we can compute the % change. We multiply by 100.0 (not 100) to avoid integer division.
month | revenue | prev_month | growth_pct 2026-01 | 16200 | NULL | NULL 2026-02 | 11100 | 16200 | -31.5 2026-03 | 24700 | 11100 | 122.5
3. Share of Revenue by Category
SELECT category, SUM(amount) AS revenue,
ROUND(100.0 * SUM(amount) / (SELECT SUM(amount) FROM orders), 1) AS pct
FROM orders
GROUP BY category
ORDER BY revenue DESC;
category | revenue | pct Electronics | 45000 | 86.5 Clothing | 4300 | 8.3 Books | 2700 | 5.2
4. Top Customers
SELECT customer, COUNT(*) AS orders, SUM(amount) AS total,
ROUND(AVG(amount)) AS avg_order
FROM orders
GROUP BY customer
ORDER BY total DESC
LIMIT 3;
customer | orders | total | avg_order Karan | 2 | 22600 | 11300 Riya | 2 | 15900 | 7950 Aman | 3 | 11000 | 3667
Explanation: Aman orders most often, but Karan spends the most. Looking at both frequency and value is the idea behind RFM (Recency, Frequency, Monetary) segmentation.
5. SQL to pandas
import sqlite3
import pandas as pd
con = sqlite3.connect("shop.db")
df = pd.read_sql("SELECT category, SUM(amount) AS revenue FROM orders GROUP BY category", con)
df.plot(kind="bar", x="category", y="revenue", legend=False, title="Revenue by category")
Explanation: pd.read_sql runs the query and returns a DataFrame, ready for visualisation. For MySQL or PostgreSQL, pass a SQLAlchemy engine instead of the SQLite connection.
Analyst Checklist
- Check row counts and NULLs before trusting results.
- Be clear about time zones and date ranges.
- Use CTEs to break the question into steps.
- Cross-check one total against a known number.
Series
SQL series: SQL Basics · MySQL · PostgreSQL · MongoDB · Database Design · SQL for Data Analytics · Advanced SQL Queries · Python MySQL series
Interview Questions
Q: How do you calculate month-over-month growth in SQL?
Aggregate by month in a CTE, then use LAG() to get the previous month and compute (current − previous) / previous.
Q: Why 100.0 instead of 100?
To force decimal division; integer division would truncate the result.
Practice Exercises
- Find the best-selling category in each month.
- Compute each customer’s first and last order date.
- Calculate the 2-month moving average of revenue.
Summary
Analytics SQL is built from GROUP BY, date functions, CTEs and window functions like LAG. Pull the results into pandas for charts and further analysis.
Next: Advanced SQL Queries · Database Design
Machine Learning Tutorials, Courses and Certifications