Pythonsqlalchemyv2.0.48
PythonBeginner-friendly

sqlalchemy

Database Abstraction Library

ormsqldatabasepostgresqlmysqlfront-ends
The Problem

Writing raw SQL strings in Python means string concatenation (and SQL injection risks), database-specific syntax that breaks when you switch engines, and no way to express relationships between tables as Python objects. SQLAlchemy solved this by offering both a high-level ORM and a Pythonic SQL expression layer.

Mental Model

SQLAlchemy has two layers you use together. The Core layer gives you a SQL expression API โ€” table.select().where(table.c.id == 5) generates correct SQL for any database. The ORM layer maps Python classes to tables, so you work with User objects and SQLAlchemy handles the INSERT/SELECT/JOIN. You can mix both layers freely.

60-second start

Install sqlalchemy

pip install sqlalchemy
import sqlalchemy

Use it when

Use SQLAlchemy in any Python application that talks to a relational database โ€” web apps, data pipelines, ETL scripts. It supports PostgreSQL, MySQL, SQLite, and Oracle, so the same code runs everywhere. It's the standard ORM in the Python ecosystem, with integrations for Flask, FastAPI, and most web frameworks.

Skip it when

SQLAlchemy's full ORM is overkill for simple read-only queries or scripts that just need to run a few SQL statements. For those cases, use the database's driver directly (psycopg2, sqlite3) or a lightweight query builder like databases.

Alternatives
tortoise-ormAsync-native ORM modelled after Django ORM; better for pure asyncio applications
peeweeSmaller, simpler ORM for straightforward CRUD applications without complex relationships
databasesAsync SQL query library without ORM overhead; good when you want to write SQL directly but asynchronously

Ready to explore the full API?

See every class, function, and relationship in an interactive graph.