惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园_首页
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
量子位
博客园 - Franky
罗磊的独立博客
月光博客
月光博客
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - 聂微东
人人都是产品经理
人人都是产品经理
Hugging Face - Blog
Hugging Face - Blog
宝玉的分享
宝玉的分享
腾讯CDC
D
Docker
N
Netflix TechBlog - Medium
Y
Y Combinator Blog
V
V2EX
Microsoft Azure Blog
Microsoft Azure Blog
Latest news
Latest news
C
CERT Recently Published Vulnerability Notes
G
GRAHAM CLULEY
C
Cisco Blogs
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
T
Threatpost
Simon Willison's Weblog
Simon Willison's Weblog
GbyAI
GbyAI
S
SegmentFault 最新的问题
Blog — PlanetScale
Blog — PlanetScale
L
Lohrmann on Cybersecurity
I
Intezer
博客园 - 叶小钗
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Last Week in AI
Last Week in AI
Cisco Talos Blog
Cisco Talos Blog
Hacker News: Ask HN
Hacker News: Ask HN
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
B
Blog
Microsoft Security Blog
Microsoft Security Blog
AI
AI
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
S
Schneier on Security
V
Visual Studio Blog
The Register - Security
The Register - Security
AWS News Blog
AWS News Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
F
Fortinet All Blogs
博客园 - 司徒正美
WordPress大学
WordPress大学
Jina AI
Jina AI
T
Tor Project blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
SQLAlchemy Essentials: A Beginner’s Roadmap
Sahil Khurana · 2026-06-15 · via DEV Community

Key Takeaways

  • SQLAlchemy is both an ORM and a SQL toolkit — pick one, use both, whatever works for your situation.
  • Learn Engine, Session, and Declarative Base first. Seriously, before you write anything.
  • Runs on PostgreSQL, MySQL, SQLite, Oracle — you can swap databases without torching the whole codebase.

Introduction

Month two or three into a backend project is when it usually happens. Not a crash, not a catastrophic failure — just this slow creep of annoyance. The raw SQL strings you threw in early on? They start multiplying. You rename one column and suddenly something is broken in three places you forgot even existed. You spend twenty minutes ctrl+F-ing through files trying to find where you wrote that query six weeks ago.

It's not a crisis. It's just painful in a boring, grinding kind of way.

That's usually when people go looking for something better and end up at SQLAlchemy. It's been around since 2006. In Python terms that's ancient history — and yet it's still the default choice for serious backend work. Not because it's easy, it's not, but because it never forces your hand. You want ORM abstractions? Fine. You want to drop down and write actual SQL because the ORM is acting strange? Also fine, you can do that in the same codebase, same connection, no hacks needed. That kind of flexibility is rarer than it sounds.

Here's what you actually need to get started.


What Even Is SQLAlchemy?

Honestly, it's two tools that ship as one.

The first is the SQL Expression Language — SQL, but expressed as Python. You get precise query control without ever touching raw string concatenation. The second is the ORM, which sits on top and removes the database from your mental model almost entirely. Classes become tables. Objects become rows. You think in Python, SQLAlchemy handles the translation.

Most people start with the ORM, fall back to the Expression Language when things get weird, and bounce between both depending on what a given query needs. Some teams skip the ORM altogether and live in the Expression Language. Totally valid either way, nobody's going to argue with you.


Why Bother With It at All?

For a script or a tiny side project — genuinely, don't bother. Plain sqlite3 is sitting right there in the standard library and it'll do the job without any setup.

But once you've got real scale, real team size, a schema that keeps shifting — the "SQL strings everywhere" approach starts falling apart. Fast. That's where SQLAlchemy starts paying rent.

What You Get Why It Matters
ORM and raw SQL You're not locked into either. Use what the situation calls for.
Cross-database support PostgreSQL, MySQL, SQLite, Oracle — change the connection string, not the whole app.
Models as Python classes Schema lives in code. Any teammate can read it without knowing the database.
Full query visibility Log every query. No hidden performance problems sneaking through.
18 years of community Whatever weird thing you run into, someone already has. Check the forums.

Installation

pip install sqlalchemy

Plus a driver for your database:

pip install psycopg2      # PostgreSQL
pip install pymysql       # MySQL

SQLite ships with Python so nothing extra needed there.


Four Things to Understand Before You Write a Single Line

Most SQLAlchemy confusion is from jumping into code examples cold, without any mental picture of the parts involved. Read this first and a lot of the friction disappears.

