October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk12 min

How to Migrate a MySQL Database to PostgreSQL with pgloader

Use pgloader to migrate MySQL data and schema to PostgreSQL with repeatable load files, explicit type casts, rehearsal runs, and a thorough post-migration validation plan.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

pgloader is the fastest practical starting point for moving a MySQL database into PostgreSQL when you need schema conversion, data loading, and common type mappings in one repeatable process. A simple migration can be one command, but a production cutover should use a version-controlled load file, a disposable rehearsal database, explicit cast rules, and a validation checklist. Views, triggers, stored procedures, and functions require separate export or rewriting because pgloader does not migrate them directly.

What pgloader does—and what it does not do

pgloader connects to a source database, creates PostgreSQL tables, transfers rows in parallel, and applies conversion rules while loading. Its MySQL workflow can translate table definitions, constraints, indexes, primary keys, foreign keys, comments, and MySQL auto_increment columns into PostgreSQL equivalents. It can also translate MySQL ON UPDATE CURRENT_TIMESTAMP behavior into a PostgreSQL BEFORE UPDATE trigger.

As an Amazon Associate I earn from qualifying purchases.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Those automatic conversions are a starting point, not proof that the target behaves exactly like the application expects. You still need to inspect generated DDL, check data types and defaults, and test application queries.

Direct migration has important limits. The MySQL and PostgreSQL references list views, triggers, stored procedures, and functions as unsupported for direct migration. Only the MySQL POINT geometric type is covered. Export unsupported objects separately, rewrite them in PostgreSQL syntax, and test them after the data load.

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.

Plan the migration before running pgloader

Inventory the source

  • Record every database, table, column type, index, constraint, view, trigger, routine, event, and scheduled job that matters to the application.
  • Identify MySQL-specific behavior such as zero dates, unsigned integers, TINYINT(1) booleans, ENUM values, implicit character-set conversions, and ON UPDATE timestamp clauses.
  • Measure table sizes and estimate the network path between MySQL and PostgreSQL. There is no authoritative universal runtime or throughput figure; performance varies with row count, indexes, network capacity, and target configuration.
  • Decide whether the application will be stopped for a final load or whether you need a replication or dual-write cutover design outside pgloader.

Create a protected PostgreSQL target

Create the target database and a migration user with the privileges needed to create schemas, tables, indexes, constraints, sequences, and triggers. Grant only the permissions required for the migration, and remove or reduce them after cutover. Keep credentials out of shell history, source control, and shared logs. Prefer a secret manager or a protected environment variable when your operating environment supports one.

Test both connections

Use a MySQL URL such as mysql://user:password@host:3306/dbname and a PostgreSQL URL such as pgsql://user:password@host:5432/dbname. The MySQL reference also documents a JDBC connection form; use that form when your MySQL deployment or driver setup requires it. Verify DNS, firewall rules, TLS requirements, authentication, and the target user’s DDL privileges before starting a full load.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Run the simplest migration

For a first rehearsal, use a disposable PostgreSQL database and the shortest command:

pgloader mysql://myuser@myhost/dbname pgsql://pguser@pghost/dbname

The credentials in this example are intentionally omitted from the URLs. Supplying a password interactively or through a protected mechanism is safer than putting a reusable password directly in a process list or committed file.

This command asks pgloader to create the target schema and load the source data using its default MySQL conversion rules. Capture the complete terminal output. Warnings, rejected rows, and target-server errors are migration findings, not harmless noise.

When the one-line command is enough

A direct command is reasonable for a small, uncomplicated database when you can recreate the target and the source uses conventional types. It is useful for discovering conversion problems quickly.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.

When to stop using a one-line command

Use a load file as soon as you need casts, table filtering, renames, schema changes, memory settings, materialized views, or a repeatable production procedure. A load file makes every option reviewable and lets you repeat the same migration after correcting data-quality problems.

Build a repeatable .load file

Store the following pattern in version control after replacing the credentials, database names, schema, casts, and resource settings with values for your environment:

