Migrate from IBM Db2 to PostgreSQL

Moving Db2 for LUW to PostgreSQL with Dalibo's db2topg scripts is a documented path for schema and code conversion, but the SQL rewrites, data transfer and validation still need planning. Db2 for z/OS is outside this tool's scope.

On this page

How much work a Db2 to PostgreSQL move involves

If your team runs IBM Db2 for Linux, UNIX and Windows and wants PostgreSQL in infrastructure it controls, the good news is that db2topg converts as much of the DB2 UDB schema and code as it can, in the style of Ora2Pg. The remaining effort sits in SQL rewrites that the tool cannot resolve, data transfer planning, application changes and validation that proves the new database behaves correctly. Those last four areas usually take more time than the conversion itself, so plan them before you commit to a schedule.

Effort depends on three things you can measure now: the number of database objects (tables, indexes, views, sequences, triggers and packages), the volume and style of procedural code in stored procedures and functions, and how tightly your applications depend on Db2-specific SQL, data types and session behavior. Build an inventory of each of these before you ask anyone for a plan. This page does not give a duration because the inventory determines it, and any figure quoted without one would be guesswork. Ask a partner for a written scope that lists the objects, code units and applications in your inventory and states what is excluded.

Scope also has a hard boundary. The db2topg scripts, published by Dalibo under the GPL-3.0 license, target DB2 UDB, which covers Db2 for Linux, UNIX and Windows. They do not work with Db2 for z/OS, so mainframe databases need a different migration approach or a different target plan. Confirm the exact Db2 product and version you run with the tool's repository documentation before you start, and record the edition in your inventory so the scope decision is documented.

Which Db2 platform decides the migration path

Db2 for Linux, UNIX and Windows (often written as Db2 LUW) is the platform db2topg is built for. The scripts convert as much as possible of a DB2 UDB database to PostgreSQL, in the style of Ora2Pg, so the migration starts from a database you can inventory with the same tooling you will use to convert it. Before planning effort, confirm the exact Db2 version and edition on each source instance, because feature support and catalog layout differ between releases and editions.

  • Version and edition: Record the Db2 release, fix pack level and edition for every database in scope, and check them against the db2topg repository documentation before testing.
  • Object types in use: List tables, indexes, views, sequences, triggers, user-defined functions, and any materialized query tables, since each category converts with a different level of automation.
  • Stored procedures: Count procedures and note the languages used (SQL PL, Java or external routines). Procedural logic is where manual rewriting usually concentrates.
  • Federation or replication links: Identify federated nicknames, Q Replication or SQL Replication subscriptions, and links to other databases. These depend on Db2 features that will not carry over and need a separate replacement plan.
  • Scope of the conversion: Confirm with the db2topg project which object types it handles and which it leaves for manual work.

Check these facts in your own environment before choosing a conversion path.

What maps cleanly from Db2 to PostgreSQL and what does not

This table compares common Db2 for LUW capabilities with their PostgreSQL equivalents and marks whether db2topg is expected to convert them automatically, partially, or needs manual rework. Treat each status as a starting hypothesis and confirm it against the db2topg repository and your own object inventory before estimating effort.

Source capabilityPostgreSQL equivalentMigration notes
Tables, columns and common data typesTables, columns and native types such as integer, numeric, varchar, timestampExpect automatic conversion for common types. Check DECFLOAT, graphic types, and long character types against the db2topg type mapping and test the results on sample data.
Primary and unique keysPrimary key and unique constraintsUsually converted automatically. Confirm constraint names, deferrable settings and any constraints Db2 enforces differently in your inventory.
IndexesB-tree and other PostgreSQL index typesStandard indexes are generally converted. Db2-specific index options, clustering and include columns need review. Recreate and compare query plans afterward.
Sequences and identity columnsSequences and identity columnsConverted with partial automation. Verify the next values after data load so inserts do not collide with migrated keys.
ViewsViews and materialized viewsSimple views usually convert. Views using Db2 functions, vendor syntax or nested expressions often need manual rewrites.
Schemas and usersSchemas and rolesSchemas map directly. Db2 authorities and grants do not translate one-to-one, so design PostgreSQL roles and privileges separately and confirm them with your security team.
SQL PL stored procedures and functionsPL/pgSQL functions and proceduresPartial conversion at best. Expect manual rework for control flow, cursors, condition handling and Db2 built-in functions.
TriggersPL/pgSQL trigger functions and triggersPartially converted. Trigger timing, transition variables and body logic usually need hand review.
Packages and modulesSchemas or grouped functionsNo direct equivalent. Plan a manual restructuring of package contents and test every called routine.
User-defined functionsFunctions in SQL, PL/pgSQL or other supported languagesSimple scalar and table functions may convert. External or compiled UDFs require rewrite or replacement.
Tablespaces and storage groupsTablespaces with limited scopeNo one-to-one mapping. Storage layout is managed by PostgreSQL and the filesystem, so review partitioning and storage placement as a separate design task.
pureXML and XQueryjsonb, xml type and SQL/JSON functionsManual rework. Data models and queries using XML or XQuery must be redesigned, and conversion tools should not be assumed to handle them.
Federation and nicknamesForeign data wrappers such as postgres_fdwManual design. Confirm which remote sources exist, then build and test equivalent connections and credentials.
Db2 for z/OS sourcesNot applicable to db2topgOut of scope for db2topg, which targets Db2 for Linux, UNIX and Windows. Plan a different migration path for z/OS databases.

