Lesson 3 of 5 Developing with Azure Database for PostgreSQL

Designing PostgreSQL Schemas for AI Workloads

This lesson explains how to choose data types, model documents and chunks, enforce integrity, and decide between columns, jsonb and partitioning.

Learning outcomes

After completing this lesson, you will be able to:

  • Choose appropriate PostgreSQL data types.
  • Describe a documents and chunks design.
  • Explain the role of constraints in multitenant data.
  • Compare typed columns with jsonb.

Choosing data types

PostgreSQL has a rich type system, and choosing precise types prevents bad data, saves space and allows efficient indexes. The following table lists the types that most AI back-end schemas use, with the reason to prefer each.

DataRecommended typeReason
Surrogate keysbigint GENERATED ALWAYS AS IDENTITY or uuidCompact, sequential keys; uuid when keys are generated outside the database
TexttextNo performance penalty over varchar(n); add a CHECK constraint if a length limit is a business rule
Money and exact quantitiesnumeric(p, s)Exact decimal arithmetic; floating point types round
Points in timetimestamptzStores an absolute instant and converts time zones correctly
FlagsbooleanClear intent and small storage
Semi-structured attributesjsonbBinary JSON that can be indexed with GIN and queried with operators
Embeddingsvector(n) or halfvec(n)Fixed dimensions allow vector indexes; halfvec halves the size

Two type traps are common. timestamp without time zone stores a wall-clock reading with no zone, which causes errors when servers or users are in different zones; timestamptz is almost always right. And json (without b) stores the original text and cannot be indexed efficiently; jsonb is the right choice for queried JSON.

Match the pairs

Choosing PostgreSQL types

Exam skills 2.2.2

Match each kind of data with the recommended PostgreSQL type.

Log in to try this activity Interactive activities are free with an account.

Modelling documents and chunks

Retrieval works on chunks, but users and permissions are about documents. A normalized design therefore separates the two: a documents table holds one row per source document with its title, source URI, owner, tenant and access metadata, and a chunks table holds one row per chunk with its text, position and embedding, referencing its document with a foreign key. Metadata used to filter retrieval, such as the tenant, is stored on the document and, where filters must be fast, copied to the chunk as well.

CREATE TABLE documents (
    id          bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    tenant_id   uuid        NOT NULL,
    title       text        NOT NULL,
    source_uri  text        NOT NULL UNIQUE,
    category    text        NOT NULL,
    attributes  jsonb       NOT NULL DEFAULT '{}',
    updated_at  timestamptz NOT NULL DEFAULT now()
);

CREATE TABLE chunks (
    id          bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    document_id bigint      NOT NULL REFERENCES documents (id) ON DELETE CASCADE,
    tenant_id   uuid        NOT NULL,
    position    integer     NOT NULL,
    content     text        NOT NULL,
    content_tsv tsvector    GENERATED ALWAYS AS (to_tsvector('english', content)) STORED,
    embedding   vector(1536) NOT NULL,
    UNIQUE (document_id, position)
);

Several design choices in this schema are deliberate. ON DELETE CASCADE removes a document's chunks with the document, so deleted content cannot be retrieved. The unique constraint on document and position lets re-ingestion replace chunks predictably. The generated column content_tsv keeps a full-text search vector up to date automatically, enabling hybrid search. The vector(1536) dimension matches the embedding model, which a vector index requires.

The following diagram compares the original schema of a table of document chunks with the revised one.

The chunk schema before and after. The original embedding column declares no dimensions, so HNSW cannot index it; the tenant is hidden inside an unindexed json value; and document titles repeat in every chunk. The revised schema keeps titles in a documents table referenced by a foreign key, adds a typed tenant_id column with a B-tree index, and declares vector(1536).
The revised schema is abbreviated.
Match the pairs

Why the schema looks like this

Exam skills 2.2.2

Match each feature of the documents and chunks schema with the problem it solves.

Log in to try this activity Interactive activities are free with an account.

Constraints and integrity

Constraints let the database reject invalid data instead of relying on every application path to check it. NOT NULL marks required columns, UNIQUE prevents duplicates, CHECK enforces rules such as CHECK (price >= 0), and foreign keys guarantee that references point to existing rows. In a multitenant design, including tenant_id in every table, and in composite keys where appropriate, makes tenant isolation explicit and supports row-level security policies that filter rows by tenant automatically.

Match the pairs

Constraints

Exam skills 2.2.2

Match each rule with the constraint that enforces it.

Log in to try this activity Interactive activities are free with an account.

jsonb, normalization and partitioning

jsonb suits attributes that vary between rows, such as product specifications that differ by category, or metadata from different sources. It can be queried with operators such as @> (contains) and ->> (extract as text) and indexed with GIN. Attributes that every row has and that queries filter or join on should be ordinary columns, which are smaller, typed and better understood by the planner.

Very large tables can be partitioned: one logical table is split into child tables by a key such as date range or tenant, and queries that filter on the key read only the matching partitions. Partitioning helps with data lifecycle (dropping an old month is instant) and with keeping per-partition indexes small, but adds complexity, so it is used for tables in the hundreds of millions of rows rather than by default.

Typed columns
SchemaFixed, enforced by the database
IndexingB-tree and others per column
Best forCommon attributes used in filters, joins and sorts
Choose when Every row has it and queries depend on it
jsonb column
SchemaFlexible per row
IndexingGIN on the whole document, or expression indexes on paths
Best forVarying attributes and pass-through metadata
Choose when It varies by row or source
Sort into groups

Column or jsonb?

Exam skills 2.2.2

Decide whether each attribute should be a typed column or live in a jsonb column.

Log in to try this activity Interactive activities are free with an account.
Worked example

A schema that returns other tenants' chunks

A RAG schema stores chunks in one table with columns id, doc_title, content, metadata json and embedding vector (no dimension). Retrieval filters tenants with metadata->>'tenant' = %s, which is slow, and an attempt to create an HNSW index fails with "column does not have dimensions".

The schema has three problems. The embedding column must declare its dimensions, such as vector(1536), before it can be indexed. The tenant, a filter used by every query, belongs in a typed tenant_id column with a B-tree index (or in partial indexes), not inside an unindexed json value. And repeating document titles in every chunk invites inconsistencies; a documents table referenced by a foreign key keeps them in one place.

Converting json to jsonb and adding a GIN index would speed the filter somewhat, but a typed column is simpler and faster for a value that every query uses. Removing the filter for speed would break tenant isolation.

Check yourself

Why is timestamptz usually preferred to timestamp for event times?

Show answer

timestamptz stores an absolute instant and converts time zones correctly, while timestamp stores a wall-clock reading with no zone, which causes errors across zones.

Exam Tips

Remember for the exam

  • Use timestamptz, numeric for money, text for strings and jsonb (not json) for queried JSON.
  • Declare vector dimensions, such as vector(1536); undimensioned columns cannot be indexed.
  • Separate documents from chunks and cascade deletes so removed content cannot be retrieved.
  • Filters used by every query belong in typed, indexed columns, not inside jsonb.