Przejdź do treści głównej
Database Migration

SQL Server to PostgreSQL Migration: Complete Guide 2025

9 min readMichał Wojciechowski
Database servers in data center

SQL Server licensing costs can consume 20-30% of an IT budget. With SQL Server Enterprise at $14,000 per core and Standard at $3,700 per core, organizations managing multiple databases face six-figure annual licensing fees. PostgreSQL, a powerful open-source alternative, offers enterprise-grade features with zero licensing costs.

I've helped multiple organizations migrate from SQL Server to PostgreSQL, achieving 60-70% cost reduction while maintaining or improving performance. This guide covers everything from initial assessment to production cutover, based on real-world migrations ranging from 50GB to 2TB databases, similar to other modernizing legacy systems projects.

01Why Companies Migrate from SQL Server

The decision to migrate isn't just about cost. According to the DB-Engines ranking, PostgreSQL has grown to #4 globally (up from #13 in 2013), while SQL Server remained flat at #3. Moving to modern cloud infrastructure with PostgreSQL offers significant benefits:

Cost Comparison

SQL Server Enterprise

$14,256/core (2025 pricing)

+ ~20% annual Software Assurance

SQL Server Standard

$3,717/core (2025 pricing)

Limited to 24 cores, 128GB RAM

PostgreSQL

$0 (open source)

Optional commercial support $2-5K/year

PostgreSQL Advantages

  • Advanced indexing (GiST, GIN, BRIN, Bloom)
  • Native JSON/JSONB support (faster than SQL Server)
  • Superior full-text search
  • Extensibility (PostGIS, pgvector, TimescaleDB)
  • Cloud-native (AWS RDS, Azure, GCP)
  • Active open-source community

Real Cost Example

Organization with 3 production servers (16 cores each):

SQL Server Enterprise: 3 servers × 16 cores × $14,256 = $684,288 initial + $136,857/year SA = $821,145 first year

PostgreSQL on Azure: 3 × Managed PostgreSQL (16 vCores, 64GB RAM) ≈ $1,800/month = $21,600/year

Savings: $799,545 first year, $115K annually after (check more Azure cost optimization strategies)

Data migration between systems

02Common Migration Challenges

1. T-SQL to PL/pgSQL Conversion

SQL Server's T-SQL has proprietary syntax that doesn't exist in PostgreSQL. Key differences:

SQL Server T-SQL

-- Identity columns
CREATE TABLE users (
  id INT IDENTITY(1,1),
  name NVARCHAR(100)
);

-- Date functions
SELECT GETDATE(), DATEADD(day, 7, OrderDate)

-- String concat
SELECT 'Hello' + ' ' + 'World'

-- TOP keyword
SELECT TOP 10 * FROM orders

-- Variables
DECLARE @count INT
SET @count = (SELECT COUNT(*) FROM users)

PostgreSQL PL/pgSQL

-- Serial/Sequences
CREATE TABLE users (
  id SERIAL PRIMARY KEY,
  name VARCHAR(100)
);

-- Date functions
SELECT NOW(), OrderDate + INTERVAL '7 days'

-- String concat
SELECT 'Hello' || ' ' || 'World'

-- LIMIT keyword
SELECT * FROM orders LIMIT 10

-- Variables
DO $$
DECLARE count_val INT;
BEGIN
  SELECT COUNT(*) INTO count_val FROM users;
END $$;

2. Data Type Mapping

SQL ServerPostgreSQLNotes
NVARCHAR(n)VARCHAR(n)PostgreSQL is UTF-8 by default
DATETIME, DATETIME2TIMESTAMPUse TIMESTAMP WITH TIME ZONE for consistency
UNIQUEIDENTIFIERUUIDUse uuid-ossp extension
IMAGE, VARBINARY(MAX)BYTEAConsider object storage for large files
XMLXMLDirect mapping, similar XPath support

3. SSIS, SSRS, and SQL Agent Alternatives

  • SSIS →
    Apache Airflow, Pentaho, Talend

    Modern orchestration with better monitoring and scheduling

  • SSRS →
    Grafana, Metabase, Apache Superset

    Modern BI tools with better visualization and dashboards

  • SQL Agent →
    pg_cron extension, Airflow, cron + scripts

    pg_cron provides similar scheduling within PostgreSQL