Engine — Your actual database connection. Manages the connection pool, sits under everything, you set it up once and mostly forget it's there. Nothing else functions without it.

Session — Where you do your work. Queries, inserts, updates — all go through a session. Key thing: changes are held in memory until you call commit(). Nothing hits the database for real until that point. This is intentional. Means you can back out of a half-finished operation if something breaks mid-way.

Declarative Base — A base class. Your model classes inherit from it. It's what lets SQLAlchemy know these Python classes are supposed to map to database tables. You make it once, inherit from it everywhere.

Model — A class that represents a table. One class, one table. One instance of that class, one row. That's the whole idea.


Building Something Step by Step

Step 1 — Connect to a Database

from sqlalchemy import create_engine

engine = create_engine('sqlite:///example.db')

Production would look more like postgresql://user:pass@localhost/mydb — same pattern. SQLite is just the easiest starting point locally since there's nothing to install or configure.


Step 2 — Define a Model

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String

Base = declarative_base()

class User(Base):
    __tablename__ = 'users'

    id   = Column(Integer, primary_key=True)
    name = Column(String)
    age  = Column(Integer)

__tablename__ is what the table gets called in the actual database. The attributes are columns. Read it a couple times and the pattern sticks pretty naturally.


Step 3 — Create the Tables

Base.metadata.create_all(engine)

Looks at everything hanging off Base, runs the CREATE TABLE statements for you. No hand-writing DDL.


Step 4 — Insert, Query, Update

from sqlalchemy.orm import sessionmaker

Session = sessionmaker(bind=engine)
session = Session()

# Add a record
new_user = User(name="John Doe", age=30)
session.add(new_user)
session.commit()

# Fetch records
users = session.query(User).all()
for user in users:
    print(user.name, user.age)

# Update something
user = session.query(User).filter_by(name="John Doe").first()
user.age = 31
session.commit()

Change something, commit. That's the loop. Forget the commit and the change silently disappears — you'll do this at least once and spend a baffled ten minutes before figuring out why. It happens to everyone, don't stress it.


Step 5 — Relationships

Here's where it gets genuinely useful. Define a relationship once and stop writing joins every time you need linked data:

from sqlalchemy import ForeignKey
from sqlalchemy.orm import relationship

class Post(Base):
    __tablename__ = 'posts'

    id      = Column(Integer, primary_key=True)
    title   = Column(String)
    content = Column(String)
    user_id = Column(Integer, ForeignKey('users.id'))

    user = relationship("User", back_populates="posts")

User.posts = relationship("Post", order_by=Post.id, back_populates="user")

Now user.posts gives you the list. post.user gives you the author. The join happens behind the scenes. You just access properties like it's a regular Python object, because it is.


SQLAlchemy vs the Other Options

Django ORM vs SQLAlchemy is a question that comes up constantly. Here's a straight answer:

SQLAlchemy Django ORM Peewee
Flexibility High — ORM and raw SQL Moderate, ORM-first design Moderate
Learning Curve Steep up front Gentler Easy
Query Control Full Limited Limited
Best Fit Standalone backends, complex apps Django projects Scripts, small projects

If you're in a Django project, just use Django ORM — no argument there, it integrates perfectly and fighting it makes no sense. Peewee is a solid pick for smaller stuff, fast to get going. But outside Django, or whenever query complexity is a real concern, SQLAlchemy is the one that ages well. It's the tool you won't find yourself trying to route around two years in.


Where to Go From Here

The complexity reputation SQLAlchemy has is real but exaggerated. Most projects use a narrow slice of it — models, sessions, queries, relationships. That slice is well-built and once it clicks, it stays clicked.

Start with the ORM. Get something working. When the ORM starts making a particular query harder than it should be — and that will happen eventually — reach for the Expression Language and write the SQL directly. That's the actual workflow, not a theoretical fallback. Experienced people do exactly this, switching between layers depending on what the problem needs.

Runs on a local SQLite file on your machine. Runs on a Postgres cluster with serious traffic. The mental model you build in the first week transfers cleanly years later. That doesn't happen by accident, and it's one of the main reasons the library has lasted this long.


At Innostax, we work through this kind of thing regularly — picking the right database layer, structuring backends that stay maintainable, building data models that hold up under pressure. If you're working through the same questions for your own project, reach out at innostax.com/contact.

Originally published on the Innostax Engineering Blog.