SQL vs NoSQL

In one sentence

Pick the store from your access patterns, consistency needs and scale, not the label: Postgres by default (JSONB, pgvector), a specialized NoSQL store when one access pattern outgrows a single primary.

Analogy: A relational database is a library with a full catalog: you can ask new questions later. A key-value store is a coat check: hand over a ticket, get your coat instantly, but never ask for "all the red coats".

Start from the queries, not the label: relational by default, a specialized store only when one access pattern dominates.

How it works

  • SQL gives a declared schema, constraints, joins and ACID transactions across tables.
  • NoSQL trades some of that for easier scale-out or a better fit for one access pattern.
  • NoSQL makes you design tables around known queries up front; relational lets you ask new questions later.
  • In Postgres, JSONB stores documents and pgvector keeps embeddings next to their rows, in one transaction.
  • Move a workload out only when you measure a limit: writes beyond one primary, multi-region writes, ANN scale.

Check yourself

Answer to mark it learned; your answers aren't scored.

A chat assistant (~50k daily users) runs on one Postgres. LLM traces, append-only at ~2 KB per call and queried as aggregates, now dominate its load. What do you do?

Go deeper

Full explanation

SQL (relational) databases store rows in tables with a declared schema, enforce constraints, join across tables and give you ACID transactions. Postgres and MySQL are the defaults. NoSQL is an umbrella for stores that give up some of that for an easier scale-out story or a better fit for one access pattern:

  • Key-value (Redis, DynamoDB): get/put by key, flat latency at any scale.
  • Document (MongoDB): one nested JSON record per entity, schema-on-read.
  • Wide-column (Cassandra, Bigtable): partition key + sorted clustering key, built for huge write rates.
  • Graph (Neo4j): multi-hop relationship queries.

The real question is which queries you must serve, how consistent they must be, and at what scale. NoSQL makes you design tables around known queries up front (DynamoDB single-table design); relational lets you ask new questions later.

My default is just use Postgres: JSONB gives you documents with GIN indexes, pgvector keeps embeddings next to the rows they describe, and one transaction covers both. Move a workload out when you measure a limit: write throughput beyond one primary, multi-region writes, or ANN at Vector databases scale. NewSQL (Spanner, CockroachDB) keeps SQL and serializable transactions while sharding automatically, paying with consensus latency on every commit.

Code One Postgres: relational + JSONB + pgvector
sqlOne Postgres: relational + JSONB + pgvector
-- One Postgres for an AI app: relational + document + vector
CREATE EXTENSION IF NOT EXISTS vector;

CREATE TABLE messages (
  id          bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  tenant_id   bigint      NOT NULL,
  convo_id    uuid        NOT NULL,
  role        text        NOT NULL,
  content     text        NOT NULL,
  meta        jsonb       NOT NULL DEFAULT '{}',  -- model, tool calls, token counts
  embedding   vector(1536),                       -- pgvector
  created_at  timestamptz NOT NULL DEFAULT now()
);

CREATE INDEX ON messages (tenant_id, convo_id, created_at);       -- load a thread
CREATE INDEX ON messages USING gin (meta jsonb_path_ops);          -- filter metadata
CREATE INDEX ON messages USING hnsw (embedding vector_cosine_ops); -- ANN recall

-- Semantic memory recall for one tenant, filtered on JSONB, in one query
SELECT id, content
FROM messages
WHERE tenant_id = 42
  AND meta @> '{"kind": "memory"}'
ORDER BY embedding <=> $1   -- cosine distance to the query embedding
LIMIT 5;
Real example

A chat assistant with ~50k daily users runs on one Postgres: users and conversations as relational tables, each message's tool calls and token counts in a JSONB column, and 1536-dim embeddings in pgvector for memory recall. One transaction writes the message and its embedding, so recall never sees half a turn. LLM traces (append-only, ~2 KB per call, queried as aggregates) outgrow it first and move to a columnar store like ClickHouse. At ~40M embeddings with per-tenant filters, ANN latency climbs and vectors move to a dedicated vector DB; conversations stay in Postgres.

Trade-offs +3 · −4

+ You gain

  • Relational: new queries without redesign; constraints and transactions catch bugs at write time.
  • Key-value and wide-column stores scale writes horizontally with predictable latency built in.
  • Postgres covers relations, documents (JSONB) and vectors (pgvector): one system to back up, secure and operate.

− You pay

  • One Postgres primary caps write throughput; sharding it (Citus or app-level) is real work.
  • NoSQL: queries are designed up front; a new access pattern can mean a new table and a backfill.
  • NoSQL: weaker or single-item transactions, and joins move into application code.
  • Every extra store adds ops, backups and consistency gaps between stores.

Use it when

Postgres by default for transactional app data, including AI metadata and moderate vector counts. A NoSQL store when one access pattern dominates at a write rate, size or latency a single primary can't serve.

Avoid it when

Don't pick NoSQL for "schema flexibility" or because "it scales" before you've measured. Don't force analytics (traces, logs) into OLTP Postgres either: use a columnar store.

Numbers to know 5
  • DynamoDB: 400 KB max item; each partition serves up to 3,000 RCU and 1,000 WCU per second.
  • MongoDB: 16 MB max document size.
  • pgvector indexes (HNSW, IVFFlat) support up to 2,000 dimensions for vector, 4,000 for halfvec.
  • Postgres default isolation is Read Committed, not Serializable.
  • Rule of thumb: pgvector on one well-sized node is comfortable up to ~10M vectors; beyond that, plan partitioning or a dedicated vector DB.
Common pitfalls 4
  • Picking MongoDB for "flexibility", then rebuilding joins, constraints and transactions in application code.
  • A hot partition key (e.g. tenant_id when one tenant is 40% of traffic): one partition throttles while the rest idle.
  • Assuming Postgres is serializable by default: under Read Committed, read-modify-write races lose updates.
  • Embeddings in a separate store with no sync plan: deleted or re-permissioned rows live on as orphan vectors.
Interview questions 3

Answer out loud first, then reveal.

How do you choose the database for a new AI product?Show answer

I start from access patterns, not the label: the top queries, their latency, consistency needs and expected volume. Most of it — users, conversations, billing — is relational and transactional, so I start with Postgres, JSONB for flexible metadata and pgvector for embeddings. One system, one backup, one transaction boundary. I split a workload out only on a measured limit: traces to a columnar store because they're append-only analytics, vectors to a dedicated DB past ~10M with heavy filtering, hot key lookups to Redis or DynamoDB.

When is NoSQL clearly the right answer?Show answer

When one access pattern dominates and its scale beats a single primary. Say every agent step for millions of sessions: very high write rates, always read by session id in time order. DynamoDB or Cassandra with partition key session_id and sort key timestamp serves that with flat latency and no sharding work on my side. The price: no ad-hoc queries, so analytics goes through a stream into a warehouse, and I must choose a partition key without hot spots.

What does NewSQL buy you, and what does it cost?Show answer

Spanner and CockroachDB keep SQL and serializable transactions while sharding and replicating automatically with Paxos or Raft, so I get relational semantics across regions. The cost is commit latency: every write needs a consensus round, and cross-region writes add tens to hundreds of milliseconds. I reach for it for multi-region writes that must be strongly consistent, like ledgers or quotas, not as a default for a product that fits on one Postgres.