SQL
AI apps need persistent storage for users, conversations, and metadata. SQL databases provide reliable, queryable storage.
SQL is Excel for databases — rows and columns, but queries scale to millions of records instantly.
Visual Workflows
Start here — study each diagram, then use + / − to zoom if needed.
Overview
Scroll inside the frame · use + / − to zoom
Scroll inside the frame · use + / − to zoom
Key Takeaways
- 1.SQL is the language for relational databases — store users, chat history, and app metadata in structured tables.
- 2.Tables have rows and columns.
- 3.SELECT reads, INSERT creates, UPDATE modifies, DELETE removes.
- 4.PostgreSQL is the go-to for AI apps.
Real Example
Scenario
Your chat app needs to remember the last 10 messages for context window management.
What you would do
Store messages in a PostgreSQL table with chat_id, role, and content. Query: SELECT * FROM messages WHERE chat_id = 1 ORDER BY id DESC LIMIT 10.
Practice Task
Open sqlite3 (or any SQL client) and run: CREATE TABLE notes (id INTEGER, text TEXT); INSERT INTO notes VALUES (1, 'hello'); SELECT * FROM notes; UPDATE notes SET text='world' WHERE id=1; DELETE FROM notes WHERE id=1;
Commands
Commands to Remember
SELECT * FROM table WHERE condition; # read rows matching a conditionINSERT INTO table (col) VALUES ('val'); # add a new rowUPDATE table SET col = 'val' WHERE id = 1; # modify an existing rowDELETE FROM table WHERE id = 1; # remove a rowpsql -U user -d dbname # connect to a PostgreSQL database
Cheat Sheet
Quick recap
quick ref- •SELECT read · INSERT create · UPDATE modify · DELETE remove
- •Data stored in tables — rows and columns with defined schema
- •PostgreSQL is the default for AI apps
- •JOIN combines related tables · indexes speed up queries
- •SQLAlchemy maps Python to tables · Alembic handles migrations
- •pgvector adds embedding search inside Postgres
Common Mistakes
- ✕No database migrations — schema drift
- ✕SQL injection from raw string queries
- ✕Not indexing frequently queried columns