Just launched: 360° security audit to protect your legacy code from AI exploits.

Discover
Blog›Gen AI in Modernization

SQL Server to PostgreSQL Migration: A Guide to T-SQL, Applications, and Tooling

In This Article

TL;DR

  • Scope the Microsoft estate before sizing the database. Stored procedures, .NET data access, SSIS packages, SSRS reports, SQL Agent jobs, and linked servers set most of the effort and the timeline.
  • Choose Babelfish, native conversion, or refactoring per application. Base the choice on change tolerance, the required host, and whether the procedure logic needs a rewrite anyway.
  • Treat procedural T-SQL as a review workload. Converters handle TOP, IDENTITY, and routine syntax well. Temp tables, TRY/CATCH, MERGE, and procedures that return result sets need an engineer’s judgment.
  • Test collation and string comparison explicitly. SQL Server’s case-insensitive default collation and trailing-space padding change query results on PostgreSQL without raising an error, including in ORM-generated SQL.
  • Validate converted procedures by comparing outputs. Row counts and checksums cover the data only, so procedures, reports, and batch jobs need output comparison on the same inputs before cutover.

What a SQL Server to PostgreSQL Migration Involves

A SQL Server to PostgreSQL migration moves a database’s schema, data, and T-SQL code onto PostgreSQL, along with every application, ETL package, report, and scheduled job that depends on SQL Server behavior. Current tools automate most schema conversion and the data copy. Procedural T-SQL, .NET data access code, and the SSIS, SSRS, and SQL Agent estate carry most of the effort and most of the risk.

A SQL Server estate is usually a Microsoft estate. Applications connect through ADO.NET or Entity Framework, data moves through SSIS packages, reports run on SSRS, and SQL Server Agent runs the batch schedule. Each component has to be re-pointed, rewritten, or replaced when the workload moves from SQL Server to PostgreSQL.

This guide is for engineering leads, data platform owners, and architects scoping the migration, and for CIOs and CTOs weighing licensing savings against effort. The conversion work applies to PostgreSQL on-premises or as a managed service on any cloud.

A SQL Server exit is one form of database modernization, and it shares its target engine and validation method with an Oracle to PostgreSQL migration.

What to Inventory Before Moving From SQL Server to PostgreSQL

Effort in a SQL Server migration follows the code and tooling around the database. The checklist below lists what to count and why each count moves the estimate.

ComponentWhat to CountWhy It Drives Effort
Stored procedures, functions, triggersObjects by size, plus use of temp tables, cursors, dynamic SQL, TRY/CATCH, and MERGEProcedural T-SQL converts partially and needs review per object
Embedded and dynamic SQLQueries in .NET code, ORM raw SQL calls, report datasetsSchema converters do not read application repositories
Entity Framework and ADO.NET projectsProjects, DbContexts, migration historiesProvider swap, regenerated migrations, raw SQL review
SSIS packagesPackages, data flows, Execute SQL tasks, script tasksT-SQL tasks and connections tied to SQL Server
SSRS reportsReports, shared datasets, subscriptionsDataset queries written in T-SQL
SQL Server Agent jobsJobs, steps, schedules, alertsCore PostgreSQL has no built-in scheduler
Linked servers and cross-database queriesLinked servers, three-part and four-part namesEach needs a foreign data wrapper or an application-level replacement
SQLCLR assembliesAssemblies and the objects that call themNo PostgreSQL equivalent, so the logic is rewritten
Downtime toleranceThe longest acceptable cutover windowDecides between a bulk load and change data capture

Run the same count for every application that connects to the database. A shared database forces one cutover for every application that uses it, so the connection inventory also sets the migration sequence.

What a SQL Server estate contains beyond the database schema converters see

How Long a SQL Server to PostgreSQL Migration Takes

Duration follows the counts in the checklist above, with each procedure, package, report, and job adding its own conversion and test effort. An estimate built as a flat percentage on top of the database work misses estates where the SSIS and reporting layer outweighs the database itself.

