Single logo
  • Courses
  • Blog
  • About
Join for freeJoin free
Learning pathShip Your First Model: From Notebook to a FastAPI Service
  1. 1
    Saving and Loading Models with joblib: One Pipeline, One File
  2. 2
    FastAPI Hello World: Routes, uvicorn and the Free Swagger Page
  3. 3
    Deploy a Machine Learning Model with FastAPI: POST /predict for a Saved Model
  4. 4
    Project: Car Price Predictor End to End, from CSV to a FastAPI Price API
  5. 5
    Python Virtual Environments: One Project, One Toolbox
  6. 6
    Git and GitHub Fundamentals: Commits, Branches, Push and Pull
  7. 7
    Testing a FastAPI App with pytest: Three Small Tests
  8. 8
    Config and Logging Instead of Hard-Coded Values in ML Training
  9. 9
    SQL Essentials for Python: SELECT, WHERE, JOIN and GROUP BY
  1. Blog
  2. /
  3. Machine Learning
  4. /
  5. MLOps and Production ML

Learning path: Ship Your First Model: From Notebook to a FastAPI Service · Step 9 of 9

SQL Essentials for Python: SELECT, WHERE, JOIN and GROUP BY

The SQL a Python developer needs, on a tiny shop with four customers and eight orders: CREATE TABLE, INSERT with placeholders, SELECT with WHERE, JOIN, GROUP BY, pandas.read_sql, and why values never go in f-strings.

Chaand Sheikh

·27 November 2026Engineering Basics

What you will learn

  • Create tables and insert rows with Python's built-in sqlite3 module
  • Ask questions with SELECT, WHERE, ORDER BY, JOIN and GROUP BY
  • Run a query into a DataFrame with pandas.read_sql
  • Pass values through ? placeholders instead of f-strings

Before you start

  • Basic Python
  • Filtering, merging and grouping in pandas

You already know how to filter, merge and group data in pandas. SQL asks the same questions, written a different way, and it runs inside the database where the data lives. Four words come up again and again: SELECT, WHERE, JOIN and GROUP BY.

A tiny online shop

We run a small shop and keep two tables. customers has four people, each with an id, a name and a city. orders has eight orders, each with an id, the id of the customer who placed it, the product and the amount.

idnamecity
1Asha RaoPune
2Ben CarterLeeds
3Chitra NairPune
4Dev PatelLeeds
idcustomer_idproductamount
11Keyboard80
21Mouse25
32Monitor220
43Webcam60
53Cable10
63Headset90
71USB hub35
82Mouse25

The question of the day: how much has each customer spent, biggest first? In pandas that's a merge and a groupby. By the end, you'll write it in SQL.

Where does the data live?

Think of a notebook kept in your house: one file on your own laptop. That's SQLite, and it's built into Python, so there's nothing to install. Now think of the same notebook in a bank vault, where the whole team can open it with the right key. That's Postgres, a database on a server.

The writing inside the notebook is the same in both places. SQL is one language for both. Here we use the notebook in the house.

Create the tables

import pathlib
import sqlite3

DB = pathlib.Path("shop.db")
DB.unlink(missing_ok=True)  # start fresh every time

connection = sqlite3.connect(DB)
connection.execute("""
    CREATE TABLE customers (
        id   INTEGER PRIMARY KEY,
        name TEXT NOT NULL,
        city TEXT NOT NULL
    )
""")
connection.execute("""
    CREATE TABLE orders (
        id          INTEGER PRIMARY KEY,
        customer_id INTEGER NOT NULL REFERENCES customers(id),
        product     TEXT NOT NULL,
        amount      INTEGER NOT NULL
    )
""")
connection.commit()

tables = connection.execute(
    "SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name"
).fetchall()
print("Tables in shop.db:", [name for (name,) in tables])
connection.close()
Tables in shop.db: ['customers', 'orders']
  • sqlite3.connect opens the file shop.db. Just above it we delete any old file, so every run starts fresh.
  • PRIMARY KEY means every customer has one unique id.
  • REFERENCES customers(id) is the link between the tables: every order points to the customer who placed it.
  • connection.commit() saves the changes to the file.

Insert the rows

import sqlite3

customers = [
    (1, "Asha Rao", "Pune"),
    (2, "Ben Carter", "Leeds"),
    (3, "Chitra Nair", "Pune"),
    (4, "Dev Patel", "Leeds"),
]
orders = [
    (1, 1, "Keyboard", 80),
    (2, 1, "Mouse", 25),
    (3, 2, "Monitor", 220),
    (4, 3, "Webcam", 60),
    (5, 3, "Cable", 10),
    (6, 3, "Headset", 90),
    (7, 1, "USB hub", 35),
    (8, 2, "Mouse", 25),
]