Documented tools and export paths for Db2 to PostgreSQL

A Db2 to PostgreSQL move depends on a few components: a conversion tool for schema and code, a source-side export path for the data, and PostgreSQL's own load and dump utilities for the target. Each one covers part of the job, and the gaps between them are where migrations usually stall.

db2topg conversion scripts

db2topg is a set of GPL-3.0 scripts from Dalibo that converts as much of a DB2 UDB database to PostgreSQL as possible, in the style of Ora2Pg. Use it to produce a first-pass schema and object conversion for Db2 for Linux, UNIX and Windows. It does not work with Db2 for z/OS, so a z/OS source needs a different plan. Expect manual review of procedural code and any Db2-specific features the scripts do not convert.

db2topg repository

Source-side Db2 export utilities

Db2 provides export and load utilities such as EXPORT and LOAD that write table data to delimited files. Confirm the exact utility syntax, output formats and supported options for your Db2 release with IBM's documentation before you script anything. These utilities move data out of Db2 but do not translate types, collations or sequences into PostgreSQL terms, so the mapping work stays with your team or your partner.

psql and COPY for bulk loads

The COPY command in PostgreSQL reads delimited files into a table in a single bulk operation, and psql runs it with the \copy meta-command from the client side. This path suits large table loads after the target schema exists. Check delimiter, quoting, encoding and NULL handling against your export files, because a mismatch often loads without error and corrupts values.

pg_dump and pg_restore for the target

After conversion and loading, pg_dump and pg_restore capture and rebuild the PostgreSQL database in a portable format, which supports repeatable rehearsals and a clean copy for test environments. They do not read Db2 directly, so they only help once the data already lives in PostgreSQL. Use them to version the converted target between rehearsals and to back up the result before cutover.

Permissive license for PostgreSQL

The PostgreSQL License is a liberal license similar to the BSD and MIT licenses, so the database itself carries few distribution obligations. The conversion scripts are GPL-3.0, which carries different terms. Confirm the license of every tool you add to the pipeline, including converters, loaders and any helper scripts, with your legal or compliance team before you distribute or embed them.

How the conversion, data load and validation fit together

The flow starts at the Db2 LUW source, where db2topg produces DDL and PL/pgSQL candidates that a team reviews. Manual SQL and code rewrites follow, and data moves through a transfer path into a staging PostgreSQL server inside the target environment. Validation checks run against staging before anything reaches the production cluster. The trust boundary marks where data leaves the source network, so teams can confirm which transfer path and credentials cross it.

Conversion, data transfer and validation paths from Db2 LUW to production PostgreSQL.

Sequence for a Db2 to PostgreSQL migration with parallel run and cutover