LOAD DATABASE
     FROM mysql://root@localhost/sakila
     INTO postgresql:///sakila
 WITH include drop, create tables, no truncate,
      create indexes, reset sequences, foreign keys
 SET maintenance_work_mem to '128MB',
     work_mem to '12MB',
     search_path to 'sakila'
 CAST type datetime to timestamptz
                    drop default drop not null using zero-dates-to-null,
      type date drop not null drop default using zero-dates-to-null
 MATERIALIZE VIEWS film_list, staff_list
 BEFORE LOAD DO
 $$ create schema if not exists sakila; $$;

Run a file with the pgloader command appropriate to your installation, for example:

pgloader migration.load

The sample uses the Sakila names from the official tutorial structure. Treat it as a pattern, not a drop-in production configuration.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Understand the major options

Option Effect Operational caution
create tables Creates target table definitions. Review generated types, defaults, and nullability before cutover.
create indexes Builds indexes described by the source. Index creation consumes target I/O and can extend the load window.
foreign keys Creates foreign-key constraints. Bad or orphaned source data can cause constraint failures.
reset sequences Moves generated sequences beyond the current key values. Verify the next generated value is greater than every existing key.
no truncate Does not truncate target tables before loading. Do not use a nonempty target unless you deliberately understand duplicate and merge behavior.
include drop Allows pgloader to drop target tables whose names occur in the source. Destructive: use only on an intentionally disposable or tightly controlled target.
search_path Sets the PostgreSQL schema used by unqualified objects. Ensure the schema exists and that the migration user can use it.

Memory settings such as maintenance_work_mem and work_mem affect the target session. Increase them only within the memory budget of the PostgreSQL server; the sample values are not universal recommendations.

Control which tables and schemas move

Large systems often need a staged migration rather than an all-or-nothing copy. Use INCLUDING ONLY TABLE NAMES MATCHING to select an allow-list and EXCLUDING TABLE NAMES MATCHING to omit tables that are temporary, archival, or regenerated by the application. Keep the filtering expressions in the load file so a rehearsal and the final run select the same objects.

Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by

If source encoding metadata is incorrect, DECODING TABLE NAMES MATCHING ... AS ... lets you tell pgloader how to decode matching table names. ALTER TABLE NAMES MATCHING can rename tables, move them to another schema, or apply table settings in pgloader’s in-memory representation before creation.

Filtering changes the validation obligation: compare row counts for every table that was included, and document every excluded table and the reason it is absent.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Map MySQL types deliberately

How pgloader chooses a cast

User-defined CAST rules are evaluated before built-in defaults, and the first matching rule wins. A rule can match a MySQL type or a qualified column. Guards can distinguish unsigned values, defaults, typemods, auto_increment, and on_update_current_timestamp. Order specific rules before broad ones so an early match does not hide a later exception.

Common conversion decisions

MySQL case Why it needs review Typical action
TINYINT(1) Many applications use it as a boolean, but it is still an integer in MySQL. Cast to PostgreSQL boolean only when the stored values and application semantics are strictly true/false.
Unsigned integers PostgreSQL integer ranges are signed; large unsigned values can overflow a signed target type. Select a wider PostgreSQL numeric type or clean values before loading, then test boundary values.
ENUM MySQL’s enum implementation and invalid-value behavior do not map transparently to every PostgreSQL design. Choose text with a check constraint, a PostgreSQL enum, or a lookup table according to how the application evolves values.
Binary columns Binary bytes must not be interpreted as text in the target encoding. Use a binary-compatible target type and verify round trips with representative byte sequences.
DATETIME and TIMESTAMP Timezone semantics differ, and an apparently identical timestamp can represent a different instant. Choose timestamp or timestamptz intentionally and test values around timezone transitions.
Zero dates Values such as 0000-00-00 are accepted by some MySQL configurations but are not valid PostgreSQL dates. Use zero-dates-to-null where null is semantically correct, or cleanse and map them to a documented sentinel before loading.

The sample load file converts datetime to timestamptz and applies zero-dates-to-null to date-like values while dropping their default and not-null properties. That is appropriate only when a missing date is acceptable. If the application requires a value, clean the source or choose a different mapping instead of silently introducing nulls.

