Your profile

One profile for every MSDEVBUILD site. Only you can see it, and the site owner if you write in.

Lesson 15 of 28
❮Prev Next❯

PostgreSQL Schemas, Data Types and Indexes

Module 2: Data for AI ⏱ 11 min read Updated

Your note

My notes for this lesson

Select any text in the lesson to highlight it or add a note. Saved in this browser.

    No highlights yet. Select a sentence in the lesson, then pick a colour or add a note.

    All my bookmarks and notes

    Reading settings

    For every lesson, saved in this browser.

    Text size
    Line spacing
    Font

    With IaaS you rent the virtual machine. Microsoft looks after the building, power and hardware; you patch the operating system.

    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.

    Simulate it » No Azure account needed

    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.

    Azure portal: Allow pgvector, create the table and search Allow pgvector, then create the table and indexes.
    </> Embed

    Embed this simulation

    Free for trainers, teachers and bloggers. Paste this into your page:

    Loading the portal…

    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
    1. Extensions must be allow-listed first. Open Server parameters, find azure.extensions and tick VECTOR.
    2. Saved. Now open a terminal and create the extension in your database.
    3. vector(1536) holds one embedding. HNSW with vector_cosine_ops makes nearest-neighbour search fast; a normal index on tenant_id helps the filter.
    4. <=> is cosine distance: smaller means closer. Filter by tenant, order by distance, take the top 3.
    5. 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.

    😟 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
    🛠️ Solved with: Schema and indexes

    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:

    1. 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.)
    2. 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
    );
    TypeUse it forWhy
    uuid / bigintKeysuuid is safe to generate anywhere; bigint is smaller and sorts well
    textChunks, titlesNo length limit worries; use varchar(n) only when a limit is a real rule
    jsonbFlexible metadataIndexed with GIN, queried with @> and ->>
    timestamptzTimesStores an exact moment, so time zones don’t bite you later
    vector(1536)EmbeddingsFixed dimensions are required for indexing
    halfvec(1536)Embeddings, smallerHalf 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);
    IndexGood forNot good for
    B-tree (default)=, <, BETWEEN, ORDER BY on normal columnsjsonb contents, vectors
    GINjsonb @>, arrays, full-text tsvectorRange queries
    HNSWVector search, best speed versus recall; can be built on an empty tableVery large builds on small memory
    IVFFlatVector search with faster builds and less memoryBuilding 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:

    OperatorDistanceOperator class
    <->Euclidean (L2)vector_l2_ops
    <=>Cosine distancevector_cosine_ops
    <#>Negative inner productvector_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

    Retail

    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.
    Ready for more?The full lesson adds the technical explanation, when to use it, interview questions and revision notes.

    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.

    Question 1

    Question 1 of 5

    A developer runs CREATE EXTENSION vector on an Azure Database for PostgreSQL flexible server and receives an error stating that the extension is not allow-listed. What should the developer do first?

    Question 2

    Question 2 of 5

    A table stores document metadata in a jsonb column named metadata. Queries frequently use the condition metadata @> '{"lang": "en"}'. Which index type should you create on the metadata column?

    Question 3

    Question 3 of 5

    You create an HNSW index by using the vector_l2_ops operator class. Your application query orders results by embedding <=> @query_vector. EXPLAIN ANALYZE shows a sequential scan. What should you do?

    Question 4

    Question 4 of 5 · Select 2

    You are designing a PostgreSQL table to store document chunks and their embeddings from a model that returns 1,536 dimensions. Which TWO column definitions are appropriate?

    Question 5

    Question 5 of 5

    A developer adds an index to a slow query and wants to confirm that PostgreSQL now uses the index and to see the actual execution time. Which command should the developer run?

    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. 1.What's the extension name for pgvector?Show

      vector

    2. 2.Which index type suits jsonb containment queries?Show

      GIN

    3. 3.Which type stores a time with its time zone?Show

      timestamptz

    4. 4.What's the maximum number of dimensions you can index with a vector column using HNSW or IVFFlat?Show

      2,000.

    5. 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

    Studying with a friend? Send them this lesson

    It's free and needs no sign-up. Their progress saves in their own browser.

    Lesson done? Make it stick with a quick gameSort It, Match the Pairs, Lightning Round and Who Am I? Earn XP and badges. Play ❯

    Install MSDEVBUILD Azure

    Free · no account · works offline

    Save the whole course for offline ›

    Hi, I’m your Nimbus

    Your study buddy. Pick what we do next.

    MSDEVBUILD · Multi-Stack Dev Build

    Sign in to MSDEVBUILD

    One account for Azure certifications and the blog: sign in here and you are signed in on both. Your XP, streak, practice deck and certificate stay in sync on every device. Optional: everything works without an account.