A pilot conversion of one representative application turns those counts into a measured rate, and that rate is the basis for a credible estimate.

Babelfish vs. Native PostgreSQL: How to Choose a Migration Path

The path decision comes first, because it changes the scope of every later phase. Three paths exist.

  • Babelfish. Adds a T-SQL dialect and SQL Server’s TDS wire protocol to PostgreSQL, so applications connect with their existing drivers and run much of their existing T-SQL. AWS offers it as a managed option on Aurora PostgreSQL, and the open-source project runs on a modified PostgreSQL build.
  • Native conversion. Rewrites schema and code into standard PostgreSQL and PL/pgSQL, with application drivers changed to match.
  • Refactoring. Moves business logic out of stored procedures and into application services during the move.

AWS’s Well-Architected guidance for Microsoft workloads lists unnecessary full application rewrites as an anti-pattern and recommends Babelfish to minimize code changes [1]. The Babelfish migration documentation tells teams to expect query rewrites for good performance [2]. The two positions fit together once the decision is made per application.

PathFits WhenCosts and Limits
BabelfishA fast licensing exit is the priority, the application tolerates little change, and Aurora PostgreSQL is an acceptable targetManaged service tied to Aurora, or a self-maintained modified build. SQLCLR, Service Broker, MERGE, updatable cursors, and cross-database DDL are unsupported [3]. Performance rewrites still expected
Native conversionThe target is community PostgreSQL on any host, and the team will maintain PL/pgSQLFull procedural conversion and driver changes up front
Refactor to the application tierProcedure logic changes often, needs a rewrite anyway, or blocks automated testingLargest up-front effort. Logic lands in .NET services that are easier to test and staff

Babelfish also works as a staged path. An application can cut over through Babelfish first and convert its T-SQL to native PostgreSQL module by module afterward, retiring the TDS endpoint once the last caller moves.

Scope that second phase at the start. An emulated estate with no conversion plan keeps SQL Server dialect in the codebase indefinitely, and the compatibility layer becomes deferred technical debt.

SQL Server to PostgreSQL Migration Steps

A SQL Server to PostgreSQL migration runs in six steps. Steps 1, 4, and 6 absorb the most unplanned effort when they are compressed.

StepWorkWhat Gets Skipped
1. Inventory and scopingThe estate checklist above, with dependencies mapped across applications and packagesApplication repositories, SSIS catalogs, SSRS report servers
2. Path decisionBabelfish, native conversion, or refactoring per applicationA second-phase plan for Babelfish workloads
3. Schema and type mappingTypes, identity columns, collation and identifier-case rulesDeciding the collation rule once for schema, code, and data together
4. T-SQL and application conversionProcedures, triggers, .NET data access, SSIS, SSRS, Agent jobsTreating the tooling estate as its own workstream with owners
5. Data movementBulk load in a maintenance window, or bulk load plus change data captureResetting identity sequences after the load
6. Validation and cutoverOutput comparison, performance replay, rollback pathComparing procedure and report behavior on both engines

The data method follows the downtime the business accepts. A bulk load in a maintenance window has the fewest moving parts. Change data capture, through AWS DMS or a pipeline tool, keeps the window short for large databases and adds a replication pipeline to monitor.

A zero-downtime migration needs a contractual SLA behind it to justify that pipeline. After any bulk load, reset every identity sequence to the highest loaded key, or the first application insert fails with a duplicate key error.

Six SQL Server to PostgreSQL migration steps and the work each one skips

How to Convert T-SQL Stored Procedures to PL/pgSQL

Converters translate routine T-SQL syntax reliably. Review effort clusters in the constructs where PostgreSQL’s execution model differs from SQL Server’s, and a count of those constructs is a stronger effort signal than total procedure count.

