SQL from Python

Your data lives in SQL Server today — and Postgres tomorrow. Python speaks both, and one skill transfers.

▶ Watch this reel

What you'll learn

  1. SQLAlchemy Core & ORM
  2. pyodbc & SQL Server
  3. Connection pooling
  4. Alembic migrations
  5. Postgres basics
  6. pgvector intro

Remember this

SQLAlchemy

SQL Server from Python

Pooling

Alembic

Postgres

pgvector

Code: SQLAlchemy + Postgres/pgvector in one script

from sqlalchemy import create_engine, text

# Same code against SQL Server — only the URL changes:
# engine = create_engine("mssql+pyodbc://user:pw@server/db?driver=ODBC+Driver+18+for+SQL+Server")
engine = create_engine(
    "postgresql+psycopg://postgres:pw@localhost:5432/app",
    pool_size=5, max_overflow=10, pool_pre_ping=True,
)

# pgvector setup (once)
with engine.begin() as conn:
    conn.execute(text("CREATE EXTENSION IF NOT EXISTS vector"))
    conn.execute(text("""
        CREATE TABLE IF NOT EXISTS docs (
          id BIGSERIAL PRIMARY KEY,
          tenant_id TEXT NOT NULL,
          body TEXT,
          embedding vector(1536)
        )"""))
    conn.execute(text("""
        CREATE INDEX IF NOT EXISTS docs_emb_idx
        ON docs USING hnsw (embedding vector_cosine_ops)"""))

# Insert with vector (psycopg adapts np arrays)
with engine.begin() as conn:
    conn.execute(text("""
        INSERT INTO docs (tenant_id, body, embedding)
        VALUES (:t, :b, :e)"""),
        {"t": "acme", "b": text_, "e": vec})

# Semantic search + tenant filter in ONE query
with engine.connect() as conn:
    rows = conn.execute(text("""
        SELECT id, body FROM docs
        WHERE tenant_id = :t
        ORDER BY embedding <=> :q
        LIMIT 5"""),
        {"t": "acme", "q": query_vec}).all()

# Migrations: alembic revision --autogenerate -m "init"