SQLAlchemy Core vs SQLAlchemy ORM Explained

SQLAlchemy is the premier database toolkit for Python, offering two distinct layers for managing relational databases: SQLAlchemy Core and SQLAlchemy ORM. While both facilitate database communication, they operate at different levels of abstraction and cater to different programming paradigms. This guide provides a direct comparison between Core's schema-centric, SQL expression model and the ORM's object-centric, domain-driven approach to help you choose the right tool for your project.

What is SQLAlchemy Core?

SQLAlchemy Core is the foundational data access layer that provides a Pythonic abstraction over raw SQL. It is built around database schemas, using objects such as Table, Column, and MetaData to represent database structures.

Key characteristics of SQLAlchemy Core include:

What is SQLAlchemy ORM?

SQLAlchemy ORM (Object-Relational Mapping) is a high-level abstraction built directly on top of SQLAlchemy Core. It bridges relational database tables and traditional object-oriented programming by mapping database tables to custom Python classes.

Key characteristics of SQLAlchemy ORM include:

Core Differences Compared

Feature SQLAlchemy Core SQLAlchemy ORM
Primary Abstraction Tables, Columns, SQL expressions Python classes, instances, relationships
Paradigm Schema-centric and functional Domain-centric and object-oriented
State Tracking None; explicitly execute queries Automatic via the Session (Unit of Work)
Output Type Direct row mappings and tuples Mapped class instances
Overhead Minimal; close to raw driver performance Higher; overhead from object hydration and state management
Query Style Focuses on columns and relational algebra Focuses on entities and entity graphs

When to Use Core vs. ORM

Choose SQLAlchemy Core when:

Choose SQLAlchemy ORM when:

Because the ORM is built on Core, these tools are not mutually exclusive. A common architectural pattern is to use the ORM for standard application business logic while dropping down to SQLAlchemy Core for complex reporting queries and bulk data processing.