T-SQL ConstructPostgreSQL TargetConverts Cleanly
TOP n, TOP n WITH TIESLIMIT n, FETCH FIRST n ROWS WITH TIESYes
IDENTITY, SCOPE_IDENTITY()GENERATED AS IDENTITY, INSERT ... RETURNINGYes
@@ROWCOUNTGET DIAGNOSTICS ... = ROW_COUNTYes
#temp tables and table variablesCREATE TEMP TABLE, with ON COMMIT DROP where neededNeeds review. PostgreSQL keeps temp tables for the whole session
TRY/CATCHBEGIN ... EXCEPTION blocksNeeds review. Exception blocks cost more to enter and exit, and transaction handling differs
MERGEMERGE (PostgreSQL 15+), or INSERT ... ON CONFLICTNeeds review. Older conversion guidance emulates MERGE, and OUTPUT clauses map to RETURNING only from PostgreSQL 17
Procedures returning result setsFunctions with RETURNS TABLE, or refcursorsNeeds review. Every caller changes too
CursorsPL/pgSQL cursors, or a set-based rewriteNeeds review
sp_executesql dynamic SQLEXECUTE ... USING with format()Needs review

Procedures that return result sets need the most coordination. PostgreSQL procedures do not return result sets to the caller, and converting them to set-returning functions changes how every .NET caller invokes them. This construct ties the T-SQL workstream to the application workstream, so both teams need the same conversion list.

SQL Server vs. PostgreSQL Differences That Change Query Results

Each difference below compiles, passes routine tests, and still changes results after cutover.

DifferenceSQL ServerPostgreSQLBusiness Impact
Default collationCase-insensitive, such as SQL_Latin1_General_CP1_CI_ASCase-sensitiveLookups on email addresses, codes, and usernames stop matching
Trailing spaces in = comparisonsStrings padded before comparison, so 'abc' = 'abc ' is true [4]Compared as stored for varchar and textJoins and lookups on padded keys return fewer rows
Identifier caseNames match case-insensitively under the default collationUnquoted names fold to lowercase, quoted names match exactlyRaw SQL against quoted PascalCase tables fails
datetime precisionAbout 3.33 ms for datetime, 100 ns for datetime2MicrosecondsRounded values break equality checks and hash comparisons
Read concurrencyLocking reads unless read committed snapshot is onMVCC, so readers do not block writersNOLOCK hints have no effect, and batch logic built on blocking changes behavior

Decide the collation rule once, before conversion. The options are the citext type, an ICU nondeterministic collation, or lower() with an expression index. Nondeterministic collations carry a performance cost and do not support some pattern matching, so LIKE-heavy code usually takes the lower() or citext route.

Application Code and Microsoft Tooling Changes for PostgreSQL

Application code changes in every native conversion, and in Babelfish migrations that use unsupported features. The changes split into .NET data access and the Microsoft tooling around the database.

Moving .NET Data Access and Entity Framework to PostgreSQL

Applications on ADO.NET move from SqlClient to Npgsql, the .NET data provider for PostgreSQL. Connection strings, parameter handling, and error handling change, and code that checks SqlException error numbers moves to PostgreSQL SQLSTATE codes.

Entity Framework applications swap the SQL Server provider for the Npgsql EF Core provider. Existing migrations carry SQL Server-specific annotations, so teams usually generate a fresh baseline migration against PostgreSQL and retire the SQL Server migration history.

ORM-based applications still break in three places.

  • Identifier casing. The Npgsql provider quotes PascalCase table and column names to preserve them, so every raw SQL query has to quote them the same way. A snake_case naming convention removes the quoting and renames every object the raw SQL touches.
  • Collation. LINQ queries that relied on case-insensitive comparisons return different results against case-sensitive columns.
  • Raw T-SQL. FromSqlRaw calls, Dapper queries, and stored procedure calls carry T-SQL that the ORM never translates.

Teams already planning an ADO.NET to EF Core migration can combine both changes into one data access rewrite.

What Replaces SQL Server Agent, SSIS, SSRS, Linked Servers, and SQLCLR

