M06·AI/ML Foundations

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.

SQL Essentials for Keeping State

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

Members onlyJoin 855+ members
Members only from here
This lesson is part of the full AI engineering roadmap. Here's what unlocking gives you.
What you unlock
  • 01All 6 modules · 40+ tutorials · source code
  • 02Verifiable certificate with public URL
  • 03LinkedIn-ready completion credential
  • 04Live sessions + every recording
  • 05Discord community
Price·lifetime
$299$197·Pay once
“Best educational investment in my ML/AI journey.”
— Ana Clara Medeiros·AI Developer
30-day money-back guaranteeInstant access after paymentSecure checkout · stripe

References

Footnotes

  1. PostgreSQL 18 Documentation — Canonical reference for every statement, type, and constraint in this lesson

  2. psql Reference — Connection flags and backslash shortcuts like \dt

  3. Use the Index, Luke — Indexing explained for developers, from B-tree basics to join performance

  4. pgvector — Postgres extension for vector similarity search; operator and index reference

  5. Transactions in PostgreSQLBEGIN/COMMIT/ROLLBACK semantics and atomicity guarantees

  6. psycopg 3 Documentation — Connection handling, parameter passing, and the query lifecycle

  7. OWASP: SQL Injection — Why parameterized queries are non-negotiable