Modern data center with servers

03Migration Strategy

Phase 1: Assessment (1-2 weeks)

  • Schema analysis - Count tables, views, stored procedures, functions, triggers
  • Code review - Identify T-SQL-specific syntax requiring conversion
  • Dependency mapping - Application connections, ETL jobs, reports, APIs
  • Performance baseline - Current query performance, peak load metrics
  • Migration tool selection - Choose between pgLoader, AWS SCT, custom scripts

Phase 2: Planning (1-2 weeks)

Migration Approach Selection

Big-Bang Migration

Single cutover weekend

✓ Simple, fast (1-3 days downtime)

✗ High risk, full rollback if issues

Best for: Small databases, non-critical apps

Phased Migration

Gradual table-by-table or module-by-module

✓ Lower risk, minimal downtime, easy rollback

✗ Complex dual-write, longer timeline

Best for: Large databases, mission-critical apps (especially in multi-tenant architecture)

Cloud database infrastructure

Phase 3: Execution (2-12 weeks)

  1. 1
    Schema Migration

    Convert DDL scripts, create tables, indexes, constraints in PostgreSQL

  2. 2
    Data Migration

    Use pgLoader or BCP → CSV → COPY for bulk data transfer

  3. 3
    Stored Procedures/Functions

    Convert T-SQL to PL/pgSQL, test logic equivalence

  4. 4
    Application Updates

    Update connection strings, ORM mappings (EF Core, Dapper), query syntax - similar to .NET application migration

  5. 5
    Testing

    Unit tests, integration tests, performance testing, data validation

Phase 4: Validation & Cutover (1-2 weeks)

Data Integrity Checks

Row counts, checksums, sample data comparison between SQL Server and PostgreSQL

Performance Testing

Load testing with production-like workload, query optimization, index tuning

Cutover Plan

Final sync, redirect traffic, monitor metrics for 48-72 hours, keep SQL Server read-only as fallback

04Migration Tools Comparison

ToolBest ForProsCons
pgLoaderSmall-medium databasesFree, fast, automatic type conversionLimited stored procedure conversion
AWS Schema Conversion ToolAWS migrationsFree, comprehensive, migration assessmentAWS-centric, complex setup
Ispirer SQLWaysComplex migrationsCommercial support, handles complex T-SQLExpensive ($5K-$50K), proprietary
Custom ScriptsUnique requirementsFull control, tailored to needsTime-consuming, requires expertise

Recommended Approach

I typically use a hybrid approach: pgLoader for schema and data + custom scripts for stored procedures. This balances automation with control.

-- pgLoader example configuration
LOAD DATABASE
  FROM mssql://user:pass@sqlserver:1433/ProductionDB
  INTO postgresql://user:pass@postgres:5432/ProductionDB

WITH include drop, create tables, create indexes, reset sequences,
     workers = 8, concurrency = 1

SET maintenance_work_mem TO '512MB',
    work_mem TO '128MB'

CAST type datetime to timestamptz drop default drop not null using zero-dates-to-null,
     type uniqueidentifier to uuid using byte-vector-to-bytea;

05Real-World Case Study

E-commerce Platform Migration

Before State

  • • SQL Server 2016 Standard (3 servers)
  • • 350GB database (850 tables)
  • • 200 stored procedures
  • • 15 SSIS packages
  • • Licensing: $89K/year (3×16 cores)
  • • Performance: 2,500 TPS peak

After State

  • • PostgreSQL 15 on Azure (managed)
  • • Same 350GB (optimized to 310GB)
  • • All procedures converted to PL/pgSQL
  • • Apache Airflow for ETL
  • • Cost: $28K/year (managed PostgreSQL)
  • • Performance: 3,200 TPS peak (+28%)

Migration Timeline (10 weeks)

Week 1-2: Assessment and planning$12K consultant time
Week 3-5: Schema + data migration with pgLoader$18K dev time
Week 6-8: Stored procedure conversion, application updates$24K dev time
Week 9: Testing, performance tuning$8K QA + dev
Week 10: Cutover and validation$6K ops time
Total Migration Cost$68K

Results After 12 Months

$61K

Annual savings

$89K → $28K licensing

28%

Performance improvement

Better indexing + query optimization

Zero

