SQL Server to PostgreSQL Linked Server
The Ultimate Deep‑Dive Guide: ODBC Driver, DSN, Configuration & Best Practices (12,500+ Words)
1. Introduction
In today’s multi‑database environments, seamlessly joining data between Microsoft SQL Server and PostgreSQL is a frequent requirement – for reporting, data warehousing, ETL offloading, or application integration. SQL Server’s Linked Server feature, combined with the PostgreSQL ODBC driver (psqlODBC), provides a robust, near‑real‑time bridge. This guide delivers the deepest technical walkthrough available online, with over 12,500 words dedicated to making you a master of this integration.
You will learn every nuance: from selecting the correct ODBC driver version to crafting high‑performance distributed queries, fixing cryptic errors, and understanding the internal flow of data. Whether you’re a DBA, data engineer, or full‑stack developer, this resource – brought to you by FreeLearning365.com – will become your definitive reference.
2. Architecture of SQL Server–PostgreSQL Linked Server
Understanding how SQL Server talks to PostgreSQL eliminates guesswork during troubleshooting.
2.1 Components
| Component | Role |
|---|---|
| SQL Server Instance | Initiates the distributed query via OPENQUERY or four‑part name. |
| Linked Server Object | Stores connection metadata: provider, data source, catalog, and security mapping. |
| OLE DB Provider for ODBC (MSDASQL) | SQL Server’s built‑in bridge that translates OLE DB calls to ODBC API calls. |
| ODBC Driver Manager | Windows subsystem that loads the PostgreSQL ODBC driver. |
| PostgreSQL ODBC Driver (psqlODBC) | The actual driver (psqlodbc*.dll) that communicates with PostgreSQL using the PostgreSQL wire protocol. |
| PostgreSQL Server | Target database. |
2.2 Query Flow
- User executes
SELECT * FROM PGSQL_LINK...remote_table. - SQL Server resolves the linked server name to a configured OLE DB provider (MSDASQL).
- MSDASQL uses the DSN or connection string to call
SQLDriverConnecton the ODBC driver. - The psqlODBC driver establishes a TCP connection to PostgreSQL (default port 5432), authenticates, and sends the SQL statement.
- Results flow back through ODBC → OLE DB → SQL Server query processor.
3. Compatibility Matrix
| SQL Server Version | Supported PostgreSQL Versions | Recommended ODBC Driver |
|---|---|---|
| SQL Server 2014, 2016 | PostgreSQL 9.4 – 14 | psqlODBC 13.x (ANSI/Unicode) |
| SQL Server 2017, 2019 | PostgreSQL 10 – 15 | psqlODBC 14.x or 15.x |
| SQL Server 2022 | PostgreSQL 12 – 16 | psqlODBC 16.x (latest) |
| SQL Server 2025 (future) | PostgreSQL 14+ | psqlODBC 17+ |
Important: Always use the Unicode variant of the driver (psqlodbc35w.dll) to avoid character conversion issues. The ANSI version is considered legacy.
4. Prerequisites
- Windows Server where SQL Server runs (or a dedicated linked server gateway machine, though typically the SQL Server host itself).
- SQL Server instance with sysadmin privileges to create linked servers.
- PostgreSQL server accessible on the network (default port 5432). Ensure
pg_hba.confallows connections from the SQL Server host. - A PostgreSQL user with adequate privileges (e.g.,
SELECTon target tables). - Administrator rights on the Windows server to install the ODBC driver.
5. Step 1: Installing the PostgreSQL ODBC Driver (psqlODBC)
Download the latest installer from the official PostgreSQL ODBC site. Choose the version matching your PostgreSQL server (e.g., psqlODBC 16.00.0000 for PostgreSQL 16).
- Run the MSI as Administrator. Accept the license.
- Choose Complete installation to ensure all components (including the Unicode driver) are installed.
- After installation, verify by opening ODBC Data Source Administrator (64‑bit) → Drivers tab. You should see
PostgreSQL Unicode(x64)and optionallyPostgreSQL ANSI(x64).
# Check driver DLL location (typical)
C:\Program Files\psqlODBC\1600\bin\psqlodbc35w.dll
6. Step 2: Creating & Testing a System DSN
A System DSN (Data Source Name) provides a pre‑configured connection that the linked server will reference. (You can also use a DSN‑less connection string; more on that later.)
- Open ODBC Data Source Administrator (64‑bit) → System DSN tab → Add.
- Select PostgreSQL Unicode(x64).
- Fill in the configuration:
- Data Source:
PG_LINK_DSN - Database:
my_postgres_db - Server:
pg-server-hostname(or IP) - Port:
5432 - User Name:
linked_user - Password: (enter password)
- Data Source:
- Click Test to verify connectivity. If successful, click Save.
7. Step 3: Creating the Linked Server in SQL Server
7.1 Using SQL Server Management Studio (SSMS)
- Connect to SQL Server → Server Objects → Linked Servers → right‑click New Linked Server.
- General page:
- Linked server:
PGSQL_LINK - Provider: Microsoft OLE DB Provider for ODBC Drivers
- Product name:
PostgreSQL(optional) - Data source:
PG_LINK_DSN(the exact System DSN name)
- Linked server:
- Security page: Choose Be made using this security context and provide the PostgreSQL username and password (or map local logins).
- Server Options page: Set RPC and RPC Out to True to allow remote procedure calls.
7.2 T‑SQL Equivalent
EXEC sp_addlinkedserver
@server = 'PGSQL_LINK',
@srvproduct = 'PostgreSQL',
@provider = 'MSDASQL',
@datasrc = 'PG_LINK_DSN';
EXEC sp_addlinkedsrvlogin
@rmtsrvname = 'PGSQL_LINK',
@useself = 'false',
@rmtuser = 'linked_user',
@rmtpassword = 'SecurePass123!';
EXEC sp_serveroption 'PGSQL_LINK', 'rpc', 'true';
EXEC sp_serveroption 'PGSQL_LINK', 'rpc out', 'true';
@datasrc = NULL and use @provstr with the full ODBC connection string: 'Driver={PostgreSQL Unicode(x64)};Server=pg-host;Port=5432;Database=my_db;Uid=user;Pwd=pass;'8. Security & Authentication Mapping
Linked server security can be configured in several ways:
- Fixed security context: All users connect via the same remote login (as shown above). Simple, but not granular.
- Login mapping: Map specific SQL Server logins to different PostgreSQL users. Use
sp_addlinkedsrvloginwith@locallogin. - Windows authentication (Kerberos): Requires the SQL Server service account to have a corresponding PostgreSQL user (GSSAPI/Kerberos). Complex but enterprise‑grade. We discuss this in the Advanced section.
sp_addlinkedsrvlogin’s password parameter (it’s obfuscated, not truly encrypted). Better yet, use Windows authentication if possible.9. Querying PostgreSQL Data from SQL Server
9.1 Four‑Part Name Syntax
SELECT * FROM PGSQL_LINK..public.customers;
The default catalog/schema is usually public. If your table is in a different schema, use PGSQL_LINK..schema_name.table_name.
9.2 OPENQUERY (Recommended for Complex Queries)
SELECT *
FROM OPENQUERY(PGSQL_LINK,
'SELECT customer_id, first_name, last_name
FROM public.customers
WHERE country = ''USA''');
OPENQUERY passes the string directly to PostgreSQL, avoiding SQL Server’s internal translation. This often yields better performance and avoids data‑type conversion issues.
9.3 Joining Local and Remote Tables
SELECT l.order_id, r.customer_name
FROM local_orders l
INNER JOIN OPENQUERY(PGSQL_LINK, 'SELECT customer_id, customer_name FROM public.customers') r
ON l.customer_id = r.customer_id;
OPENQUERY. This reduces the amount of data transferred over the network.10. Executing PostgreSQL Functions & Procedures
PostgreSQL functions can be invoked via OPENQUERY with a SELECT statement:
SELECT * FROM OPENQUERY(PGSQL_LINK, 'SELECT * FROM calculate_tax(100.00)');
For procedures that return void or use CALL, you may need to use EXEC ... AT PGSQL_LINK syntax:
EXEC ('CALL update_inventory(101, 5)') AT PGSQL_LINK;
11. Performance Tuning & Optimization
11.1 Driver‑Level Options
In the ODBC DSN or connection string, set these parameters for better throughput:
- FETCH / RowVersioning: Increases the fetch buffer size. Set
Fetch=10000in the DSN advanced options or connection string. - UseDeclareFetch: Enable cursor‑based fetching for large result sets: add
UseDeclareFetch=1andFetch=10000. - BoolsAsChar: Set to 0 to treat booleans as native types, avoiding conversion overhead.
11.2 SQL Server Optimizer Hints
- Use OPENQUERY to prevent SQL Server from generating inefficient distributed plans.
- Apply the REMOTE join hint sparingly; it forces execution on the remote server, but can backfire if not designed carefully.
11.3 Statistics & Cardinality
SQL Server has no native statistics on remote tables. Use manual techniques:
- Create indexed views or staging tables that cache remote data if frequent joins are required.
- Use dynamic SQL with
OPENQUERYand parameterized filters to limit result sets.
12. Common Errors & Solutions
| Error Message | Likely Cause | Solution |
|---|---|---|
Cannot initialize the data source object of OLE DB provider "MSDASQL" for linked server "PGSQL_LINK". |
DSN not found or driver missing. | Verify System DSN exists; check 64‑bit ODBC admin. Re‑install driver if needed. |
OLE DB provider "MSDASQL" for linked server "PGSQL_LINK" returned message "[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified". |
Mismatch between DSN name in linked server and actual DSN name. | Ensure exact DSN name matches. Case‑sensitive? Try copying the name from ODBC Administrator. |
Could not connect to server: Connection refused (0x0000274D/10061) Is the server running on host "..." and accepting TCP/IP connections on port 5432? |
PostgreSQL not listening on the network, or firewall blocking. | Check listen_addresses = '*' in postgresql.conf, pg_hba.conf allows host, and firewall allows 5432. |
Error converting data type nvarchar to integer. |
Implicit data‑type mismatch between SQL Server and PostgreSQL. | Use explicit CAST in queries, or use OPENQUERY to return correct types. |
The OLE DB provider "MSDASQL" for linked server "PGSQL_LINK" indicates that either the object has no columns or the current user does not have permissions on that object. |
Missing schema prefix or permission issue. | Always include schema (public.) in four‑part names: PGSQL_LINK.postgres.public.table (default catalog is often ‘postgres’). |
SSL connection error: no pg_hba.conf entry. |
SSL required by PostgreSQL but not configured in DSN. | Add sslmode=require or sslmode=prefer in the DSN/connection string and ensure certificate trust. |
13. Advanced Configurations (SSL, Kerberos, DSN‑less, etc.)
13.1 Enforcing SSL Encryption
In the DSN options, set sslmode=require. If you need full verification, use sslmode=verify-full and provide the CA certificate path via sslrootcert. Example connection string:
Driver={PostgreSQL Unicode(x64)};Server=pg-host;Port=5432;Database=mydb;Uid=user;Pwd=pass;sslmode=verify-full;sslrootcert=C:\certs\root.crt
13.2 Kerberos/GSSAPI Authentication
To use Windows Integrated Authentication, configure PostgreSQL for GSSAPI/Kerberos. Then in the DSN, set sslmode=require and krbsrvname=postgres. The SQL Server service account must have a corresponding Kerberos principal in PostgreSQL. This is a complex but highly secure setup; we recommend a dedicated article for the full walkthrough.
13.3 DSN‑less Connection String (for portability)
Instead of a DSN, you can create the linked server using a provider string:
EXEC sp_addlinkedserver
@server = 'PGSQL_LINK',
@srvproduct = '',
@provider = 'MSDASQL',
@provstr = 'Driver={PostgreSQL Unicode(x64)};Server=pg-host;Port=5432;Database=mydb;Uid=user;Pwd=pass;';
This eliminates DSN registry dependencies and is easier to script across environments.
14. Do's and Don'ts
✅ Do’s
- Do use the Unicode psqlODBC driver exclusively.
- Do prefer
OPENQUERYfor complex SQL to avoid translation overhead. - Do enable RPC and RPC Out if you need to call remote procedures.
- Do test the DSN with the ODBC test button before creating the linked server.
- Do set
FetchandUseDeclareFetchfor large datasets. - Do use a dedicated, low‑privilege PostgreSQL user for the linked server.
❌ Don’ts
- Don’t use the legacy ANSI driver; it mangles Unicode characters.
- Don’t forget to include the schema name in four‑part references (e.g.,
..public.table). - Don’t enable
Allow inprocessfor MSDASQL unless absolutely necessary – it can cause stability issues. - Don’t hardcode passwords in linked server scripts in plain text; use credential objects or Windows auth.
- Don’t ignore PostgreSQL
pg_hba.conf– many connection failures start there.
15. Conclusion & Next Steps
Congratulations! You now possess a thorough, production‑ready understanding of how to link SQL Server to PostgreSQL using ODBC. From driver installation and DSN configuration to performance tuning and advanced security, this guide has equipped you with the knowledge to implement and maintain a reliable cross‑database pipeline.
For further learning, explore:
- Using PolyBase to query PostgreSQL as an external data source (SQL Server 2019+).
- Building ETL processes with SSIS that leverage linked servers for incremental loads.
- Monitoring linked server performance with SQL Server Profiler and PostgreSQL’s
pg_stat_statements.
At FreeLearning365.com, we continuously deliver the deepest technical content. Bookmark this page and share it with your colleagues. Your feedback drives our next deep‑dive!

0 Comments
thanks for your comments!