ComponentReplacement on the PostgreSQL SideScoping Note
SQL Server Agent jobspg_cron for in-database jobs, or an external schedulerJob steps that call T-SQL, SSIS, or shell commands each need a new owner
SSIS packagesRe-pointed through ODBC connections, or migrated to a pipeline platform such as Azure Data Factory, Databricks, Spark, or AirflowExecute SQL tasks carry T-SQL, and SSIS runs under SQL Server licensing
SSRS reportsDataset queries rewritten against a PostgreSQL data source, or reports moved to another platformSQL Server 2025 ships no new SSRS version, and Power BI Report Server replaces it [5]
Linked serverspostgres_fdw for PostgreSQL sources, tds_fdw for remaining SQL Server sources, or application-level integrationThree-part and four-part names in procedures break at cutover
SQLCLRPL/pgSQL, PL/Python, or an application serviceNo PostgreSQL equivalent, and Babelfish does not support it either [3]
Database MailAn application-level notification serviceAWS SCT’s extension pack emulates Agent and Database Mail on PostgreSQL [6], adding a dependency to remove later

The licensing point belongs in the business case. SSIS and SSRS run under SQL Server licensing, so an estate that keeps them in production keeps part of its SQL Server license after the databases move. An SSIS pipeline migration retires the package dependency and that license together.

Start a $0 Modernization Assessment

Dependency Map
Risk Heatmap
Modernization Plan (3-5 Days)
MedtronicClairULAB Systems+more

SQL Server to PostgreSQL Converter Tools Compared

A SQL Server to PostgreSQL converter covers schema and data reliably and T-SQL partially. The table compares tool classes across five columns, and coverage thins out after the third.

Tool ClassExamplesSchemaDataT-SQL LogicApplication CodeValidation
Open-source schema and data toolspgloader, sqlserver2pgsqlYesYesNoNoNo
Commercial database convertersDBConvert, Full Convert, Intelligent ConvertersYesYesLimitedNoLimited
Code conversion toolsAWS SCT, IspirerYesWith a companion data toolPartial, with action items or emulationEmbedded SQL in some productsNo
CDC and pipeline toolsAWS DMS, EstuaryBasicYes, including ongoing replicationNoNoData-level checks
AI-assisted conversionCloud conversion assistants, AI modernization platformsYesWith a companion data toolPartial to broad, with reviewVaries by toolVaries by tool

Three points affect how to read tool claims.

  • SSMA migrates into SQL Server. SQL Server Migration Assistant appears in some tool lists for this pair. It converts other databases into SQL Server and Azure SQL, so it has no role in a move to PostgreSQL.
  • Automation rates count objects. Vendor percentages usually count converted objects, a different unit from engineering effort. The remainder holds the temp-table, transaction, and result-set patterns that take the longest to review.
  • Emulation defers work. AWS SCT’s extension pack emulates SQL Server functions in an aws_sqlserver_ext schema [6]. Converted code then depends on that schema until someone replaces each call with native PostgreSQL.

How Gen AI Converts T-SQL and Embedded SQL for PostgreSQL

Gen AI conversion covers parts of the estate that rule-based converters leave. It performs well on three kinds of work.

  • Translating whole procedures with their surrounding context, including temp-table and error-handling patterns.
  • Finding T-SQL embedded in .NET repositories, SSIS packages, and report definitions.
  • Mapping dependencies between procedures, applications, and jobs.

Hyperscaler AI tooling for this pair is tied to a target. Google’s Database Migration Service offers Gemini-assisted conversion workspaces for SQL Server to AlloyDB, and Microsoft’s AI-assisted migration in the PostgreSQL extension for VS Code covers Oracle sources only [7].

AI-converted code needs three controls before merge.

  • Human review of every diff, with the reviewer checking transaction and error-handling semantics.
  • Behavioral testing against SQL Server outputs on the same inputs.
  • Performance tuning on PostgreSQL, since the converted code runs against a different planner.

Programs that apply these controls across teams formalize them as safety nets for Gen AI in legacy modernization, enforced in the pipeline.

