SQL Databases with SQLAlchemy
Part of the Python Roadmap
In short
Writing SQL strings by hand works for a script, but a real app needs dozens of queries that are safe, reusable and easy to change. SQLAlchemy lets you treat rows as Python objects while still giving you full SQL power.
SQLAlchemy is Python's most widely used database toolkit. Its ORM maps classes to tables so you can query and save rows as Python objects, and Alembic handles schema migrations.

Think of it like this
A personal translator
You speak Python, the database speaks SQL. SQLAlchemy is the translator standing between you. You say "save this Student object" and it says INSERT INTO students. You ask "students with marks above 90" and it writes the SELECT, fills in the values safely and hands back Python objects.
Watch it happen
Saving and reading with the ORM
1/4You create Student(name="Diya", marks=93). It is just a Python object so far.
The big ideas
What you need to know
Classes are tables
In SQLAlchemy 2.0, a class with __tablename__ and Mapped[...] attributes describes a table and its columns.
Engine and Session
The engine knows how to connect, using a URL like sqlite:///college.db. A Session is one unit of work: add, query, commit.
select() builds queries
select(Student).where(Student.marks > 90) builds SQL in Python. session.scalars() runs it and returns objects.
Alembic for changes
create_all() only makes missing tables. For changes to existing tables, Alembic writes and runs migration scripts.
See it in code
Walk through the code
1from sqlalchemy import String, create_engine, select2from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column3 4class Base(DeclarativeBase):5 pass6 7class Student(Base):8 __tablename__ = "students"9 id: Mapped[int] = mapped_column(primary_key=True)10 name: Mapped[str] = mapped_column(String(100))11 city: Mapped[str] = mapped_column(String(50))12 marks: Mapped[int]13 14engine = create_engine("sqlite:///college.db", echo=True)15Base.metadata.create_all(engine)16 17with Session(engine) as session:18 session.add_all([19 Student(name="Aarav", city="Jaipur", marks=88),20 Student(name="Diya", city="Kochi", marks=93),21 Student(name="Kabir", city="Indore", marks=95),22 ])23 session.commit()24 25 stmt = select(Student).where(Student.marks > 90).order_by(Student.name)26 for student in session.scalars(stmt):27 print(student.id, student.name, student.marks)1/5Every model inherits from one shared Base class.
SQLAlchemy 2.0 style. Swap the URL for postgresql+psycopg://user:pass@localhost/college and the rest of the code stays the same.
Save yourself the pain
Common mistakes
Oops
Forgetting session.commit() and wondering why nothing was saved.
Do this instead
Changes stay pending until commit. If something fails, call session.rollback() or let the with block clean up.
Oops
Looping over students and reading student.courses one by one, firing a query each time.
Do this instead
That is the N+1 problem. Load related rows in one go with options(selectinload(Student.courses)).
Oops
Using create_all() to change an existing table's columns.
Do this instead
create_all never alters existing tables. Use Alembic: alembic revision --autogenerate, then alembic upgrade head.
Your mission
Library database
Quick check
You called session.add(student) but the row isn't in the database. What's the most likely reason?
Go deeper
- 1Define two related models, such as Author and Book, with a foreign key.
- 2Insert and query rows using a session.
- 3Create and apply a migration with Alembic when you add a column.
More web & apis at this stop
Stuck on this topic? Ask an Insider
Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.