Module 8: SQL for Data Science
Module 8: SQL for Data Science
Introduction to Data Science — Week 8
Querying relational databases — the language of structured data
Module Overview
Most of the world's business data lives in relational databases. SQL (Structured Query Language)
is the standard language for querying those databases. This module introduces students to SQL:
what relational databases are, how to write basic queries, how to filter and aggregate data, and
how to combine multiple tables with joins. Students will also learn how to run SQL from Python
so that SQL and pandas can be combined in real workflows.
Learning Objectives
By the end of this module, students will be able to:
- Explain what a relational database is and how tables relate to one another.
- Write SELECT queries with WHERE, ORDER BY, LIMIT, and DISTINCT.
- Aggregate data with GROUP BY, HAVING, COUNT, SUM, AVG, MIN, and MAX.
- Combine tables with INNER, LEFT, RIGHT, and FULL OUTER joins.
- Use subqueries and common table expressions (CTEs) for complex queries.
- Execute SQL queries from Python and integrate results with pandas.
Lesson 1: What Is a Relational Database?
A relational database stores data in tables. Each
table has rows (records) and columns (fields). Tables can be
linked to each other through shared keys.
Key Concepts
- Table: A collection of related records, like a spreadsheet.
- Primary key: A column (or set of columns) that uniquely identifies each row.
- Foreign key: A column that references the primary key of another table.
- Schema: The structure of the database — its tables, columns, and relationships.
Example: Customers and Orders
| customers |
orders |
customer_id (PK)
name
email
|
order_id (PK)
customer_id (FK)
amount
order_date
|
The orders.customer_id column refers to customers.customer_id. That's how tables are linked.
📚 Think of it like a library: Each table is like a card catalog. The primary
key is the unique call number for each book. The foreign key is a reference from one card to
another — like "see also this author." SQL is how you search across all those cards at once.
💡 Key Idea: Relational databases are powerful because they enforce structure
and can join tables together. This is why SQL remains a foundational skill for data science.
Lesson 2: Basic SELECT Queries
The most basic SQL query selects data from a table. The SELECT statement tells
the database what to return; FROM tells it where to look.
Select All Columns
SELECT * FROM customers;
Select Specific Columns
SELECT name, email FROM customers;
Filter with WHERE
SELECT name, email
FROM customers
WHERE name = 'Alex';
Comparison Operators
| Operator |
Meaning |
= | Equal to |
<> or != | Not equal to |
>, >= | Greater than, greater than or equal |
<, <= | Less than, less than or equal |
BETWEEN | Within a range |
IN | Matches any value in a list |
LIKE | Matches a pattern (with % wildcards) |
IS NULL | Matches missing values |
Ordering and Limiting
SELECT name, email
FROM customers
ORDER BY name ASC
LIMIT 10;
Distinct Values
SELECT DISTINCT country FROM customers;
🔍 Think of it like a search engine: A SELECT query is like typing a search
into Google. You specify what you want (SELECT), where to search (FROM), and any filters
(WHERE) — and the database returns the matching rows.
💡 Key Idea: SQL is declarative — you describe what you want,
not how to compute it. The database engine figures out the "how."
Lesson 3: Aggregating Data
Aggregation collapses many rows into summary statistics. This is
where SQL really shines.
Aggregate Functions
| Function |
What It Does |
COUNT() | Counts rows (or non-null values in a column) |
SUM() | Adds up values |
AVG() | Average (mean) |
MIN() | Smallest value |
MAX() | Largest value |
Basic Aggregation
SELECT COUNT(*) AS total_orders FROM orders;
SELECT AVG(amount) AS avg_order FROM orders;
SELECT SUM(amount) AS total_revenue FROM orders;
Grouping with GROUP BY
SELECT customer_id, COUNT(*) AS order_count, SUM(amount) AS total_spent
FROM orders
GROUP BY customer_id
ORDER BY total_spent DESC;
customer_id | order_count | total_spent
------------+-------------+------------
1023 | 5 | 428.50
1007 | 3 | 287.20
1051 | 4 | 241.75
Filtering Groups with HAVING
WHERE filters rows; HAVING filters groups.
SELECT customer_id, SUM(amount) AS total_spent
FROM orders
GROUP BY customer_id
HAVING SUM(amount) > 300
ORDER BY total_spent DESC;
🧩 Think of it like sorting laundry: GROUP BY is like sorting
clothes into piles (by color or type). The aggregate functions (COUNT, SUM, AVG) are like
counting or measuring each pile. HAVING is like saying "show me only piles with
more than 5 items."
⚠️ Watch Out! WHERE runs before grouping;
HAVING runs after. If you want to filter on an aggregate (like
SUM(amount) > 300), you must use HAVING — not WHERE.
Lesson 4: Joins — Combining Tables
Most real questions require data from more than one table. Joins
combine tables based on a shared key.
Types of Joins
| Join Type |
What It Returns |
| INNER JOIN |
Only rows with matches in both tables |
| LEFT JOIN |
All rows from the left table, plus matches from the right (NULLs where no match) |
| RIGHT JOIN |
All rows from the right table, plus matches from the left |
| FULL OUTER JOIN |
All rows from both tables, with NULLs where there's no match |
Example: Customers with Their Orders
SELECT c.name, o.order_id, o.amount, o.order_date
FROM customers c
INNER JOIN orders o ON c.customer_id = o.customer_id
ORDER BY o.order_date DESC;
Left Join: All Customers, Even Those Without Orders
SELECT c.name, COUNT(o.order_id) AS order_count
FROM customers c
LEFT JOIN orders o ON c.customer_id = o.customer_id
GROUP BY c.name
ORDER BY order_count DESC;
🧩 Think of it like two puzzle pieces: You join two tables on the key that
matches. An INNER JOIN keeps only the pieces that fit together.
A LEFT JOIN keeps all the left pieces, even the ones without a matching right piece.
💡 Key Idea: If you're not sure which join to use, start with
INNER JOIN. If you're worried about losing rows from one table, use
LEFT JOIN.
⚠️ Watch Out! Always check the row count before and after a join. A one-to-many
join will multiply your rows — this can silently inflate aggregates and cause wrong conclusions.
Lesson 5: Subqueries and CTEs
Subqueries are queries nested inside other queries.
Common Table Expressions (CTEs) are named subqueries that make
complex queries easier to read.
Subquery Example
SELECT name
FROM customers
WHERE customer_id IN (
SELECT customer_id
FROM orders
WHERE amount > 500
);
CTE Example
WITH big_spenders AS (
SELECT customer_id, SUM(amount) AS total_spent
FROM orders
GROUP BY customer_id
HAVING SUM(amount) > 500
)
SELECT c.name, b.total_spent
FROM customers c
INNER JOIN big_spenders b ON c.customer_id = b.customer_id
ORDER BY b.total_spent DESC;
🪆 Think of it like nested dolls: A subquery is a query inside a query — like
a smaller doll inside a bigger one. CTEs are a way to give each doll a name, so the whole thing
is easier to understand.
💡 Key Idea: If a query is getting complicated, split it into CTEs. This
makes it readable and easier to debug — step by step.
Lesson 6: Running SQL from Python
In real data science work, SQL and Python are often used together. You can query a database
from Python and load the results directly into a pandas DataFrame.
Example with SQLite
import sqlite3
import pandas as pd
# Connect to a SQLite database
conn = sqlite3.connect("sales.db")
# Run a query and load results into a DataFrame
query = """
SELECT region, SUM(amount) AS total_sales
FROM orders
GROUP BY region
ORDER BY total_sales DESC
"""
df = pd.read_sql_query(query, conn)
# Always close the connection when done
conn.close()
print(df)
region total_sales
0 North 124500.50
1 West 118300.25
2 East 105200.00
3 South 98900.75
When to Use SQL vs. pandas
| Task |
Best Tool |
| Data stored in a database |
SQL |
| Simple filtering and aggregation |
Either — SQL often faster on large data |
| Complex reshaping, joins, or pandas-specific operations |
pandas |
| Machine learning workflows |
Python (pandas, scikit-learn) |
| Data already in memory (DataFrame) |
pandas |
🔧 Think of it like tools in a toolbox: SQL is the hammer — great for banging
in a nail (filtering and aggregating data in a database). pandas is the Swiss Army knife —
versatile for in-memory data manipulation. Good data scientists use both, choosing the right
tool for the job.
💡 Key Idea: Do the heavy lifting in SQL (filter, aggregate) and then bring
the results into pandas for further analysis. This is far more efficient than pulling entire
tables into Python and filtering there.
Lesson 7: SQL Best Practices
Query Style
- Use uppercase for SQL keywords (
SELECT, FROM, WHERE).
- Put each clause on a new line for readability.
- Use aliases for tables (
customers c) and computed columns (AS total_sales).
- Comment your queries — especially if they're complex or will be reused.
Performance
- Use
LIMIT while exploring, so you don't pull millions of rows.
- Filter early —
WHERE clauses reduce the data the database has to process.
- Avoid
SELECT * in production queries — specify only the columns you need.
- Use indexes on columns you filter or join on (database-specific, but worth knowing).
Safety
- Never use string formatting to insert values into SQL — use parameterized queries to avoid SQL injection.
- Always
LIMIT UPDATE and DELETE statements — or test with SELECT first.
- Back up before running anything destructive on real data.
⚠️ SQL Injection: If you build queries by concatenating user input, attackers
can execute arbitrary SQL. Always use parameterized queries:
# ❌ DANGEROUS
query = f"SELECT * FROM users WHERE name = '{user_input}'"
# ✅ SAFE
cursor.execute("SELECT * FROM users WHERE name = ?", (user_input,))
💡 Key Idea: Good SQL is readable, efficient, and safe. Treat queries as code
— because that's exactly what they are.
Hands-On Lab: Query a Database and Integrate with pandas
Goal: Practice SQL queries and integrate them with pandas.
Instructions
- Download a small sample database (e.g., SQLite's "chinook" sample database, or the Titanic dataset converted to SQLite).
- Open it in SQLite (or use Python with
sqlite3).
- Write and run SQL queries to answer the following:
- List all rows from one table — but limit to 10.
- Filter rows by a numeric or text condition.
- Sort the results by a specific column.
- Aggregate: compute the count, average, or sum grouped by a category.
- Use
HAVING to filter aggregated groups.
- Join two tables together on a shared key.
- Use a subquery or CTE to answer a more complex question.
- Load the result of one query into a pandas DataFrame using
pd.read_sql_query.
- Visualize the result with matplotlib or seaborn (e.g., a bar chart of totals by category).
- Write a short summary (1 page) of what you found.
Submission
Your notebook (with SQL queries, pandas code, and at least one chart) + a 1-page summary.
Assessment for Module 8
- Quiz (10 questions): Covers SELECT, WHERE, GROUP BY, HAVING, joins, subqueries, CTEs, and SQL best practices.
- Lab: Graded on query correctness, efficiency, and clarity of the summary.
- Participation: Contribution to the group activity and discussion prompts.
Key Terms
- Relational database — a database organized into related tables.
- Table — a collection of rows and columns.
- Primary key — a column that uniquely identifies each row.
- Foreign key — a column that references another table's primary key.
- SELECT — the SQL clause for choosing columns.
- WHERE — filters individual rows.
- GROUP BY — groups rows for aggregation.
- HAVING — filters groups after aggregation.
- JOIN — combines rows from two or more tables.
- INNER JOIN — only rows with matches in both tables.
- LEFT JOIN — all rows from the left table.
- Subquery — a query nested inside another query.
- CTE — a named subquery (using
WITH).
- SQL injection — a security vulnerability from unsafe query construction.
Discussion Prompts
- Why is SQL still relevant after decades, even with powerful libraries like pandas?
- What's the difference between
WHERE and HAVING?
- When would you choose a LEFT JOIN over an INNER JOIN?
- Why might a query return different row counts before and after a join?
- What's the risk of building SQL queries with string formatting? How can you avoid it?
- If you were analyzing a billion-row database, would you use SQL, pandas, or both? Why?
Further Reading
- SQL Cookbook by Anthony Molinaro and Robert de Graaf
- Learning SQL by Alan Beaulieu
- Mode Analytics SQL Tutorial (free online)
- Kaggle Learn: "Intro to SQL" and "Advanced SQL" micro-courses
- SQLite official documentation — excellent for learning the standard
- pandas documentation — "Comparison with SQL"
💡 Instructor Note: SQL is a skill best learned by doing. Provide a
small sample database (like chinook or a synthetic "customers and orders" schema) and let
students write queries against it. Emphasize that filtering early (in SQL) is
more efficient than filtering late (in pandas) — students often pull entire
tables into memory unnecessarily. Also stress the importance of parameterized queries
for safety, even if students aren't building web apps yet.