This sequence moves a Db2 for LUW workload to PostgreSQL in stages, so each conversion gap, data difference and application query is found and fixed before production traffic depends on the new database.

  1. Inventory schemas, objects, code and queries

    Your database owners and application teams list every schema, table, view, index, sequence, trigger, stored procedure, function and package, along with the Db2-specific SQL that applications send. Record which objects are actively used, which are dead, and which depend on Db2 features such as specific data types, cursors or proprietary administrative functions. The inventory is complete when each object has an owner, a usage status and a conversion category, and the team agrees on the list in writing.

  2. Run db2topg against a copy

    Run the Dalibo db2topg scripts against a copy of the source database, never the production instance, and keep the output under version control. Review the conversion report to see which objects converted automatically, which were partly converted and which failed. The step is done when every object in the inventory is accounted for in the report and the team has recorded the reasons for each failure.

  3. Rewrite procedural code and unconverted SQL

    Developers and database engineers rewrite the stored procedures, functions, triggers and SQL statements that did not convert, and they adjust application queries that depend on Db2 behavior. Each change goes through code review and is tested against the converted schema. Plan this work with the application teams, because query changes affect the software release schedule. The step is done when the rewritten code compiles or runs in a test instance and each change is linked to its inventory item.

  4. Load a pilot into staging PostgreSQL

    Build a staging PostgreSQL server on the version you have chosen after checking it against your own support window. PostgreSQL 18 is the current major release, first released September 25, 2025, and supported until November 14, 2030. Older supported versions end earlier, with PostgreSQL 14 supported until November 12, 2026. Load a full or representative copy of the data and record load times and any errors. The step is done when the staging load completes without unresolved errors and the team can repeat it from scripts.

  5. Validate counts, keys, constraints and queries

    Compare row counts for every table, then check primary keys, unique keys, foreign keys, check constraints, nullability and sequence values against the source. Run a set of representative business queries on both systems and compare the results, including dates, decimals, character encodings and null handling. Document each difference and decide whether it is a defect or an accepted change. The step is done when every difference has a recorded disposition and the business owners have signed off on the test results.

  6. Run both systems in parallel

    Send the same workload, or a replayed copy of it, to Db2 and PostgreSQL, and compare outputs, errors and performance. Watch for differences that only appear under real concurrency, such as locking behavior, transaction isolation and batch timing. Keep Db2 as the system of record while the comparison runs. The step is done when the agreed period of parallel running ends with no unexplained differences in results and the performance is accepted by the application owners.

  7. Cut over with a documented rollback plan

    Freeze writes on Db2, run a final incremental data transfer, repeat the key validation checks and switch application connections to PostgreSQL. Agree in advance on the criteria for rolling back, the steps to return traffic to Db2, and how changes made after cutover would be reconciled. Rehearse the cutover and rollback in staging before the production event. The step is done when production traffic runs on PostgreSQL, the checks pass and the rollback path has been tested.

  8. Decommission Db2 after the retention period

    Keep the Db2 database read-only and retrievable for the retention period your organization has agreed with its data owners and compliance team. Confirm which backups, logs and exports must be kept, then remove Db2 access and infrastructure in a controlled way. Db2 for z/OS is outside what db2topg supports, so a z/OS source needs its own assessment. The step is done when the retention period has ended, the retained copies are verified and the decommission is recorded.

What drives the cost and duration of a Db2 migration

This table lists the factors that move the cost and schedule of a Db2 to PostgreSQL migration, why each one matters, and what to request in a quote. Conversion and validation work is one-time, while the high availability, backup and authentication design you build for PostgreSQL carries recurring operating cost after cutover. Use the table to scope a written quote, since the largest drivers are usually code coupling and validation depth rather than raw data size.

DriverWhy it moves cost or timeWhat to ask for in a quote
Database size and countEach database has its own schema, objects and load path, so the number of databases multiplies inventory, conversion and testing work.A per-database inventory with object counts, schema owners and cross-database dependencies.
Stored procedures and triggersDb2 SQL PL and trigger logic often needs manual rewriting in PL/pgSQL, which is usually the largest effort item.Counts by object type, with a split between automatically converted code and code the vendor will rewrite by hand.
Db2-specific features in useFeatures such as sequences with specific caching, MQTs, XML columns, temporal tables or federation have no direct equivalent and need design decisions.A feature usage report from the source catalog and a proposed PostgreSQL replacement for each feature found.
Application SQL coupling and driversEmbedded SQL, vendor-specific functions and JDBC or ODBC driver changes in client code must be found, changed and retested in each application.A list of applications and drivers that connect, with the SQL changes expected and who makes them.
Data volume and acceptable downtimeLarger tables and shorter outage windows push the team toward bulk load tuning or replication, which adds design and test work.The load method proposed (offline export and import or replication), the expected outage window and the test runs needed to prove it.
Number of parallel run cyclesEach trial migration and reconciliation pass repeats load, conversion and validation, so every extra cycle adds effort.The number of rehearsal cycles included in the fixed scope and the cost of any additional cycles.
Validation depthRow counts alone miss type, collation and precision differences, so checksums, sampled row comparison and business report checks extend the schedule.The validation checks included, the tables covered and the sign-off criteria agreed with your team.
Authentication and integration changesMoving clients to SCRAM password authentication, directory login or certificates changes connection settings in every system that connects.A list of authentication methods in use today, the target methods and the integrations, jobs and monitoring tools to update.
Target high availability and backup designReplication, failover tooling, point-in-time recovery and tested restores are built and operated after cutover, so they add one-time build work and recurring operating effort.The target recovery objectives your team sets, the replication and backup design proposed, and the ongoing support or retainer terms.