connection = sqlite3.connect("shop.db")
connection.executemany("INSERT INTO customers VALUES (?, ?, ?)", customers)
connection.executemany("INSERT INTO orders VALUES (?, ?, ?, ?)", orders)
connection.commit()

for table in ("customers", "orders"):
    count = connection.execute(f"SELECT COUNT(*) FROM {table}").fetchone()[0]
    print(f"{table}: {count} rows")
connection.close()
customers: 4 rows
orders: 8 rows

executemany inserts many rows in one call. Each ? is a placeholder that gets filled with one value from the tuple. Remember those question marks; we come back to them at the end. (The f-string in the counting loop only fills in our own table names, never anything a user typed.)

SELECT with WHERE and ORDER BY

Which orders are bigger than 50, biggest first? SQL reads almost like English:

import sqlite3

connection = sqlite3.connect("shop.db")

query = """
    SELECT id, product, amount
    FROM orders
    WHERE amount > 50
    ORDER BY amount DESC
"""
for row in connection.execute(query):
    print(row)
connection.close()
(3, 'Monitor', 220)
(6, 'Headset', 90)
(1, 'Keyboard', 80)
(4, 'Webcam', 60)

WHERE keeps only the rows that match: the Keyboard, Monitor, Webcam and Headset. The other four are left out. ORDER BY amount DESC sorts them, and DESC means biggest first. In pandas, this is a filter and then sort_values.

JOIN the two tables

Those rows show only a customer id, but a person wants to see a name. So we join. The script opens and closes the connection exactly as before; only the query changes:

query = """
    SELECT orders.id, customers.name, orders.product, orders.amount
    FROM orders
    JOIN customers ON orders.customer_id = customers.id
    ORDER BY orders.id
"""
for row in connection.execute(query):
    print(row)
(1, 'Asha Rao', 'Keyboard', 80)
(2, 'Asha Rao', 'Mouse', 25)
(3, 'Ben Carter', 'Monitor', 220)
(4, 'Chitra Nair', 'Webcam', 60)
(5, 'Chitra Nair', 'Cable', 10)
(6, 'Chitra Nair', 'Headset', 90)
(7, 'Asha Rao', 'USB hub', 35)
(8, 'Ben Carter', 'Mouse', 25)

The rule sits in the ON part: orders.customer_id = customers.id. Order 1 has customer id 1, and customer 1 is Asha Rao. Eight orders, eight rows, each with a name.

Notice that Dev Patel is not in the result. He hasn't placed any order, so there's nothing to match. In pandas, this is a merge.

GROUP BY: the question of the day

How much has each customer spent? Take the join and add three things:

query = """
    SELECT customers.name, SUM(orders.amount) AS total
    FROM orders
    JOIN customers ON orders.customer_id = customers.id
    GROUP BY customers.name
    ORDER BY total DESC
"""
for name, total in connection.execute(query):
    print(f"{name}: {total}")
Ben Carter: 245
Chitra Nair: 160
Asha Rao: 140
  • GROUP BY customers.name puts all the orders of one customer into one group.
  • SUM(orders.amount) AS total adds up each group.
  • ORDER BY total DESC puts the biggest first.
GROUP BY customer, then SUM Ben Carter Monitor 220 + Mouse 25 Chitra Nair Webcam 60 + Cable 10 + Headset 90 Asha Rao Keyboard 80 + Mouse 25 + USB hub 35 Dev Patel: no orders, no match, not in the result SUM 245 160 140
GROUP BY makes one group per customer, SUM adds each group, and ORDER BY total DESC puts Ben first. Dev Patel has no orders, so the join leaves him out.

Ben has two orders, 220 plus 25, which makes 245. That's our answer. In pandas, this is groupby and sum.

SQL and pandas together

You don't have to choose. pd.read_sql runs a SQL query and gives you back a DataFrame:

import sqlite3

import pandas as pd

connection = sqlite3.connect("shop.db")

query = """
    SELECT customers.name, SUM(orders.amount) AS total
    FROM orders
    JOIN customers ON orders.customer_id = customers.id
    GROUP BY customers.name
    ORDER BY total DESC
"""
from_sql = pd.read_sql(query, connection)
print("SQL does the work:")
print(from_sql.to_string(index=False))

joined = pd.read_sql(
    "SELECT customers.name, orders.amount FROM orders "
    "JOIN customers ON orders.customer_id = customers.id",
    connection,
)
from_pandas = (
    joined.groupby("name", as_index=False)["amount"].sum()
    .rename(columns={"amount": "total"})
    .sort_values("total", ascending=False)
)
print("pandas does the work:")
print(from_pandas.to_string(index=False))
connection.close()
SQL does the work:
       name  total
 Ben Carter    245
