PostgreSQL Schemas, Data Types and Indexes
30-second answer
A good AI table in Azure Database for PostgreSQL keeps each fact in the right type: uuid or bigint keys, text for chunks, jsonb for flexible metadata, timestamptz for times and vector(1536) (from the pgvector extension) for embeddings. You first add vector to the azure.extensions server parameter, then run CREATE EXTENSION vector. Then you index for the way you query: B-tree for equality and ranges, GIN for jsonb, and HNSW or IVFFlat for vectors, and you prove it works with EXPLAIN ANALYZE.
Exam objective: 2.2.2 Model schemas and implement indexing strategies, including designing tables and choosing appropriate data types. 2.2.3 Implement indexing strategies, including optimizing query latency and reducing pgvector compute overhead. (Skills measured as of October 7, 2026)
Simulations
Feel it before you read it. No account needed, nothing leaves this page.
Extensions must be <strong>allow-listed</strong> first. Open <strong>Server parameters</strong>, find <code>azure.extensions</code> and tick <strong>VECTOR</strong>.
👆 Click the glowing item in the portal to continue
Read the steps as text
- Extensions must be allow-listed first. Open Server parameters, find azure.extensions and tick VECTOR.
- Saved. Now open a terminal and create the extension in your database.
- vector(1536) holds one embedding. HNSW with vector_cosine_ops makes nearest-neighbour search fast; a normal index on tenant_id helps the filter.
- <=> is cosine distance: smaller means closer. Filter by tenant, order by distance, take the top 3.
- EXPLAIN shows Index Scan using docs_embedding_idx. Without the index it would be a sequential scan over every row.
🧪 Simulation for learning. Screens are simplified versions of the Azure portal; names, prices and IDs are examples. Nothing here touches real Azure.
🖱️ Drag to rotate · scroll or pinch to zoom
PostgreSQL with pgvector
In Azure Database for PostgreSQL, the pgvector extension adds a vector(1536) column type. Without an index, every search compares against every row (a sequential scan). An HNSW or IVFFlat index finds near neighbours fast, trading a little recall for a lot of speed.
🤔 What happens if…
Read this tour as text
- Text becomes a vector. An embedding model turns text into a list of numbers, a vector (1,536 numbers for
text-embedding-3-small). Texts that mean similar things get vectors that sit close together, so "refund" lands near "money back". - Cosmos DB: items, partitions, RUs. In Azure Cosmos DB for NoSQL, JSON items live in containers, spread across logical partitions by the partition key. Every operation costs Request Units (RUs). A point read by id and partition key costs about 1 RU. A query that scans every partition costs far more.
- Indexing and consistency. By default Cosmos DB indexes every property, so writes cost more RUs. An indexing policy can exclude paths you never filter on, such as the big
embeddingarray. Consistency levels trade freshness for speed and cost: Strong, Bounded staleness, Session (default), Consistent prefix, Eventual. - Vector search in Cosmos DB. A vector embedding policy tells Cosmos DB where the vectors are, their dimensions and distance function. A vector index makes search fast:
diskANNorquantizedFlatfor large sets, orflatfor exact search on small vectors (up to 505 dimensions). ThenORDER BY VectorDistance(c.embedding, @q)returns the closest items. - Change feed. The change feed is an ordered log of inserts and updates in a container (deletes only show up in the *all versions and deletes* mode). A change feed processor reads it with a lease container that remembers how far each worker got, so a new product can be embedded the moment it’s saved.
- PostgreSQL with pgvector. In Azure Database for PostgreSQL, the pgvector extension adds a
vector(1536)column type. Without an index, every search compares against every row (a sequential scan). An HNSW or IVFFlat index finds near neighbours fast, trading a little recall for a lot of speed. - RAG with a metadata filter. Retrieval-augmented generation (RAG): embed the question, fetch the closest chunks (
ORDER BY embedding <=> $1 LIMIT 5), filter by metadata such astenant_idorlang, then send those chunks to the model as context. The answer is grounded in your own data. - Azure Managed Redis. Azure Managed Redis keeps hot data in memory. Cache-aside: check Redis, and on a miss read the database and store the result with a TTL. When data changes, invalidate the key. Redis can also hold a vector index for fast similarity search, for example a semantic cache of answers.
Build the retrieval half of a RAG app on PostgreSQL. Connect with psql, get past the extension allow-list, load 5,000 chunks for three tenants, then make similarity search fast with HNSW and safe with a tenant filter.
🎓 Education-only simulation. Your lab is saved in this browser, so you can leave and continue later.
😟 THE PROBLEM
Queries that took 20 ms now take 4 seconds at a million rows.
😊 THE SOLUTION
Pick the right data types and index what you filter on.
- Everything stored as text✓ Proper types and JSONB
- Sequential scans✓ B-tree and GIN indexes
- Guessing the plan✓ EXPLAIN ANALYZE
Start with a question
Why does the same query take 3 milliseconds in one database and 3 seconds in another?
Picture two libraries with the same books. One has a catalogue sorted by author and a shelf map. The other has books piled in the order they arrived. Finding one book in the second library means checking every pile.
Databases work the same way. The schema decides what each column holds, and indexes are the catalogue. Get them right and your AI app pulls the right 5 chunks out of 2 million rows before the user notices. Get them wrong and every question walks the whole table.
Explain it like I’m 10
The technical explanation
Step 1: allow the extension, then create it
On flexible server, extensions are off until you allow them. The pgvector project’s extension name is vector:
- In the portal, open Server parameters, find azure.extensions and tick VECTOR. Save. (The CLI equivalent is
az postgres flexible-server parameter set --name azure.extensions --value vector.) - Connect to your database and run:
SHOW azure.extensions; -- check it's allowed
CREATE EXTENSION IF NOT EXISTS vector;
CREATE EXTENSION works per database, so repeat it in each database that needs vectors. If you skip step 1, you get an error saying the extension isn’t allow-listed.
Step 2: pick the right types
Here’s a table for document chunks in a multi-tenant support assistant:
CREATE TABLE doc_chunks (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
tenant_id text NOT NULL,
doc_id uuid NOT NULL,
chunk_no int NOT NULL,
content text NOT NULL,
metadata jsonb NOT NULL DEFAULT '{}'::jsonb, -- {"lang":"en","product":"router"}
created_at timestamptz NOT NULL DEFAULT now(),
embedding vector(1536) -- text-embedding-3-small
);
| Type | Use it for | Why |
|---|---|---|
uuid / bigint | Keys | uuid is safe to generate anywhere; bigint is smaller and sorts well |
text | Chunks, titles | No length limit worries; use varchar(n) only when a limit is a real rule |
jsonb | Flexible metadata | Indexed with GIN, queried with @> and ->> |
timestamptz | Times | Stores an exact moment, so time zones don’t bite you later |
vector(1536) | Embeddings | Fixed dimensions are required for indexing |
halfvec(1536) | Embeddings, smaller | Half precision, about half the storage and index size |
Two limits are worth knowing. A vector column without dimensions can’t be indexed. And HNSW and IVFFlat indexes on vector support up to 2,000 dimensions. If your model returns 3,072, either ask the model for fewer (the dimensions parameter on text-embedding-3 models) or store halfvec, which pgvector can index at higher dimensions.
Step 3: index for the way you query
-- B-tree: equality, ranges and sorting
CREATE INDEX ix_chunks_tenant_created ON doc_chunks (tenant_id, created_at DESC);
-- GIN: jsonb containment, such as metadata @> '{"lang":"en"}'
CREATE INDEX ix_chunks_metadata ON doc_chunks USING gin (metadata);
-- HNSW: approximate nearest neighbour search with cosine distance
CREATE INDEX ix_chunks_embedding ON doc_chunks USING hnsw (embedding vector_cosine_ops);
| Index | Good for | Not good for |
|---|---|---|
| B-tree (default) | =, <, BETWEEN, ORDER BY on normal columns | jsonb contents, vectors |
| GIN | jsonb @>, arrays, full-text tsvector | Range queries |
| HNSW | Vector search, best speed versus recall; can be built on an empty table | Very large builds on small memory |
| IVFFlat | Vector search with faster builds and less memory | Building before data is loaded (it learns clusters from the rows) |
The vector index has to match the operator your query uses. pgvector has three main ones:
| Operator | Distance | Operator class |
|---|---|---|
<-> | Euclidean (L2) | vector_l2_ops |
<=> | Cosine distance | vector_cosine_ops |
<#> | Negative inner product | vector_ip_ops |
An index built with vector_cosine_ops speeds up ORDER BY embedding <=> $1, and is ignored by ORDER BY embedding <-> $1.
Step 4: prove it with EXPLAIN ANALYZE
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, content
FROM doc_chunks
ORDER BY embedding <=> '[0.012, -0.031, ...]'
LIMIT 5;
Before the HNSW index, the plan shows Seq Scan on doc_chunks under a Sort, and the real time grows with every row. After it, you should see Index Scan using ix_chunks_embedding. If you still see a Seq Scan, check the operator class, check that LIMIT is there (the index is used for “top K” queries), and run ANALYZE doc_chunks so the planner has fresh statistics. On a huge table where ANALYZE itself would take too long, run EXPLAIN without ANALYZE to see the plan instantly.
Architect level Cutting pgvector compute and storage
Every 1536-dimension vector is about 6 KB. Two million chunks is 12 GB before indexes, and an HNSW index adds more. A few levers help. Ask the embedding model for fewer dimensions if your tests show recall holds up. Switch to halfvec, which halves the bytes, and you can even keep vector in the table and index an expression cast to halfvec. Use a partial index (WHERE tenant_id = 'bigcustomer') when one slice gets most of the searches, remembering that the query’s WHERE must match the index’s WHERE exactly for the planner to use it. And partition very large tables by tenant or date so searches touch fewer rows.
Real-world business scenario
Northwind Electronics (fictional)
- The problem
- Their product-help bot stored metadata as a text column of comma-separated tags and had no vector index. Searches across 1.8 million manual chunks took several seconds and often returned chunks from the wrong product line.
- What they used
- Azure Database for PostgreSQL flexible server with pgvector: jsonb metadata with a GIN index, a B-tree index on (tenant_id, created_at) and an HNSW index with vector_cosine_ops.
- Why that choice
- Typed columns let the filters use indexes, and the HNSW index turned the vector search from a full scan into a graph walk. EXPLAIN ANALYZE confirmed each change.
- The result
- Typical retrieval time fell from seconds to tens of milliseconds, and the product filter stopped mixing up router and modem manuals.
When to use it and when not to
✓ Use it when…
- Your app already uses PostgreSQL and you want vectors next to the business data you join with.
- You need SQL filters (tenant, language, date) combined with similarity search.
- You want to check every performance change with EXPLAIN ANALYZE.
✕ Think twice when…
- Putting everything in one jsonb blob. Filter-heavy fields deserve their own typed, indexed columns.
- Indexing every column "just in case". Each index slows writes and uses storage.
↔ Alternatives to consider
- Azure Cosmos DB for NoSQL vector search when the app is document-first and needs global distribution.
- Azure AI Search when you want hybrid keyword plus vector ranking and semantic reranking without managing indexes yourself.
Test yourself with exercises
5 original practice questions in the AI-200 style. Pick your answers, then check them. You will see why each option is right or wrong. Score 75% or more and this topic is marked complete.
Interview preparation
Say your answer out loud first, then open the model answer. Interviewers care more about your reasoning than the exact words.
Beginner What steps do you take to use pgvector on Azure Database for PostgreSQL flexible server?
Model answer
Two steps. First I add vector to the azure.extensions server parameter, which is the allow-list. Then I connect to the database and run CREATE EXTENSION vector. After that I can create a column like embedding vector(1536).
Interviewer follows up
Why vector and not pgvector?
You
The project is called pgvector, but the extension's actual name is vector. Both the allow-list and CREATE EXTENSION use vector.
Intermediate Why put metadata in jsonb instead of adding a column for everything?
Model answer
For fields that change often or differ per document, like source system tags, jsonb saves me schema changes. A GIN index makes queries like metadata @> '{"lang":"en"}' fast. But anything I filter on in almost every query, like tenant_id, gets its own typed column and a B-tree index, because that's faster and clearer.
Experienced developer How would you reduce the compute and storage overhead of embeddings in PostgreSQL?
Model answer
Use fewer dimensions if the model allows it, since text-embedding-3 models accept a dimensions parameter. Store as halfvec instead of vector when the small precision loss is acceptable, which roughly halves the size. Index only the rows I search, using a partial index if one segment dominates. And check with EXPLAIN ANALYZE that the planner actually uses the index.
Scenario A query that filters by tenant and orders by created_at is slow. EXPLAIN ANALYZE shows a Seq Scan. What do you do?
Model answer
Create a composite B-tree index on (tenant_id, created_at DESC), run ANALYZE so the statistics are fresh, and check the plan again. I'd expect an Index Scan and a big drop in actual time.
Quick revision
Key points
- Allow-list vector in azure.extensions, then CREATE EXTENSION vector in each database that needs it.
- Pick types on purpose: uuid or bigint keys, text, jsonb, timestamptz, vector(n) or halfvec(n).
- B-tree for equality, ranges and sorting. GIN for jsonb and full-text. HNSW or IVFFlat for vectors.
- A vector index only helps when its operator class matches the query operator, such as vector_cosine_ops with <=>.
- EXPLAIN ANALYZE shows Seq Scan versus Index Scan and the real time taken.
Important terminology
- pgvector
- The PostgreSQL extension that adds the vector data type, distance operators and vector indexes. Its extension name is vector.
- azure.extensions
- The flexible server parameter that lists which extensions are allowed. An extension must be on this allow-list before CREATE EXTENSION works.
- vector(n)
- A pgvector column type holding n single-precision numbers, for example vector(1536) for text-embedding-3-small.
- halfvec
- A pgvector type that stores each number in half precision, roughly halving storage and index size.
- jsonb
- PostgreSQL's binary JSON type. It can be indexed with GIN and queried with operators such as @>.
- B-tree index
- The default PostgreSQL index, good for equality, ranges and sorting on normal columns.
- GIN index
- A generalised inverted index, used for jsonb containment, arrays and full-text search.
- EXPLAIN ANALYZE
- Runs a query and shows the real plan, including whether an index or a sequential scan was used and how long each step took.
Common mistakes
- Running CREATE EXTENSION vector before adding vector to azure.extensions.
- Declaring a column as vector with no dimensions, which can't be indexed.
- Building a cosine query (<=>) on top of an index created with vector_l2_ops, so the index is ignored.
Exam tips
- "Extension not allowed" error = add it to azure.extensions first.
- "Fast filter on a jsonb attribute" = GIN index.
- "Confirm the index is used" = EXPLAIN ANALYZE.
Five quick revision questions
-
1.What's the extension name for pgvector?Show
vector
-
2.Which index type suits jsonb containment queries?Show
GIN
-
3.Which type stores a time with its time zone?Show
timestamptz
-
4.What's the maximum number of dimensions you can index with a vector column using HNSW or IVFFlat?Show
2,000.
-
5.Which operator class goes with cosine distance?Show
vector_cosine_ops
Official references
Finished this lesson? Tick it off. Your progress is saved in this browser.
Next up: pgvector Similarity Search and RAG with Metadata Filters
Lesson done? Make it stick with a quick gameSort It, Match the Pairs, Lightning Round and Who Am I? Earn XP and badges.