Preserve generated keys safely

pgloader documents conversion of MySQL auto_increment columns to PostgreSQL serial-style columns. After loading, inspect the generated sequence and run a test insert in a transaction. The sequence must be above the current maximum key; otherwise the first application insert can fail with a duplicate-key error. The reset sequences option helps, but it does not replace verification.

Handle automatic update timestamps

MySQL’s ON UPDATE CURRENT_TIMESTAMP behavior is translated to a PostgreSQL before-update trigger. Confirm that the trigger fires on the same updates as before, that explicit timestamp assignments retain the intended meaning, and that your application’s auditing code does not now update a column twice.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.

Rehearse, inspect, and correct

  1. Clone the target environment. Create an empty PostgreSQL database that is disposable and sized close enough to expose permission, encoding, and resource problems.
  2. Run the load file. Keep the output, PostgreSQL server log, and rejected-row details together with the exact file revision used.
  3. Inspect the generated schema. Check every table’s columns, defaults, nullability, primary key, foreign keys, unique constraints, indexes, sequences, and schema placement.
  4. Investigate every warning. Classify it as an expected conversion, a rejected row, a truncation risk, an encoding issue, or an actual failure. Do not proceed merely because the process returned control to the shell.
  5. Fix casts or source data. Update the load file or cleanse the MySQL data, then destroy and recreate the rehearsal target so the next run is from a known state.
  6. Repeat until the result is deterministic. A second run should produce the same schema and row totals when the source has not changed.

Do not run include drop against a production database unless dropping matching target tables is an explicitly approved part of the cutover. A separate disposable rehearsal is the safest place to test destructive options.

What to do with views, triggers, and stored routines

Because pgloader does not directly migrate MySQL views, triggers, stored procedures, or functions, treat them as a separate workstream:

  • Export definitions from MySQL before the migration and place them under version control.
  • Rewrite MySQL syntax, delimiter handling, procedural language, date functions, error handling, and identifier quoting for PostgreSQL.
  • Recreate views after base tables and data are present. If a view is expensive and read-only, consider whether a materialized view is appropriate; the load-file MATERIALIZE VIEWS clause is an explicit choice, not a guarantee that every source view will work unchanged.
  • Reimplement triggers and verify firing order, transition values, recursion behavior, and transaction effects.
  • Replace stored procedures and functions with tested PostgreSQL routines or move the logic into the application where that is the safer design.
  • Run application-level tests for every path that depends on these objects.

Do not assume that a successful table load means the application is feature-complete. Unsupported objects are often the difference between a data copy and a usable migration.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Validate the PostgreSQL result

Validation should be a written checklist, not an informal spot check. Complete these checks before switching application traffic:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Row counts: compare source and target counts for every table, including filtered tables. Explain intentional differences such as excluded archives.
  • Keys and constraints: verify primary keys, foreign keys, unique constraints, indexes, and nullability. Check for orphaned foreign keys if constraints were deferred or omitted.
  • Sequences: confirm every sequence or identity value is greater than the current maximum key, then perform a rolled-back insert test.
  • Types and ranges: inspect converted integers, unsigned values, enum-like columns, dates, timestamps, binary data, and text encodings. Include maximum and minimum source values in test cases.
  • Aggregates: compare representative sums, counts, minimums, maximums, and grouped totals. Aggregates can reveal truncation or timezone errors that row counts miss.
  • Queries: execute representative application queries against both databases and compare result sets, ordering assumptions, null handling, and pagination.
  • Unsupported objects: recreate and test views, triggers, stored procedures, and functions separately.
  • Logs and artifacts: retain pgloader warnings, rejected rows, PostgreSQL logs, the load file, and schema-diff results so the migration can be audited or repeated.

Cutover and rollback planning

Freeze or quiesce writes long enough to produce a consistent final source snapshot, unless you have designed a separate change-capture or dual-write process. Run the corrected load against the final target, perform the validation checklist, deploy the PostgreSQL-compatible application configuration, and monitor errors, latency, constraint violations, and sequence allocation.