What usually goes wrong in Db2 to PostgreSQL migrations

Most failed Db2 to PostgreSQL migrations do not fail on a single dramatic error. They fail because a converted object was assumed correct, a data difference went unnoticed, or a fallback was never proven. Each card below names one failure and the step in the migration sequence that prevents it.

Trusting converted code without testing

The db2topg scripts convert as much as they can, but converted SQL and objects are a starting point, not a finished result. Each converted view, function and trigger needs to run against representative data and produce the same results as Db2. Plan a test pass for every converted object class during the build phase, and record which objects still need manual work before cutover.

db2topg repository

Underestimating procedural logic and packages

Stored procedures, triggers, and Db2 packages often hold business rules that are not visible in the table design. Inventory every procedural object early, classify it by complexity and dependencies, and assign a rewrite owner. Treat the rewrite effort as a separate work item in the scope, because it usually drives the schedule more than table conversion does.

Type and collation changes that alter results

Character data may sort, compare, or match differently once the collation and encoding change. Trailing blanks in CHAR columns, decimal precision, and timestamp handling are common sources of silent differences. Compare the source and target collation and encoding settings, then run sample queries with ORDER BY, joins, and uniqueness checks on real data before accepting the mapping.

Identity and sequence values left behind

Identity columns and sequences may not carry their current values over, so the next insert can collide with existing keys or reuse numbers the application expects to be unique. Capture the current high-water mark for every generated key on the source, set the PostgreSQL sequences after the data load, and check them again during the final cutover window.

Application SQL that relies on Db2 behavior

Application code may depend on Db2 features such as implicit casts, FETCH FIRST syntax, specific null handling, or error codes returned to the client. These behaviors often sit in drivers and ORM layers, not in the database. Inventory the SQL the applications send, test each statement against PostgreSQL, and update the error handling that parses Db2 SQLSTATE values or messages.

No tested rollback or count checks

A cutover without row count comparison, constraint validation, and a rehearsed rollback path leaves the team unable to prove the data is complete or to return safely. Run row counts and checksums per table after each load rehearsal, validate every foreign key and check constraint, and rehearse the reverse path to Db2 before the cutover date is set.

Questions buyers ask before moving Db2 to PostgreSQL

What drives the cost of moving Db2 to PostgreSQL?

The cost depends mainly on how much Db2-specific SQL, procedural code and data types the application estate uses, how many databases and applications are in scope, and how much testing and cutover work the business requires. Db2 scripts like db2topg convert as much as possible automatically, but the remaining manual rewrites, application changes and test cycles are where most of the effort sits. Costs fall into two groups: one-time work for assessment, conversion, data transfer, rewrites, validation and cutover, and recurring work after go-live for backups, monitoring, patching and upgrades. Ask any provider for a quote built from a written scope that lists the databases, object counts, applications, test environments and cutover approach, and ask which items are fixed and which depend on what the assessment finds.

How long does a Db2 to PostgreSQL migration take?

The honest answer is that duration depends on the inventory, so no reliable estimate exists until the source is examined. The factors that move the timeline most are the number of schemas, tables, views, stored procedures, triggers and packages, the volume of data and the downtime the business will accept at cutover, the number of applications that query the database and need changes, and how quickly application owners can run tests. A team with a small, well-documented database and few stored procedures will finish far sooner than one with hundreds of procedures spread across many applications. Ask for a timeline only after an inventory and assessment, and make sure the plan shows the test windows the business has agreed to provide.

What must our team provide before the migration starts?

