SQLAlchemy is a popular SQL toolkit and Object-Relational Mapper (ORM) for Python. It provides:
With SQLAlchemy, you can focus on Python objects instead of hand-writing SQL for everything, while still keeping full control when you need raw SQL.
Typical workflow when using SQLAlchemy ORM:
declarative_base().Below is a minimal example that shows how to set up SQLAlchemy with SQLite and define a simple model.
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import declarative_base, sessionmaker
# 1. Create engine (here using SQLite database file)
engine = create_engine("sqlite:///students.db", echo=True)
# 2. Base class for ORM models
Base = declarative_base()
# 3. ORM model mapped to a "students" table
class Student(Base):
__tablename__ = "students"
id = Column(Integer, primary_key=True)
name = Column(String(100), nullable=False)
age = Column(Integer)
city = Column(String(100))
def __repr__(self):
return f"<Student id={self.id} name={self.name!r}>"
# 4. Create all tables in the database
Base.metadata.create_all(engine)
# 5. Create a Session factory
SessionLocal = sessionmaker(bind=engine)
Once the model and engine are ready, you can perform CRUD (Create, Read, Update, Delete) operations using a session.
from sqlalchemy.orm import Session
# Create a new session
with Session(engine) as session:
# INSERT: create Student objects
s1 = Student(name="Alice", age=21, city="Pune")
s2 = Student(name="Bob", age=22, city="Mumbai")
session.add_all([s1, s2])
session.commit() # commit transaction to save to DB
# SELECT: query all students
all_students = session.query(Student).all()
print("All students:", all_students)
# FILTER: students from Pune
pune_students = session.query(Student).filter(Student.city == "Pune").all()
print("Pune students:", pune_students)
# UPDATE: change a student's city
alice = session.query(Student).filter(Student.name == "Alice").first()
alice.city = "Delhi"
session.commit()
# DELETE: remove a student
bob = session.query(Student).filter(Student.name == "Bob").first()
session.delete(bob)
session.commit()
students.db (if it does not already exist).students with columns id, name, age, and city.Because echo=True was passed to create_engine(), SQLAlchemy will also print the generated SQL statements to the console. This helps you see exactly which SQL is executed behind the scenes.
Session as a context manager (with Session(engine) as session:) to auto-handle cleanup.models.py) for better organization.nullable=False, unique constraints, and indexes.echo=True during development for debugging, but turn it off in production.Student model to add a email column. Insert a few students and verify that the new column is stored.Course with fields like id, name, and credits. Map it to a new table using SQLAlchemy ORM.Student and Course (e.g., many-to-many using an association table). Try inserting sample data and querying which students are enrolled in which courses."sqlite:///:memory:") and observe the behavior.As you practice, pay attention to how SQLAlchemy translates your Python code into SQL and how sessions manage pending changes before committing to the database.
Use this quick helper to imagine how many records you might be inserting with SQLAlchemy. This is just a front-end calculator; in a real app, such numbers would guide how you batch inserts and design transactions.