Chitra Nair    160
   Asha Rao    140
pandas does the work:
       name  total
 Ben Carter    245
Chitra Nair    160
   Asha Rao    140

Same three rows, same totals. The difference is where the work happens. SQL runs inside the database; pandas runs inside your program. When the data is big, let the database filter and group, and bring only the small answer into pandas.

Values go into placeholders, not f-strings

Suppose a user types this into a search box: x' OR '1'='1. If we build the query with an f-string, the typed text is pasted straight into the SQL.

import sqlite3

name = "x' OR '1'='1"  # what a careless or malicious user might type

# Unsafe: the value is pasted into the SQL text. We only PRINT it, never run it.
unsafe = f"SELECT * FROM customers WHERE name = '{name}'"
print("f-string query text:")
print(unsafe)

# Safe: the ? placeholder keeps the value as data, never as SQL.
connection = sqlite3.connect("shop.db")
rows = connection.execute("SELECT * FROM customers WHERE name = ?", (name,)).fetchall()
print("placeholder query rows:", rows)
connection.close()
f-string query text:
SELECT * FROM customers WHERE name = 'x' OR '1'='1'
placeholder query rows: []

The quote inside the text closes our value early, and the rest becomes part of the SQL itself. The query now says name = 'x' OR '1'='1'. That's always true, so it would match every customer. We only print it; we never run it.

The placeholder version gives an empty list, because no customer is called x' OR '1'='1. With a ?, the value stays data and is never read as SQL.

The rule: any value that comes from outside your code goes into a placeholder, never into an f-string.

Moving to the bank vault

What changes when you move from SQLite to Postgres? Very little. With SQLite you connect to a file. With Postgres you use a package called psycopg, and the connect line takes a connection string with the user, the password, the server address and the database name. This line is not run here, because it needs a Postgres server; the password is a placeholder:

import psycopg

connection = psycopg.connect(
    "postgresql://shop_user:[email protected]:5432/shop"
)

Everything after that line stays the same: SELECT, WHERE, JOIN and GROUP BY all work as they are. One small difference: Postgres writes its placeholder as %s instead of ?. And just like an API key, keep the real password out of your code and your config (see config and logging).

Common mistakes

  • Forgetting commit(). Without it, your inserts never reach the file.
  • Expecting every customer after a JOIN. A plain JOIN keeps only rows that match, so Dev Patel disappears.
  • Pulling everything into pandas first. Filter and group in SQL, then read the small answer.
  • Building queries with f-strings from user input. Use ? placeholders (%s in Postgres).

Recap

SQLWhat it doespandas idea
WHEREPicks rowsBoolean filter
ORDER BY ... DESCSorts, biggest firstsort_values(ascending=False)
JOIN ... ONCombines tables on a keymerge
GROUP BY + SUMOne summary row per groupgroupby(...).sum()
?Keeps a value as data

With a few million orders instead of eight, the same few lines still work.

Try it yourself:

  1. Add a products table and link the orders to it.
  2. Find who bought the most items, using COUNT instead of SUM.
  3. Find the average order per city, using AVG and GROUP BY customers.city.

The scripts for this lesson are in the StudyEasy AI Community, free to join.

Built this? Share your solution in the StudyEasy AI Community.

Join free on Skool →
← Previous
Config and Logging Instead of Hard-Coded Values in ML Training
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool
Go deeper with a course

Machine Learning Engineer: From First Model to ML Engineer

Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)

Related articles
Python Virtual Environments: One Project, One Toolbox

Why every Python project gets its own virtual environment: two projects that need different versions of requests, python -m venv .venv, activation, pip install and the PyCharm setting that activates it for you.

Git and GitHub Fundamentals: Commits, Branches, Push and Pull

The Git you use every day, on a tiny hello-ml project: commits as save points, the staging area, a branch merged with a fast-forward, then push, clone, pull and pull requests with a teammate.

Testing a FastAPI App with pytest: Three Small Tests

A tiny FastAPI app with a Hello World route and a name route that refuses numbers, three pytest tests that check it, and what happens when the validation is deleted by mistake.

Config and Logging Instead of Hard-Coded Values in ML Training

Take the hard-coded values out of a car price training script: one config.toml read with tomllib, logging with levels and a run id on every line, and secrets read from the environment. Same RMSE, 2195, before and after.

On this page
  • A tiny online shop
  • Where does the data live?
  • Create the tables
  • Insert the rows
  • SELECT with WHERE and ORDER BY
  • JOIN the two tables
  • GROUP BY: the question of the day
  • SQL and pandas together
  • Values go into placeholders, not f-strings
  • Moving to the bank vault
  • Common mistakes
  • Recap
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool
Go deeper with a course

Machine Learning Engineer: From First Model to ML Engineer

Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.