SQL Essentials for Keeping State
Most AI systems are a database with an LLM attached in disguise. Learn to model state, query it, and keep it consistent with SQL.

Every real-world system you build (using AI or not) needs a way to remember things. Luckily for us, the most battle-tested system, relational databases, are also a perfect fit for building AI apps. On top of that, recent advancements in systems like Postgres1 have made them even more powerful and flexible, with features like vector search and JSONB that are tailor-made for AI workloads.
The previous tutorial gave you a Postgres container running under Docker Compose. In this tutorial, you'll set up a local Postgres instance and model the state of a chat assistant with tables, constraints, and indexes. You'll learn to write SQL queries and some of the most important clauses (WHERE, JOIN, GROUP BY, HAVING) to work with databases. Make no mistake, SQL and database design are foundational skills for any AI engineer, and this lesson is your crash course to get up to speed.
What You'll Build
- A Postgres database modeling chat threads and messages
- Queries that answer real operational questions: token spend, slow threads, orphaned data
An index that turns a sequential scan into an index scan, verified with
EXPLAIN- A Python client that queries Postgres safely with parameterized SQL
Spin Up Postgres
- 01All 6 modules · 40+ tutorials · source code
- 02Verifiable certificate with public URL
- 03LinkedIn-ready completion credential
- 04Live sessions + every recording
- 05Discord community
References
Footnotes
-
PostgreSQL 18 Documentation — Canonical reference for every statement, type, and constraint in this lesson ↩
-
psql Reference — Connection flags and backslash shortcuts like
\dt↩ -
Use the Index, Luke — Indexing explained for developers, from B-tree basics to join performance ↩
-
pgvector — Postgres extension for vector similarity search; operator and index reference ↩
-
Transactions in PostgreSQL —
BEGIN/COMMIT/ROLLBACKsemantics and atomicity guarantees ↩ -
psycopg 3 Documentation — Connection handling, parameter passing, and the query lifecycle ↩
-
OWASP: SQL Injection — Why parameterized queries are non-negotiable ↩