How to Validate a SQL Server to PostgreSQL Migration Before Cutover

Validation for a SQL Server to PostgreSQL migration runs at four levels. The behavior differences above become fixed test cases at the second level.

  • Data. Row counts per table, then column hashes after normalizing datetime precision, bit-to-boolean values, and trailing spaces on both sides.
  • Converted procedures. Each procedure runs on SQL Server and PostgreSQL with the same inputs, and result sets, output parameters, and side effects are compared.
  • Business outputs. SSRS reports, SSIS loads, and Agent job results from both systems for the same period are compared line by line.
  • Transaction behavior. Concurrent test runs confirm that batch logic written for SQL Server’s locking reads produces the same results under MVCC.

Data-level checks follow the same techniques as any data migration validation. Procedure and business-output comparison needs the SQL Server system available as a reference until sign-off.

PostgreSQL vs. SQL Server Performance After Cutover

PostgreSQL performance after cutover depends on tuning for its planner. Capture the top queries and batch windows on SQL Server and replay them on PostgreSQL before cutover. Check exception-heavy procedures and case-insensitive lookups first, since both add cost after conversion.

Find Where Parity Risk Sits in the Estate

Behavioral parity across converted procedures, .NET data access, and SSIS packages takes the most evidence in a SQL Server exit. A $0 Modernization Assessment maps where that risk concentrates in your codebase before conversion starts.

How Legacyleap’s Gen AI Agents Run a SQL Server to PostgreSQL Migration

Legacyleap is a Gen AI-powered legacy modernization platform built on multi-agent orchestration. For a SQL Server exit, its five agents cover the database and the Microsoft estate around it across the Assess, Comprehend, Modernize, Validate, and Deploy lifecycle.

  • Assessment Agent. Inventories stored procedures, .NET data access code, SSIS packages, and dependencies across repositories, and produces a dependency map, modernization hotspots, and an effort and timeline estimate.
  • Documentation Agent. Reconstructs the business logic held in procedures and triggers, along with data flows and integration maps, including where no documentation exists.
  • Recommendation Agent. Recommends per module whether logic stays in the database or moves to .NET services, and produces an ordered migration plan with effort and risk scores.
  • Modernization Agent. Executes the plan as diff-based pull requests. These cover stored-procedure logic moved into .NET services, the data access code that calls it, and SSIS pipelines migrated to targets such as Azure Data Factory, Databricks, or Spark. Roughly 70% of the modernization work is automated, and engineers review and direct the rest.
  • QA Agent. Generates unit, integration, regression, and API tests, and produces behavior parity validation reports against the SQL Server baseline before cutover.

No agent merges, deploys, or executes code autonomously. Every change is a diff-based pull request that an engineer reviews.

Full-codebase grounding reads application code, SSIS packages, and the procedures they call together, so cross-layer dependencies appear in one map. All processing runs inside the organization’s own infrastructure, and source code never leaves the environment.

Next Steps for Planning a SQL Server to PostgreSQL Migration

Moving from SQL Server to PostgreSQL is scoped by the T-SQL, the .NET data access code, and the SSIS, SSRS, and Agent estate around the database. Counting that estate, choosing a path per application, and comparing procedure and report outputs before cutover give the program a realistic plan and a defensible sign-off.

For teams scoping the move, the $0 Modernization Assessment produces the estate inventory, a dependency and module map, a risk and complexity heatmap, and a modernization plan for one representative codebase. It takes 3 to 5 days and runs inside the client’s environment. More than 150 production-grade assessments have been completed to date.

A technical demo shows how the five agents take an approved plan through conversion and parity validation.

Count the Microsoft Estate Before Conversion Starts

A $0 Modernization Assessment produces the estate inventory, a dependency and module map, a risk and complexity heatmap, and a modernization plan for one representative codebase in 3 to 5 days, at no cost and inside your own environment.

FAQ

Q1. Does application code change when migrating from SQL Server to PostgreSQL?

