Data Access with SQLAlchemy
Map tables to typed Python models with SQLAlchemy 2.x, query them through the ORM or raw SQL, and manage sessions and connections correctly in a web service.
4 objectives 6 steps about 130 min
Learn it step by step
Read the lessons in order, try the practice checks, then prove the skill with the knowledge check.
This skill page is a public outline. Its lessons and knowledge check appear here as subject-matter experts approve them.
Learning objectives
- Declare typed ORM models with relationships and constraints that match a relational schema.
- Write select, insert, update and delete operations in 2.0 style, and use parameterized raw SQL through text() when the ORM is the wrong tool.
- Detect an N+1 query pattern from the SQL log and remove it with an explicit loading strategy.
- Scope sessions, transactions and pooled connections per request in a sync or async service, keeping data access behind a repository or service layer.
Lesson plan
6 steps, about 130 min · 5 of 5 lessons available so far
- ORM, Query Builder or Raw SQL: Choosing the Level Concept · 15 min
- Typed Models and Relationships Worked example · 25 min
- Queries in 2.0 Style, and When to Write SQL Yourself Worked example · 25 min
- Lab: Hunting an N+1 in the SQL Log Lab · 25 min
- Sessions, Pools and Async Engines in a Web App Concept · 25 min
- Check: Read the ORM Code, Predict the SQL Knowledge check · 8 questions
Practise it
Replace the in-memory store of your API with PostgreSQL through SQLAlchemy 2.x and an async engine: models with a one-to-many relationship, a session-per-request dependency, one report endpoint written as parameterized raw SQL, and a test asserting the list endpoint issues a constant number of queries.
References
Hard prerequisites
Unlocks
On these roadmaps
Progress and evidence for this skill are shared across all of them.