The migration needs read access to the Db2 catalog and objects, a current inventory of databases, schemas, application connections and batch jobs, and named owners for each application that uses the database. You also need test environments that mirror production closely enough to run real workloads, and agreed test windows with the business teams who will sign off results. Confirm who can grant access to the source and target servers, who approves changes to application code and who has authority to schedule the cutover. Missing owners and unavailable test windows cause more delay than technical problems, so settle them in the written scope before work begins.

Can our own team run this migration, and what skills does it need?

Many teams can do parts of the work internally, but the migration needs people who know both Db2 and PostgreSQL well. The core skills are Db2 SQL and stored procedure knowledge, PostgreSQL SQL and PL/pgSQL, data loading and validation methods, and enough application knowledge to change queries and test behavior. Operations skills matter as well, since the team will own backups, replication, monitoring and upgrades after cutover. Assess your team honestly against that list. If gaps exist, decide whether to train staff, bring in outside help for specific phases such as conversion or validation, or hire a partner for a fixed scope with written deliverables.

Does db2topg handle Db2 for z/OS, and what should we do instead?

No. db2topg is a set of GPL-3.0 scripts from Dalibo that converts as much as possible of a DB2 UDB database to PostgreSQL, in the style of Ora2Pg, and it does not work with DB2 z/OS. Db2 for z/OS is a different product with its own catalog, utilities and SQL behavior, so mainframe databases need a separate assessment. Your options include a manual or hybrid conversion using PostgreSQL tools, a staged approach that moves selected workloads first, or an architecture review that decides which data should move at all. Confirm the exact Db2 product and version for every source before choosing a tool, because the wrong tool will cost time in the assessment phase.

How do we confirm the converted database works correctly?

Validation should compare the source and target at several levels: object counts and definitions, row counts and checksums per table, and sample data comparisons for types such as dates, decimals, character sets and nulls. Next, run the application's own test suite and the batch and reporting jobs against the PostgreSQL copy, and compare results with Db2 output for the same inputs. Performance tests matter as well, because execution plans differ between engines and some queries that were fast on Db2 may need index or SQL changes. Ask for a written test plan that lists each check, the acceptance criteria, who signs off and how failures are logged and retested.

What happens to backups, high availability and upgrades after cutover?

After cutover, the team owns the PostgreSQL platform, so backups, replication, failover and upgrades must be designed and tested before go-live. PostgreSQL supports point-in-time recovery from a base backup and archived WAL files, and hot standby servers with synchronous or asynchronous replication. PostgreSQL does not include automatic failover, so you need an external tool and a tested procedure. For upgrades, PostgreSQL 14 is supported until November 12, 2026, while PostgreSQL 18 is supported until November 14, 2030, so choose the version you deploy with its support window in mind. Plan restore tests, failover drills and a regular minor and major upgrade schedule as part of the migration scope.

How DeployOpen scopes and delivers a Db2 to PostgreSQL migration

DeployOpen plans, builds, tests and documents Db2 to PostgreSQL migrations inside infrastructure you control. Engagements are fixed-scope, so the scope, deliverables and timeline are agreed in writing before the migration work begins.

How we scope

  • We confirm the Db2 version, platform and whether the source is in scope, since db2topg does not handle Db2 for z/OS.
  • We inventory schemas, packages, stored procedures, triggers, data volumes and the applications that query the database.
  • The written scope lists conversion targets, rewritten SQL, data transfer approach, validation criteria and the cutover window.

How we build

  • We run db2topg against a copy of the source, then review what converted automatically and what needs manual rewriting.
  • We rewrite Db2 SQL and procedural code into PostgreSQL equivalents and test each change against representative workloads.
  • We build the data transfer pipeline, rehearse it on full copies, and record row counts and checksum results for each load.

How we hand over

  • You receive converted schema code, rewrite decisions, a list of unconverted objects and the reasons for each.
  • Validation reports compare row counts, data samples and application test results between Db2 and PostgreSQL.
  • Runbooks cover the cutover sequence, rollback steps, PostgreSQL configuration and the operational settings your team will own.

How we support

  • Post-cutover support covers defect fixes, query issues found by your application teams and the first production checks.
  • Ongoing support, upgrades and continuous testing are available as retainers once the migration is complete.
  • We confirm support boundaries, response expectations and PostgreSQL version plans with you in the written scope.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.