Advanced·15 min·data · sqlalchemy · orm
SQLAlchemy Core — SQL as Python
SQLAlchemy Core: SQL, but as Python
Raw SQL strings are hard to compose and easy to get wrong. SQLAlchemy Core gives you an expression language — write queries as Python objects, get real SQL out.
Why bother
- Type-checked in your editor —
users.c.email == "..."is autocompleted. - Composable — filters, joins, aggregates are Python expressions you can build up conditionally.
- Portable — same code runs against SQLite, Postgres, MySQL, MSSQL.
- No injection — parameters are bound automatically.
Core primitives
create_engine("sqlite:///:memory:")— connection pool + dialect.Table(name, MetaData(), Column(...))— describe your schema.select(t).where(...).order_by(...)— build a SELECT.insert(t)/update(t)/delete(t)— the other DML verbs.with engine.begin() as conn:— auto-commits on success, rolls back on exception.
When to use Core vs the ORM
- Core: ETL, analytics, bulk operations, complex reporting queries.
- ORM (next lesson): object-heavy business logic with rich relationships.
- Both are the same library — you can mix them freely.
Try it
- Add a query that counts users per plan.
- Update Bob's plan to "pro" and re-run the select.