Yes, in every native conversion, because the driver, embedded SQL, and SQL Server system functions all change. Functions such as GETDATE(), ISNULL(), and NEWID() become now(), COALESCE(), and gen_random_uuid() on PostgreSQL.

Q2. Can T-SQL stored procedures be converted to PostgreSQL automatically?

Partially. Converters translate routine T-SQL syntax automatically, and constructs such as INSERT ... EXEC need a manual rewrite, usually to INSERT ... SELECT from a set-returning function.

Q3. What is the best tool to convert SQL Server to PostgreSQL?

No single SQL Server to PostgreSQL converter covers schema, data, T-SQL, application code, and validation. A working toolset combines a schema converter, a bulk-load or CDC tool for the data, and a separate method for application code and output comparison.

Q4. Should you use Babelfish or convert to native PostgreSQL?

Use Babelfish for a fast licensing exit onto Aurora PostgreSQL with minimal code change. Convert to native PostgreSQL when the target must run on any host or the T-SQL depends on features Babelfish does not support, which Babelfish Compass reports before any code moves.

Q5. Is PostgreSQL case-sensitive compared to SQL Server?

Yes. PostgreSQL compares strings case-sensitively by default, so values such as ‘ABC’ and ‘abc’ that a SQL Server unique index rejected as duplicates can both load into the same PostgreSQL column.

Q6. How long does a SQL Server to PostgreSQL migration take?

Duration depends on the size of the T-SQL, application, and SSIS/SSRS estate, so an estimate sized from the database alone understates it. Keep SQL Server running in parallel for at least one full business cycle after cutover, since month-end and quarter-end jobs are the last outputs to match.

Q7. How do you migrate from SQL Server to PostgreSQL with minimal downtime?

Bulk load the data in advance, then replicate changes with change data capture until a short final cutover. Disable foreign keys and triggers on the target during the bulk load, and re-enable and validate them before the CDC catch-up starts.

References

[1] AWS Well-Architected Framework, Microsoft Workloads Lens. MSFTCOST04-BP02 Consider Babelfish for Aurora PostgreSQL

[2] Babelfish for PostgreSQL Documentation. Migrating to Babelfish

[3] Amazon Aurora User Guide. Unsupported functionalities in Babelfish

[4] Microsoft Learn. = (String comparison or assignment)

[5] Microsoft Learn. Reporting Services Consolidation FAQ

[6] AWS Schema Conversion Tool User Guide. Migrating from SQL Server to PostgreSQL with AWS Schema Conversion Tool

[7] Microsoft Learn. Migrate Oracle to PostgreSQL with the PostgreSQL extension for Visual Studio Code

Book a $0 Assessment

We will scan a portion of your legacy codebase and share documentation, architecture maps, dependency graphs, in 3-5 days.

Book a Time →
Share the Blog

Latest Blogs

Db2 to Postgres Migration: Schema, SQL PL, and App Code

Db2 to Postgres Migration: A Guide to Schema, SQL PL, and Application Code

Oracle to PostgreSQL Migration: Code, Data, and Validation

Oracle to PostgreSQL Migration: A Guide to Code, Data, and Validation

Legacy System Audit: What to Check Before Modernizing

Legacy System Audit: How to Assess Code and Data Before Modernization

Data Migration Validation, A Practitioner Guide

Data Migration Validation: A Practitioner’s Guide to Validating Data After Migration

Strangler Fig Approach for Code and Data Migration

Understanding the Strangler Fig Approach for Code and Data Modernization

Cloud Modernization Services, Scope, Cost, Delivery Model

Cloud Modernization Services: A Buyer’s Guide to Scope, Strategy, and Delivery Model

Technical Demo

Book a Technical Demo

Explore how Legacyleap’s Gen AI agents analyze, refactor, and modernize your legacy applications, at unparalleled velocity.

Watch how Legacyleap’s Gen AI agents modernize legacy apps ~50-70% faster

Want an Application Modernization Cost Estimate?

Get a detailed and personalized cost estimate based on your unique application portfolio and business goals.