Keep the MySQL database available and unchanged for the agreed rollback window. Define in advance which writes must be replayed or discarded if you revert; simply pointing the application back at MySQL after new PostgreSQL writes have occurred can lose data.

Choosing pgloader versus other migration approaches

pgloader is attractive when you want an open, scriptable conversion with explicit casts and table filtering. A dump-and-restore workflow may offer more control over a full logical backup but usually requires you to perform MySQL-to-PostgreSQL schema and type rewrites yourself. A managed migration service may provide monitoring, retries, and change replication, but introduces provider-specific configuration, network requirements, and cost.

Decision axis Questions to ask
Schema and type conversion Does the approach handle your unsigned values, zero dates, enums, timestamps, binary columns, and generated keys?
Views and routines Will you rewrite unsupported objects manually, or does the service offer a compatible conversion path?
Repeatability and filtering Can you store table selection, casts, renames, and resource settings in version control?
Downtime and cutover Can the method provide a consistent final snapshot or change capture within your outage budget?
Security How are credentials protected, and which hosts, ports, TLS settings, and privileges are required?
Observability and retries Can you identify rejected rows, resume or repeat safely, and retain logs?
Scale and throughput What are the measured results for your data size, indexes, network, and target hardware? Do not rely on a universal benchmark.
Manual PostgreSQL work How much application SQL, routine code, and operational behavior must change after the data copy?

For many teams, the practical answer is hybrid: use pgloader for the repeatable base-table transfer and handle unsupported objects, cutover coordination, and application changes as separately tested deliverables.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Troubleshooting common failures

Authentication or connection errors

Confirm the hostname resolves from the pgloader machine, the port is reachable, the server allows that client address, and the credentials are valid. Check whether TLS is mandatory and whether the PostgreSQL role has permission to create the requested schema and objects.

Invalid date or timestamp errors

Find the offending source values, especially zero dates and timezone-sensitive timestamps. Apply a narrowly scoped cast using zero-dates-to-null only when null is correct, or cleanse the source and rerun the rehearsal.

Numeric overflow

Compare the source column’s unsigned range with the selected PostgreSQL type. Widen the destination type or reject and remediate out-of-range data before loading; do not assume a signed integer is equivalent to an unsigned MySQL column.

Duplicate keys after loading

Check whether the target was nonempty, whether the source contains duplicate values that MySQL tolerated under a different collation or constraint set, and whether a sequence was reset. Recreate the target for a clean rehearsal and inspect constraints before retrying.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Encoding or garbled text

Verify the source connection character set, table metadata, and target encoding. Use the documented table-name decoding option when identifiers—not data—are encoded incorrectly, and test representative multilingual text after loading.

Application behavior changed

Compare collation and case-sensitivity assumptions, null behavior, timestamp zones, auto-generated keys, and SQL syntax. PostgreSQL is not a drop-in MySQL SQL dialect; migrate application queries and routines as part of the cutover plan.

A concise production checklist

  • Target database and least-privilege migration role created.
  • Both endpoints reachable with protected credentials.
  • Source inventory completed, including unsupported objects.
  • Version-controlled load file reviewed.
  • Table filters, renames, schemas, casts, and memory settings documented.
  • Disposable rehearsal completed with warnings and rejected rows resolved.
  • Views, triggers, procedures, and functions rewritten and tested.
  • Final consistency and cutover window approved.
  • Row counts, constraints, indexes, sequences, types, aggregates, and application queries validated.
  • Rollback conditions, retained MySQL access, and migration artifacts agreed.

Bottom line

Start with pgloader’s one-line command to expose compatibility problems, then move to a version-controlled load file for every serious migration. Explicitly map zero dates, timestamps, unsigned values, booleans, enums, binary data, and generated keys; rehearse on a disposable target; and validate more than row counts. pgloader can move the relational foundation efficiently, but PostgreSQL rewrites for unsupported views, triggers, stored routines, and application SQL remain your responsibility.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.