Back to Tutorials
Python for AI
Beginner

SQL for Data Science: Queries, Groups and Joins

Run real SQL in your browser: step through a query in the order the database runs it, join tables four ways, and catch the join that quietly doubles your totals.

10 minInteractive: drag, click and try things as you read


Most of the world’s data lives in databases, and the way you ask a database for it is SQL. Before any model or chart, someone writes a query to pull the right rows, and a quiet mistake there flows into everything after it. SQL reads top to bottom but runs in a different order, and joins can repeat rows. Know those two things and most SQL surprises stop being surprising. Everything on this page runs on a real SQLite database inside your browser, so you can try any query you like.

Describe the result, not the steps#

A database stores data in tables: rows of records, each with the same named columns. Ours is a café: a customers table, an orders table and a reviews table, linked by ID numbers. The orders are the same twelve as in the pandas groupby explainer, plus one more.

SQL (Structured Query Language) was designed at IBM in the 1970s, and it’s declarative: you describe the table you want back and the database works out how to build it. That’s why the same query works on a laptop file and on a warehouse holding billions of rows. The database you’re using here is SQLite, the small database built into every Android phone and iPhone, compiled to run in a web page.

A typical analysis query has up to seven parts:

  • SELECT picks the columns, and can compute new ones like COUNT(*) or AVG(amount).
  • FROM names the table.
  • WHERE keeps only the rows that pass a test.
  • GROUP BY collapses rows into one per group, like pandas’ groupby.
  • HAVING keeps only the groups that pass a test.
  • ORDER BY sorts the result.
  • LIMIT keeps the first few rows.

The order it really runs in#

You write SELECT first, but the database can’t pick columns from a table it hasn’t fetched or average groups it hasn’t made. Logically, it runs the clauses in a fixed order: FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, LIMIT. Step through it below and watch the table change at each clause.

Try it
A real SQLite database running in your browser, with made-up café orders. Each step shows the real table at that point, computed by running the query up to that clause. The circled numbers give the order each line runs in.

Two things happen that people often don’t expect. At WHERE, order 10 disappears even though nobody asked to drop it. Its amount is missing, recorded as NULL, and any comparison with NULL gives “unknown” rather than true, so the row fails the test. And HAVING throws out a whole group, Sandwich, which had the highest average of all: it only had two orders left after WHERE. WHERE filters rows before grouping; HAVING filters groups after it.

Predict first

You want only the items whose average order is over £4. You write WHERE AVG(amount) > 4. What does the database do?

Try your own
The same café tables in a real SQLite database. Pick a ready-made query or write your own; anything you change stays in your browser, and Reset tables puts everything back.

The other buttons show NULL at work. COUNT(*) counts rows, 13, while COUNT(amount) counts values that aren’t NULL, 12, and AVG quietly skips the gap, just as pandas does. WHERE city <> 'London' looks as if it returns everyone outside London, but Gita, whose city is unknown, is missing: “unknown is not London” is itself unknown. If you want her, ask for her: OR city IS NULL.

Joins: matching rows across tables#

Real data is split across tables so each fact is stored once: a customer’s city sits in customers, not copied onto every order. A join puts them back together by matching a column in one table to a column in the other, here orders.customer_id to customers.id. The type of join decides what happens to rows with no match.

Predict first

There are 7 customers and 13 orders. One customer, Gita, has never ordered, and one order belongs to a customer who has since been deleted. How many rows does customers LEFT JOIN orders return?

Try it
Each line is a match between a customer and an order. Rows without a match are highlighted when the join keeps them and struck through when it drops them. The table under the drawing is the real result; yellow cells are NULLs the join filled in.

INNER JOIN (or plain JOIN) keeps only matches. LEFT JOIN keeps every row of the first table, matched or not, which is what you want for questions like “every customer and what they spent, including those who spent nothing”. RIGHT JOIN is the same from the other side, and FULL JOIN keeps everything. The unmatched rows are often the interesting ones: an order whose customer doesn’t exist is a data quality problem worth finding.

