Home › Studies › AI-200 › AI Data Services › PostgreSQL & pgvector

PostgreSQL & pgvector

psycopg and Entra tokens · vector(n) columns · IVFFlat, HNSW, DiskANN · compute and storage · embeddings and RAG · PgBouncer

By the tools4free.dev team · Last reviewed November 13, 2026

Practice questions for this topic →

Connect and query from Python

Microsoft's Python quickstart for Azure Database for PostgreSQL flexible server shows two authentication methods: Microsoft Entra authentication (the Passwordless tab) and PostgreSQL authentication (the Password tab).

Microsoft Entra (passwordless)PostgreSQL (password)
IdentityIdentities defined in Microsoft Entra IDAccounts stored in PostgreSQL
Python packages in the quickstartazure-identity (and azure-keyvault-secrets if you use Key Vault)psycopg, installed as "psycopg[binary]"
Server prerequisiteEntra authentication configured, and you are a Microsoft Entra administrator on the serverA PostgreSQL account (the quickstart uses the administrator login and its password)
How the password is obtainedcredential = DefaultAzureCredential(), then credential.get_token("https://ossrdbms-aad.database.windows.net/.default").token is used as the passwordThe DBPASSWORD environment variable
UpkeepTokens have a limited lifetime (24 hours by default): implement a token refresh policyYou manage the rotation of the passwords yourself

The quickstart's get_conn.py is demonstration code: it creates DefaultAzureCredential() on every call and has no token refresh. Production code needs both a reused credential and a refresh policy.

Schemas, data types and extensions

Enable the extensions

  1. Allowlist the extension in the azure.extensions server parameter (portal Parameters pane or az postgres flexible-server parameter set).
  2. Check with SHOW azure.extensions;.
  3. Connect to the target database and run CREATE EXTENSION vector;. Repeat for every database that needs it.

The community calls it pgvector, but the extension and binary are named vector. That is the name you allowlist and create. pg_diskann depends on vector: allow and create vector first, or run CREATE EXTENSION IF NOT EXISTS pg_diskann CASCADE;. The semantic-search tutorial also allowlists and creates azure_ai.

Index types and query tuning

Without an index, pgvector does an exact search (perfect recall, slower). An approximate nearest neighbor (ANN) index trades recall for speed. Load data before you build the index.

IndexBuild and memoryKey options (defaults)Query-time setting
IVFFlat (ivfflat)Faster build, less memory than HNSW; lower speed-recall tradeoff. Uses k-means lists, so it needs data firstlists (set at create)ivfflat.probes
HNSW (hnsw)Slower build, more memory than IVFFlat; better speed-recall tradeoff; no training step, so it can be built on an empty tablem (16), ef_construction (64)hnsw.ef_search (40)
DiskANN (diskann)Balance of high accuracy and fast build; no training step; Flexible Server onlymax_neighbors (32), l_value_ib (50 on the tuning page, 100 on the DiskANN page: the pages differ)diskann.l_value_is
DistanceOperatorIndex operator class
Cosine<=>vector_cosine_ops
L2 (Euclidean)<->vector_l2_ops
Inner product (the operator gives the negative inner product)<#>vector_ip_ops

The query must use the operator that matches the index's operator class, or the planner does not consider the index.

Tuning rules from Microsoft's page

Compute, memory and storage

TierPage's descriptionUse for
BurstableCPU credit model: credits build below baseline and are used above itWorkloads that do not need full CPU continuously. The page calls it not recommended for production; no PgBouncer
General PurposeBalance between CPU and memory with scalable I/O throughputMost production workloads
Memory OptimizedIn-memory performance for faster transaction processing and higher concurrencyHigh-performance, high-concurrency workloads
Premium SSD v2Premium SSD
SizesAny size from 1 GiB to 64 TiB, adjustable in 1 GiB stepsDedicated sizes
Max disk size65,536 GiB32,767 GiB
Max throughput1,200 MB/s900 MB/s
Max IOPS80,00020,000
Host cachingNot supported-
Performance tuningCapacity, throughput and IOPS adjustable independently at any time-

Vector search and RAG

Vector similarity compares embeddings with a distance metric such as Euclidean distance or cosine similarity. The retrieval half of retrieval-augmented generation (RAG) is a nearest-neighbor query over stored embeddings.

  1. Create a vector column for each searched field (ALTER TABLE recipes ADD COLUMN embedding vector(1536);).
  2. Generate embeddings with the azure_ai extension, for example azure_openai.create_embeddings('text-embedding-ada-002', ...), and store them.
  3. Generate the embedding for the user's query.
  4. Search the vector column for the nearest neighbors: the tutorial's search function orders by the cosine distance (embedding <=> query_embedding) ascending and applies a limit.
  5. Rank further with a relevance or ranking model; without one, rank by decreasing dot product.

Connection optimization with PgBouncer

Postgres uses a process-based model for connections, so many idle connections are expensive. Built-in PgBouncer pools them. It runs on the same VM as the server and uses a server connection only inside an open transaction or while a query is active.

ItemValue
Port6432 (regular PostgreSQL port is 5432); same host name
EnableSet pgbouncer.enabled to true on the Parameters pane; no server restart needed. The same page also says PgBouncer is enabled by default on port 6432: Microsoft's page is not consistent, so follow the parameter.
TiersGeneral Purpose and Memory Optimized; not Burstable
Default pool modetransaction
pgbouncer.default_pool_size50 per user/database pair
pgbouncer.max_client_conn5000
pgbouncer.query_wait_timeout120 seconds
pgbouncer.server_idle_timeout600 seconds
ScaleUp to 10,000 connections with low overhead
Pooling modeServer connection is held for
SessionThe whole client connection
TransactionOne transaction (default in the built-in PgBouncer)
StatementOne statement; multi-statement transactions are not supported

