Connect to and Query Azure Database for PostgreSQL
30-second answer
You connect to Azure Database for PostgreSQL flexible server from Python with psycopg (version 3). Instead of a stored password, you get a Microsoft Entra token from DefaultAzureCredential for the scope https://ossrdbms-aad.database.windows.net/.default and pass it as the password, with your Entra user or managed identity name as the user and sslmode=require. Then you run SQL with parameterised queries (%s placeholders), never by pasting user input into the SQL string.
Exam objective: 2.2.1 Connect and query Azure Database for PostgreSQL by using SDKs. (Skills measured as of October 7, 2026)
Simulations
Feel it before you read it. No account needed, nothing leaves this page.
Search for <strong>postgres</strong> in the top bar.
👆 Click the glowing item in the portal to continue
Read the steps as text
- Search for postgres in the top bar.
- Type postgres and pick Azure Database for PostgreSQL flexible servers under Services.
- Select + Create.
- Pick Microsoft Entra authentication only: no database password to leak. Set yourself as the Entra admin.
- For a lab, public access with your own IP is fine. Production apps usually use private access in a VNet.
- Review and Create. It takes about five minutes.
- Connect with an Entra access token as the password. Your Python app does the same with DefaultAzureCredential.
🧪 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
Your Python app stores the database password in plain text.
😊 THE SOLUTION
Connect with psycopg and a Microsoft Entra token instead.
- Passwords in config✓ Entra ID tokens
- SQL injection✓ Parameterised queries
- Connection per request✓ A connection pool
Start with a question
Your app needs to read from a database. Do you really have to paste the database password into a config file?
Think about a staff canteen. Some offices hand out a paper coupon that anyone can copy. Others let you tap your ID card, and the card only works while you still work there.
A database password in config.py is the paper coupon. It gets committed to git, pasted into Teams and left on old laptops. Microsoft Entra authentication is the ID card: your app proves who it is, gets a short-lived token, and uses that as the password. Nobody has a secret to leak.
This lesson shows how a Python app connects to Azure Database for PostgreSQL that way and then runs queries safely.
Explain it like I’m 10
The technical explanation
Azure Database for PostgreSQL flexible server is managed PostgreSQL. Microsoft patches it, backs it up and can run a standby for high availability. You still write normal SQL and use normal PostgreSQL drivers. For Python that’s psycopg version 3:
pip install "psycopg[binary]" psycopg_pool azure-identity
What a connection needs
| Setting | Example | Notes |
|---|---|---|
host | contoso-pg.postgres.database.azure.com | From the server’s Overview page |
port | 5432 | 6432 if you go through the built-in PgBouncer |
dbname | support | A database on the server |
user | rag-api (an Entra identity) or pgadmin | The role name in PostgreSQL |
password | an Entra token, or a database password | Token preferred |
sslmode | require | Refuses to connect without TLS |
Passwordless sign-in with Microsoft Entra ID
Two things have to be set up on the server first. The server’s authentication must allow Microsoft Entra (the portal option is “Microsoft Entra authentication only” or “PostgreSQL and Microsoft Entra authentication”). And an Entra admin must create a database role for your user, group or managed identity.
Then your code asks for a token and uses it as the password:
import os
import psycopg
from azure.identity import DefaultAzureCredential
credential = DefaultAzureCredential()
def get_token() -> str:
# Token for Azure Database for PostgreSQL
return credential.get_token("https://ossrdbms-aad.database.windows.net/.default").token
conn = psycopg.connect(
host=os.environ["PGHOST"], # contoso-pg.postgres.database.azure.com
dbname=os.environ["PGDATABASE"], # support
user=os.environ["PGUSER"], # rag-api (the managed identity's role name)
password=get_token(),
port=5432,
sslmode="require",
)
DefaultAzureCredential uses your az login session on your laptop and the app’s managed identity in App Service, Container Apps or Functions. Same code, no secret.
The token is checked only when a connection opens. An open connection keeps working after the token expires, but any new connection needs a fresh token. That matters once you add a pool, which you’ll see below and in the performance lesson.
Running queries safely
tenant = "contoso"
search = "refund"
with conn: # commits on success, rolls back on error
with conn.cursor() as cur:
cur.execute(
"SELECT id, title FROM docs WHERE tenant_id = %s AND title ILIKE %s LIMIT 10",
(tenant, f"%{search}%"), # values travel separately from the SQL
)
for row in cur.fetchall():
print(row)
cur.execute(
"INSERT INTO docs (tenant_id, title, body) VALUES (%(t)s, %(title)s, %(body)s) RETURNING id",
{"t": tenant, "title": "Refund policy", "body": "Refunds within 30 days..."},
)
new_id = cur.fetchone()[0]
The %s and %(name)s placeholders are the whole point. psycopg sends the SQL text and the values separately, so a value like '; DROP TABLE docs; -- is just a strange title, not a command. This is called a parameterised query, and it’s the answer to SQL injection.
For many rows at once, cur.executemany(sql, rows) reuses the same statement, and cur.copy() with COPY ... FROM STDIN is the fastest way to bulk-load, which you’ll want when loading thousands of embeddings.
Reusing connections
Opening a PostgreSQL connection costs a TLS handshake, sign-in and a new server process. A web API that opens one per request spends more time connecting than querying. Use a pool, and give it a connection class that gets a fresh token every time it opens a connection:
from psycopg_pool import ConnectionPool
class EntraConnection(psycopg.Connection):
@classmethod
def connect(cls, conninfo="", **kwargs):
kwargs["password"] = get_token() # fresh token for every new connection
return super().connect(conninfo, **kwargs)
pool = ConnectionPool(
conninfo=f"host={os.environ['PGHOST']} dbname=support user=rag-api sslmode=require",
connection_class=EntraConnection,
min_size=2, max_size=10,
)
with pool.connection() as conn:
print(conn.execute("SELECT version()").fetchone())
-
1 Get a token
DefaultAzureCredential asks Entra ID for the ossrdbms-aad scope.
-
2 Connect
psycopg opens a TLS connection with the token as the password.
-
3 Map the role
PostgreSQL matches the Entra identity to a database role.
-
4 Query
Parameterised SQL runs, and rows come back.
Architect level Network access decides whether you can connect at all
Flexible server has two networking models, chosen at creation. Public access gives the server a public endpoint protected by firewall rules (and you can add private endpoints). Private access (VNet integration) puts the server inside a delegated subnet with no public endpoint, and your app must reach that VNet. If the connection times out, it’s almost always networking. If it’s refused with “password authentication failed”, it’s the token, the user name or a missing role. Knowing which error means what saves a lot of time.
Real-world business scenario
Fabrikam Insurance (fictional)
- The problem
- A claims assistant built in Python read policy documents from PostgreSQL using a shared admin password stored in an app setting. A contractor copied it into a test script that later ended up in a public repository.
- What they used
- Azure Database for PostgreSQL flexible server with Microsoft Entra authentication, a managed identity for the API, psycopg 3 with parameterised queries and a pool that fetches a fresh token per connection.
- Why that choice
- There's no password to copy any more, and access is removed by deleting the database role or the identity. Parameterised queries close the injection hole the security review flagged.
- The result
- The shared password was retired, and the security team can see exactly which identity ran each session in the server logs.
When to use it and when not to
✓ Use it when…
- Your app runs in Azure (App Service, Container Apps, Functions, AKS) and can use a managed identity.
- You want access controlled by Entra users and groups instead of database passwords.
- You run any query that includes user input. Parameterise it every time.
✕ Think twice when…
- An old tool that only accepts a short password field and can't take a token. Use a database password stored in Key Vault for that one tool.
- Opening a new connection for every request in a busy API. Use a pool or PgBouncer.
↔ Alternatives to consider
- PostgreSQL password authentication with the secret in Azure Key Vault, when Entra isn't possible.
- Azure Cosmos DB for NoSQL when your data is JSON documents and you want global scale without SQL joins.
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 do you need to connect a Python app to Azure Database for PostgreSQL?
Model answer
The server host name (something like myserver.postgres.database.azure.com), the database name, a user, a password or token, port 5432 and TLS. In Python I use psycopg 3. For the password I prefer a Microsoft Entra token from DefaultAzureCredential, so there's no secret in my config.
Interviewer follows up
What is the user name when you sign in with a managed identity?
You
It's the name of the Entra principal that was mapped to a database role, for example the managed identity's name. An Entra admin creates that role first.
Intermediate Why do you pass values with %s instead of building the SQL string with an f-string?
Model answer
Because an f-string mixes data into the SQL text. If a user types something like a quote and a DROP TABLE, it becomes part of the query. With %s, psycopg sends the values separately from the SQL, so input is always treated as data. It's the fix for SQL injection.
Experienced developer Entra tokens expire. How do you stop a long-running app from failing an hour after it starts?
Model answer
The token only matters when a connection is opened, so I fetch a fresh token every time a new connection is made. With psycopg_pool I give the pool a small connection class whose connect method asks DefaultAzureCredential for a token, and I keep max_lifetime under the token lifetime. Open connections stay valid; new ones get new tokens.
Scenario Your app connects fine from your laptop but times out from a new App Service. What would you check first?
Model answer
Networking. With public access I'd check the server firewall rules allow the App Service outbound IPs or Azure services. With private access I'd check the App Service has VNet integration into a subnet that can reach the server and that private DNS resolves the host name. A timeout usually means network, while a wrong token gives an authentication error.
Quick revision
Key points
- Use psycopg 3 (import psycopg) with host, dbname, user, password, port 5432 and sslmode=require.
- For passwordless sign-in, DefaultAzureCredential gets a token for
https://ossrdbms-aad.database.windows.net/.defaultand you pass it as the password. - An Entra admin on the server must create a database role for each Entra user, group or managed identity.
- Always use %s placeholders and pass values as a tuple or dict. Never format user input into SQL.
- Use with blocks so connections commit or roll back and close cleanly.
Important terminology
- Azure Database for PostgreSQL flexible server
- The managed PostgreSQL service on Azure, where Microsoft runs patching, backups and high availability while you choose compute and storage.
- psycopg
- The most used PostgreSQL driver for Python. Version 3 is imported as psycopg and adds a separate psycopg_pool package for pooling.
- Microsoft Entra authentication
- Signing in to PostgreSQL with an Entra access token as the password instead of a database password.
- ossrdbms-aad scope
- The token scope
https://ossrdbms-aad.database.windows.net/.defaultused to request tokens for Azure Database for PostgreSQL. - sslmode=require
- A connection setting that makes the client refuse to connect without TLS encryption.
- Parameterised query
- SQL with placeholders such as %s, where the driver sends the values separately so user input can't change the query.
Common mistakes
- Building SQL with f-strings or + from user input, which opens the door to SQL injection.
- Fetching one token at start-up and reusing it for every new connection after it has expired.
- Leaving sslmode out and assuming the client will always pick TLS.
Exam tips
- "Connect without storing a password" = Microsoft Entra token from DefaultAzureCredential used as the password.
- "Token scope for PostgreSQL" =
https://ossrdbms-aad.database.windows.net/.default. - "Prevent SQL injection" = parameterised queries (%s placeholders), not string formatting.
Five quick revision questions
-
1.Which Python driver is used in the samples for PostgreSQL?Show
psycopg (version 3).
-
2.What scope do you request a token for?Show
https://ossrdbms-aad.database.windows.net/.default -
3.Where does the token go in the connection?Show
In the password field.
-
4.Which setting forces TLS?Show
sslmode=require.
-
5.What's the default PostgreSQL port?Show
5432 (PgBouncer uses 6432).
Official references
Finished this lesson? Tick it off. Your progress is saved in this browser.
Next up: PostgreSQL Schemas, Data Types and Indexes
Lesson done? Make it stick with a quick gameSort It, Match the Pairs, Lightning Round and Who Am I? Earn XP and badges.