Open in VS Code: From your cloned
s26-06643repository, run in the terminal:code sse/optional/databases/databases.ipynb
Databases for Research#
At some point, flat files (CSV, JSON) stop scaling. When you have thousands of experiments, need to query data by multiple criteria, or share data across a team, a database is the right tool. This lecture covers when to use databases, SQL fundamentals, and how to work with databases from Python.
Section 1: When Files vs. Databases#
Files Are Fine When:#
Your data fits in memory
You read the entire dataset each time
Only one person/process accesses the data
The schema rarely changes
Databases Are Better When:#
You need to query specific subsets of data efficiently
Multiple users or processes access the data concurrently
Data integrity constraints matter (e.g., no duplicate experiment IDs)
You need to join related data (experiments + measurements + samples)
Your dataset grows continuously
SQLite: The Best Starting Point#
SQLite is a serverless database stored in a single file. It is:
Built into Python (no installation needed)
Perfect for single-user, local workflows
Used by many applications (Firefox, iOS, Android)
Capable of handling datasets up to ~1 TB
For multi-user or server deployments, consider PostgreSQL.
Section 2: SQL Basics#
SQL (Structured Query Language) is the standard language for relational databases. Here are the essentials.
Creating Tables#
CREATE TABLE experiments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
date TEXT NOT NULL,
temperature REAL,
pressure REAL,
catalyst TEXT,
notes TEXT
);
CREATE TABLE measurements (
id INTEGER PRIMARY KEY AUTOINCREMENT,
experiment_id INTEGER NOT NULL,
time_s REAL NOT NULL,
concentration REAL NOT NULL,
FOREIGN KEY (experiment_id) REFERENCES experiments(id)
);
Inserting Data#
INSERT INTO experiments (name, date, temperature, pressure, catalyst)
VALUES ('run-001', '2026-03-01', 350.0, 1.0, 'Pt/Al2O3');
INSERT INTO measurements (experiment_id, time_s, concentration)
VALUES (1, 0.0, 1.0), (1, 10.0, 0.82), (1, 20.0, 0.67);
Querying Data#
-- All experiments with Pt catalyst above 300 K
SELECT * FROM experiments
WHERE catalyst LIKE 'Pt%' AND temperature > 300;
-- Average concentration by experiment
SELECT e.name, AVG(m.concentration) as avg_conc
FROM experiments e
JOIN measurements m ON e.id = m.experiment_id
GROUP BY e.name;
Section 3: Python + SQLite#
import sqlite3
# Connect (creates the file if it doesn't exist)
conn = sqlite3.connect(":memory:") # Use a filename for persistent storage
cursor = conn.cursor()
# Create tables
cursor.execute("""
CREATE TABLE experiments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
temperature REAL,
catalyst TEXT
)
""")
cursor.execute("""
CREATE TABLE measurements (
id INTEGER PRIMARY KEY AUTOINCREMENT,
experiment_id INTEGER NOT NULL,
time_s REAL NOT NULL,
concentration REAL NOT NULL,
FOREIGN KEY (experiment_id) REFERENCES experiments(id)
)
""")
# Insert data — always use parameterized queries!
experiments = [
("run-001", 350.0, "Pt/Al2O3"),
("run-002", 400.0, "Pt/Al2O3"),
("run-003", 350.0, "Pd/C"),
]
cursor.executemany(
"INSERT INTO experiments (name, temperature, catalyst) VALUES (?, ?, ?)",
experiments
)
measurements = [
(1, 0.0, 1.0), (1, 10.0, 0.82), (1, 20.0, 0.67),
(2, 0.0, 1.0), (2, 10.0, 0.65), (2, 20.0, 0.42),
(3, 0.0, 1.0), (3, 10.0, 0.91), (3, 20.0, 0.83),
]
cursor.executemany(
"INSERT INTO measurements (experiment_id, time_s, concentration) VALUES (?, ?, ?)",
measurements
)
conn.commit()
print("Database created with", cursor.execute("SELECT COUNT(*) FROM experiments").fetchone()[0], "experiments")
# Query: which experiments used Pt catalyst?
cursor.execute("SELECT name, temperature FROM experiments WHERE catalyst LIKE 'Pt%'")
for row in cursor.fetchall():
print(f" {row[0]}: {row[1]} K")
# Query with JOIN: get measurements for a specific experiment
cursor.execute("""
SELECT e.name, e.temperature, m.time_s, m.concentration
FROM experiments e
JOIN measurements m ON e.id = m.experiment_id
WHERE e.name = 'run-001'
ORDER BY m.time_s
""")
print(f"{'Name':<10} {'Temp (K)':<10} {'Time (s)':<10} {'Conc':<10}")
print("-" * 40)
for row in cursor.fetchall():
print(f"{row[0]:<10} {row[1]:<10.1f} {row[2]:<10.1f} {row[3]:<10.3f}")
# Pandas integration — load query results directly into a DataFrame
import pandas as pd
df = pd.read_sql_query("""
SELECT e.name, e.catalyst, e.temperature, m.time_s, m.concentration
FROM experiments e
JOIN measurements m ON e.id = m.experiment_id
ORDER BY e.name, m.time_s
""", conn)
df
Section 4: SQLAlchemy (ORM Approach)#
For larger projects, an Object-Relational Mapper (ORM) like SQLAlchemy lets you work with database rows as Python objects:
from sqlalchemy import create_engine, Column, Integer, Float, String, ForeignKey
from sqlalchemy.orm import DeclarativeBase, relationship, Session
class Base(DeclarativeBase):
pass
class Experiment(Base):
__tablename__ = "experiments"
id = Column(Integer, primary_key=True)
name = Column(String, nullable=False)
temperature = Column(Float)
catalyst = Column(String)
measurements = relationship("Measurement", back_populates="experiment")
class Measurement(Base):
__tablename__ = "measurements"
id = Column(Integer, primary_key=True)
experiment_id = Column(Integer, ForeignKey("experiments.id"))
time_s = Column(Float, nullable=False)
concentration = Column(Float, nullable=False)
experiment = relationship("Experiment", back_populates="measurements")
engine = create_engine("sqlite:///research.db")
Base.metadata.create_all(engine)
with Session(engine) as session:
exp = Experiment(name="run-004", temperature=375.0, catalyst="Pt/Al2O3")
exp.measurements.append(Measurement(time_s=0.0, concentration=1.0))
session.add(exp)
session.commit()
SQLAlchemy is more verbose upfront but pays off in larger projects where you need validation, relationships, and migrations.
Exercise: Store and Query Experimental Results#
Build a small database for managing experimental results.
Create a SQLite database with two tables:
experiments: id, name, date, temperature, pressure, catalystresults: id, experiment_id (foreign key), time_s, conversion, selectivity
Insert at least 5 experiments with 10+ measurements each (you can generate synthetic data)
Write queries to answer:
Which catalyst gives the highest average conversion?
At what temperature is selectivity maximized?
Plot conversion vs. time for all experiments with a specific catalyst
Load the results into a pandas DataFrame and create a summary plot
Bonus: Wrap your database operations in a Python class with methods like add_experiment(), add_result(), and query_by_catalyst().
conn.close()
Summary#
Concept |
Tool/Approach |
|---|---|
Simple local database |
SQLite (built into Python) |
Multi-user database |
PostgreSQL |
Python + SQL |
|
ORM |
SQLAlchemy for object-oriented database access |
Pandas integration |
|
Key SQL operations |
CREATE, INSERT, SELECT, JOIN, GROUP BY |
Tips and Tricks#
Prompt: “Write a SQL query that [description]”: AI is excellent at SQL — describe what you want in plain English and it generates the query.
Always use parameterized queries: Never use f-strings or
.format()in SQL — AI sometimes generates unsafe queries, so always check.Use
:memory:for experiments:sqlite3.connect(":memory:")gives you a throwaway database for testing — no cleanup needed.Prompt: “Convert this pandas DataFrame operation to a SQL query”: If you know pandas, AI can translate your logic to SQL.
Load query results into pandas immediately:
pd.read_sql_query()gives you a DataFrame — from there, use all the pandas tools you already know.Design your schema before writing code: Ask the agent: “Design a database schema for [domain] with tables for [entities].”
Prompt: “Add a foreign key constraint and explain what it enforces”: AI explains relational concepts well while generating correct SQL.
Back up before modifying production data:
cp database.db database_backup.db— one command that can save hours of recovery.
Foundational Concepts to Commit to Memory#
SQLite is built into Python —
import sqlite3requires no installation, and the database is a single file. It handles datasets up to ~1 TB.Always use parameterized queries —
cursor.execute("SELECT * FROM t WHERE x = ?", (value,))prevents SQL injection. Never use f-strings in SQL.PRIMARY KEY AUTOINCREMENT gives each row a unique, auto-assigned integer ID — this is the standard way to identify rows.
FOREIGN KEY relationships connect tables —
experiment_idin a measurements table referencesidin the experiments table.JOIN combines related tables in a single query —
JOIN measurements m ON e.id = m.experiment_idlinks experiments to their measurements.pd.read_sql_query()loads SQL results directly into a pandas DataFrame, bridging the gap between databases and your analysis code.SQLAlchemy (ORM) lets you work with database rows as Python objects — more verbose upfront but valuable for larger projects with complex relationships.
Files vs. databases: use files when you read everything at once; use databases when you need to query subsets, enforce constraints, or handle concurrent access.
Knowing vs. Doing: Reflection#
Databases sit in an interesting spot on the “knowing vs. doing” spectrum. SQL is a language most scientists never formally learn, but it is remarkably useful once you know even the basics. The core operations — CREATE, INSERT, SELECT, JOIN, GROUP BY — cover probably 90% of what you will ever need. And AI agents are excellent at writing SQL queries, especially if you can describe your schema and what you want in plain English. You do not need to be a database administrator. You need to know enough to describe your data model and verify that the query returns what you expect.
Here is where the tension gets real: you could spend weeks learning advanced SQL (window functions, common table expressions, indexing strategies, query optimization) and still not build anything useful. Or you could learn the basics in this lecture, let an AI agent help you write the queries, and have a working research database by the end of the day. The second path gets you a product — something your lab can actually use. The first path makes you an expert who has not shipped anything yet.
The more you know about databases, the faster you can spot when an AI-generated query is wrong — maybe it is doing a cross join when you wanted an inner join, or it forgot a WHERE clause that filters out bad data. That verification step is where your knowledge pays off. But you build that intuition by using databases, not by studying them in isolation. Start with SQLite and a real dataset from your research. The learning and the doing reinforce each other.
Additional Resources#
Python sqlite3 Module — official documentation for Python’s built-in SQLite interface
SQLAlchemy — the Python SQL toolkit and Object-Relational Mapper