CLI and PowerShell

TaskAzure CLIPowerShell
Allowlist an extensionaz postgres flexible-server parameter set --resource-group <resource_group> --server-name <server> --name azure.extensions --value "<extension_name>,<extension_name>"SHOW azure.extensions;
Install pgvector in a database-CREATE EXTENSION vector;
Install DiskANN with its dependency-CREATE EXTENSION IF NOT EXISTS pg_diskann CASCADE;
Connect with psycopg-conn = psycopg.connect(conn_string)
Insert with parameters-cursor.execute("INSERT INTO inventory (name, quantity) VALUES (%s, %s);", ("banana", 150))
Add an embedding column-ALTER TABLE recipes ADD COLUMN embedding vector(1536);
Create an IVFFlat cosine index-CREATE INDEX t_test_embedding_cosine_idx ON t_test USING ivfflat (embedding vector_cosine_ops) WITH (lists = 5000);
Set IVFFlat probes-SET ivfflat.probes = 10;
Set HNSW candidate list for search-SET hnsw.ef_search = 100;
Force a DiskANN index scan-SET LOCAL enable_seqscan TO OFF;
Make a full-disk server writable-SET SESSION CHARACTERISTICS AS TRANSACTION READ WRITE;

Exam Tips

Tick each tip once you can answer it without looking.

“Python app must reach Azure Database for PostgreSQL without storing a password” → Microsoft Entra authentication: DefaultAzureCredential, get_token("https://ossrdbms-aad.database.windows.net/.default"), token as the password. Trap: The token lifetime is limited (24 hours by default), so production code needs a token refresh policy. The server also needs Entra authentication configured and you as an Entra admin.

“Install a PostgreSQL driver for the password-based Python quickstart” → psycopg ("psycopg[binary]"). Trap: azure-identity is the package for the passwordless (Entra) path.

“Name to allowlist and create for pgvector” → vector, allowed in azure.extensions, then CREATE EXTENSION vector; in each database. Trap: pgvector is only the community name. Allowlisting alone does not install it; the CREATE is per database.

“Column must be indexable with ivfflat or hnsw” → Declare dimensions, vector(n), with n at most 2000. Trap: A plain vector column or one above 2000 dimensions cannot be indexed; storing it is still allowed.

“Embeddings with more than 2000 dimensions need an index” → DiskANN with product quantization on (pg_diskann v0.6+, up to 16,000 dimensions), or reduce dimensionality. Trap: Product quantization is labelled Preview on its page. ivfflat and hnsw stop at 2000.

“Index with no training step that can be built on an empty table” → HNSW (also DiskANN). Trap: IVFFlat uses k-means lists, so build it after the data is loaded.

“Fastest build and least memory, accepting lower speed-recall” → IVFFlat. Trap: HNSW builds slower and uses more memory but has the better speed-recall tradeoff.

“Cosine search must use the index” → vector_cosine_ops index and the <=> operator in ORDER BY. Trap: <-> is L2 (vector_l2_ops) and <#> is inner product (vector_ip_ops); a mismatch means the index is not considered.

“Better recall from an IVFFlat index at query time” → Raise ivfflat.probes (per connection or SET LOCAL). Trap: More probes cost speed. Probes equal to the list count is an exact search that skips the index.

“Better recall from an HNSW index at query time” → Raise hnsw.ef_search (default 40). Trap: m and ef_construction are build-time options, fixed at CREATE INDEX.

“Query is slow: first step” → Read the plan with EXPLAIN (ANALYZE, VERBOSE, BUFFERS): parallel? index used? partitions pruned?. Trap: Do not add indexes blindly. A partial index is used only when the query's WHERE matches its definition.

“Force a DiskANN index scan in one transaction” → SET LOCAL enable_seqscan TO OFF; inside a transaction. Trap: A session-level SET affects later statements; SET LOCAL ends at COMMIT or ROLLBACK.

“Server went read-only because the disk is almost full (95 percent or under 5 GiB free)” → Scale storage up (storage can only grow) or enable autogrow, delete data after SET SESSION CHARACTERISTICS AS TRANSACTION READ WRITE;. Trap: You cannot scale storage down, and Premium SSD v2 autogrow is public preview.

“Dev or test server with idle periods; risk of CPU credits running out” → Burstable tier; watch CPU Credits Remaining. Trap: Page: not recommended for production. Burstable has no built-in PgBouncer.

“Tune IOPS, throughput and size of the disk independently, any size from 1 GiB” → Premium SSD v2. Trap: Premium SSD has dedicated sizes; v2 has no host caching.

“Too many idle or short-lived connections hurt the server” → Built-in PgBouncer: pgbouncer.enabled = true, connect on port 6432. Trap: Port 5432 is the regular PostgreSQL port, not PgBouncer. PgBouncer is not supported on Burstable. Statement mode cannot be used with prepared statements.

“Backfill thousands of embeddings with azure_openai.create_embeddings” → Update in chunks with a modest LIMIT and repeat until no rows remain. Trap: A very large batch can be throttled by Azure OpenAI and fail halfway through.

“Similarity search limited to one customer tier” → WHERE on the metadata column, backed by a partial index with the same WHERE or by partitioning. Trap: A WHERE form that differs from the partial index definition (for example LIKE) means the index is not used.

Sources

Checked against Microsoft Learn on November 13, 2026.

← Cosmos DB for NoSQL & VectorsAzure Managed Redis →