SQL Server to PostgreSQL Linked Server: Ultimate Step‑by‑Step Guide | FreeLearning365

SQL Server to PostgreSQL Linked Server: Ultimate Step‑by‑Step Guide | FreeLearning365

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.

💡 Tip: Bookmark this page! It’s structured as a step‑by‑step lab. Follow along and you’ll have a working SQL Server–PostgreSQL linked server in under two hours.

2. Architecture of SQL Server–PostgreSQL Linked Server

Understanding how SQL Server talks to PostgreSQL eliminates guesswork during troubleshooting.

2.1 Components

ComponentRole
SQL Server InstanceInitiates the distributed query via OPENQUERY or four‑part name.
Linked Server ObjectStores 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 ManagerWindows 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 ServerTarget database.

2.2 Query Flow

  1. User executes SELECT * FROM PGSQL_LINK...remote_table.
  2. SQL Server resolves the linked server name to a configured OLE DB provider (MSDASQL).
  3. MSDASQL uses the DSN or connection string to call SQLDriverConnect on the ODBC driver.
  4. The psqlODBC driver establishes a TCP connection to PostgreSQL (default port 5432), authenticates, and sends the SQL statement.
  5. Results flow back through ODBC → OLE DB → SQL Server query processor.
📌 Note: The ODBC driver and SQL Server must be of the same bitness (64‑bit). A 32‑bit SQL Server cannot use a 64‑bit ODBC driver directly.

3. Compatibility Matrix

SQL Server VersionSupported PostgreSQL VersionsRecommended ODBC Driver
SQL Server 2014, 2016PostgreSQL 9.4 – 14psqlODBC 13.x (ANSI/Unicode)
SQL Server 2017, 2019PostgreSQL 10 – 15psqlODBC 14.x or 15.x
SQL Server 2022PostgreSQL 12 – 16psqlODBC 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.

⚠️ Warning: Do not use the ancient “PostgreSQL OLE DB Provider” (PGNP). It is deprecated and unstable. Microsoft’s MSDASQL with a modern ODBC driver is the only supported path.

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.conf allows connections from the SQL Server host.
  • A PostgreSQL user with adequate privileges (e.g., SELECT on 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).

  1. Run the MSI as Administrator. Accept the license.
  2. Choose Complete installation to ensure all components (including the Unicode driver) are installed.
  3. After installation, verify by opening ODBC Data Source Administrator (64‑bit) → Drivers tab. You should see PostgreSQL Unicode(x64) and optionally PostgreSQL ANSI(x64).
# Check driver DLL location (typical)
C:\Program Files\psqlODBC\1600\bin\psqlodbc35w.dll
⭐ Best Practice: Always install the Unicode driver. Ensure the driver architecture matches SQL Server – for 64‑bit SQL Server, install the 64‑bit psqlODBC.

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

  1. Open ODBC Data Source Administrator (64‑bit) → System DSN tab → Add.
  2. Select PostgreSQL Unicode(x64).
  3. 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)
  4. Click Test to verify connectivity. If successful, click Save.
💡 Tip: For production, consider using a File DSN or a DSN‑less connection string to avoid registry dependency. However, System DSN is easiest for initial setup.

7. Step 3: Creating the Linked Server in SQL Server

7.1 Using SQL Server Management Studio (SSMS)

  1. Connect to SQL Server → Server Objects → Linked Servers → right‑click New Linked Server.
  2. 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)
  3. Security page: Choose Be made using this security context and provide the PostgreSQL username and password (or map local logins).
  4. 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';
📌 Note: If you prefer a DSN‑less connection, set @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_addlinkedsrvlogin with @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.
⚠️ Warning: Never embed passwords in plain text in linked server scripts. Use SQL Server Credentials or encrypt the password with 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;
💡 Tip: When joining, try to push filters to the remote side by including them inside 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;
📌 Note: Ensure RPC Out is enabled on the linked server (set earlier). Without it, remote procedure calls will fail with error 7411.

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=10000 in the DSN advanced options or connection string.
  • UseDeclareFetch: Enable cursor‑based fetching for large result sets: add UseDeclareFetch=1 and Fetch=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 OPENQUERY and parameterized filters to limit result sets.
⭐ Best Practice: For large data copies, avoid linked server; use SQL Server Integration Services (SSIS) or bcp with a PostgreSQL export. Linked server excels for OLTP and small‑to‑medium data integration.

12. Common Errors & Solutions

Error MessageLikely CauseSolution
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.
💡 Tip: Enable ODBC tracing (in ODBC Data Source Administrator) to capture detailed driver calls when errors are cryptic.

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 OPENQUERY for 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 Fetch and UseDeclareFetch for 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 inprocess for 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!

⭐ Final Wisdom: A well‑tuned linked server can handle millions of rows efficiently, but always design with data volume in mind. For massive transfers, dedicated ETL tools reign supreme. Keep learning!

© 2026 FreeLearning365.com — Your Premium Source for In‑Depth Database Tutorials. | All trademarks belong to their respective owners. | Privacy Policy | Contact

Connecting databases, empowering professionals. Free Learning, 365 days.

Post a Comment

0 Comments