Production incidents

Smooth migration, no data loss

ROI: Migration paid for itself in 13 months. 5-year TCO savings: $305K. Learn more about quantifying technical debt for better business justification.

IT team collaborating on database migration

06FAQs

How long does SQL Server to PostgreSQL migration take?

Migration timeline depends on database size and complexity. A small database (10-50GB, 100 tables) typically takes 2-4 weeks including testing. Medium databases (100-500GB, 500 tables) require 1-3 months. Large enterprise databases (1TB+, 1000+ tables with complex stored procedures) can take 3-6 months for careful phased migration.

What about SQL Server-specific features like SSIS, SSRS, and SQL Agent?

PostgreSQL alternatives exist: SSIS can be replaced with Apache Airflow, Luigi, or Pentaho Data Integration. SSRS can be replaced with Grafana, Metabase, or Apache Superset. SQL Agent can be replaced with pg_cron extension or external schedulers like Airflow. Migration requires redesigning ETL workflows and reports, but modern alternatives often provide better features.

How much cost savings can I expect from migrating to PostgreSQL?

Typical cost savings range from 50-80% depending on your SQL Server edition. SQL Server Enterprise ($14,000/core) vs PostgreSQL (free) provides maximum savings. Including support contracts and Azure/AWS managed PostgreSQL, organizations typically save 60-70% on database licensing alone. Total TCO reduction including reduced maintenance overhead averages 50-65%.

Can I keep both SQL Server and PostgreSQL running during migration?

Yes, this is the recommended approach for large migrations. Use dual-write pattern or CDC (Change Data Capture) to keep both databases synchronized during migration. This allows you to validate PostgreSQL performance, test application changes, and have an immediate rollback path if issues arise. Most enterprises run parallel databases for 1-3 months before final cutover.

What are the biggest challenges in T-SQL to PL/pgSQL conversion?

Main challenges include: (1) IDENTITY columns → SERIAL/SEQUENCES, (2) Date/time functions differences (GETDATE() → NOW(), DATEADD → interval arithmetic), (3) String concatenation (+ operator → ||), (4) TOP keyword → LIMIT, (5) ISNULL/COALESCE behavior differences, (6) Transaction isolation levels, (7) Cursor syntax differences. Most can be addressed with automated conversion tools plus manual refinement.

Is PostgreSQL performance comparable to SQL Server?

Yes, PostgreSQL often outperforms SQL Server for read-heavy workloads, JSON operations, and OLAP queries. SQL Server can be faster for write-heavy OLTP with proper indexing. Real-world benchmarks show PostgreSQL 15+ handles 15,000-20,000 TPS on commodity hardware. The key is proper tuning: indexes, VACUUM strategy, connection pooling (PgBouncer), and query optimization. Most organizations see similar or better performance after migration with significantly lower costs.

Key Takeaways

  • PostgreSQL migration can save 60-70% on database costs while improving performance
  • Phased migration with dual-write minimizes risk and allows gradual validation
  • Modern alternatives to SSIS, SSRS, SQL Agent often provide better features and integration
  • Most migrations pay for themselves in 12-18 months through licensing savings alone
  • Proper tuning (indexes, VACUUM, connection pooling) is critical for optimal PostgreSQL performance

Need Help with Database Migration?

I help organizations migrate from SQL Server to PostgreSQL with minimal risk and maximum cost savings. Let's discuss your migration strategy.

Related Articles

References

  1. [1] Microsoft Azure - Official Documentation -https://learn.microsoft.com/en-us/azure/
  2. [2] Microsoft Learn - Azure Training Center -https://learn.microsoft.com/en-us/training/azure/
  3. [3] Flexera State of the Cloud Report 2024 -https://www.flexera.com/blog/cloud/cloud-computing-trends-2024-state-of-the-cloud-report/
  4. [4] FinOps Foundation - Best Practices -https://www.finops.org/
  5. [5] Gartner - Cloud Computing Research -https://www.gartner.com/en/information-technology/insights/cloud-computing
  6. [6] AWS - Official Documentation -https://docs.aws.amazon.com/
  7. [7] Google Cloud - Official Documentation -https://cloud.google.com/docs
SQL Server to PostgreSQL Migration Guide 2025 | Wojciechowski.app | Wojciechowski.app