pandas does the same with merge: customers.merge(orders, left_on="id", right_on="customer_id", how="left"), where how can be "inner", "left", "right" or "outer". (concat is different: it stacks tables on top of each other instead of matching rows.)

The join that doubles your totals#

One customer can have many orders. That’s fine with one join, because each order appears once. The trouble starts when you join two “many” tables to the same customer at once.

Predict first

Amira has 3 orders, worth £13.20 in all, and has written 2 reviews. You join customers to orders and to reviews, then add up her order amounts. What do you get?

Try it
Real SQLite again. The first table is what each query returns. On “Join both tables”, the second shows Amira’s six rows before grouping, coloured by order.

This is called fan-out, and it’s one of the most common silent bugs in reporting: the query runs, the numbers look plausible, and they’re wrong for four customers out of six. The fix is to summarise each table down to one row per customer first, then join the summaries. A WITH clause (a common table expression) gives each summary a name so the query stays readable. Before you sum after a join, check that the join didn’t repeat the rows you’re summing. A quick way is to compare COUNT(*) after the join with the count in the original table.

SQL and Python together#

In data science work, SQL and pandas split the job. Let the database filter, join and group, because it can do that next to the data without sending millions of rows across the network. Then pull the much smaller result into pandas for plots, statistics and models. A few habits help:

  • Check the row count after every join. It should be what you expect: one row per order, or one per customer.
  • Ask what NULL should mean. Missing amount, unknown city, no orders: decide whether each should be dropped, kept or counted as zero (COALESCE(spent, 0)).
  • Filter early. A WHERE on a date or category keeps the work small and the query fast.
  • Never paste user input into SQL text. Pass values as parameters (? in Python’s sqlite3), so a name like O'Brien can’t break the query or worse.

In code#

Python comes with SQLite built in. The café tables, joined and grouped by the database, then handed to pandas:

import sqlite3
import pandas as pd

con = sqlite3.connect(":memory:")
con.executescript("""
CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT, city TEXT);
INSERT INTO customers VALUES (1, 'Amira', 'London'), (2, 'Ben', 'Leeds'), (3, 'Chloe', 'Manchester'),
  (4, 'Dev', 'Leeds'), (5, 'Ella', 'London'), (6, 'Femi', 'Manchester'), (7, 'Gita', NULL);
CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER, item TEXT, amount REAL);
INSERT INTO orders VALUES (1, 1, 'Coffee', 3.20), (2, 2, 'Cake', 4.50), (3, 1, 'Sandwich', 6.80),
  (4, 3, 'Coffee', 2.90), (5, 4, 'Coffee', 3.10), (6, 2, 'Coffee', 3.10), (7, 5, 'Cake', 4.20),
  (8, 3, 'Sandwich', 7.10), (9, 1, 'Coffee', 3.20), (10, 4, 'Sandwich', NULL), (11, 5, 'Coffee', 3.40),
  (12, 6, 'Cake', 4.80), (13, 9, 'Coffee', 2.80);
""")

# let the database do the filtering and grouping, then hand pandas the small result
query = """
SELECT city, COUNT(orders.id) AS orders, ROUND(SUM(amount), 2) AS spent
FROM customers
LEFT JOIN orders ON orders.customer_id = customers.id
GROUP BY city
ORDER BY spent DESC
"""
print(pd.read_sql_query(query, con))
#          city  orders  spent
# 0      London       5   20.8
# 1  Manchester       3   14.8
# 2       Leeds       4   10.7
# 3         NaN       0    NaN

The city totals match the pandas groupby explainer’s. The last row is Gita: the LEFT JOIN kept her, her city is unknown, and she has no orders, so COUNT(orders.id) gives 0 and the sum is NULL.

What to remember

  • SQL runs in the order FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, LIMIT: WHERE filters rows, HAVING filters groups.
  • NULL means unknown: comparisons with it are never true, COUNT(column) and AVG skip it, and IS NULL is how you ask for it.
  • A join returns one row per matching pair; joining two one-to-many tables at once repeats rows and inflates sums, so summarise first.

Keep going

Sign in to save your place and keep a learning streak. Free, with Google.