Home › Insights › Blogs › App Modernization

How to Convert Oracle to PostgreSQL: Data Types, SQL and PL/SQL

Sajid Hussain Sajid Hussain
Last updated: 20 Nov 2026
Get an AI summary of this post on Perplexity ChatGPT Gemini
Key takeaways
Tables, columns and most data types convert mechanically. Packages, package state and the Oracle dialect inside application SQL are the engineering work.
Four type decisions change application behaviour rather than storage: NUMBER without precision, VARCHAR2 counted in bytes, DATE carrying a time component, and TIMESTAMP WITH TIME ZONE normalising to UTC.
PL/pgSQL resembles PL/SQL closely enough that the first stretch feels fast, which disguises how different packages, autonomous transactions and transaction control are.
A package becomes a schema of functions, but package-level variables have no equivalent and rehoming them changes every caller.

Converting Oracle to PostgreSQL splits cleanly in two. Data types, tables, constraints, views and straightforward procedures convert almost mechanically, and tools do most of it. Packages, package state, autonomous transactions, optimizer hints and the Oracle dialect scattered through application SQL do not convert at all, and that second half is where the schedule lives. For where this sits in the wider project, see the step-by-step migration guide.

Oracle to PostgreSQL data type mapping

Most types have a direct equivalent and can be taken from a tool’s default without thought. Four cannot, because the choice changes what the application computes rather than how the value is stored. Those four are worth deciding deliberately, against the actual data, before a single object is generated.

Oracle to PostgreSQL data type mapping, and what each one can break.
Oracle typePostgreSQL typeWatch out for
NUMBER(p,0)smallint / integer / bigint by precisionDo not default everything to numeric; integer arithmetic is materially faster
NUMBER(p,s)numeric(p,s)Direct equivalent
NUMBER (no precision)numeric, or integer / double precision after profilingProfile the actual values first; the declaration tells you nothing
VARCHAR2(n) / NVARCHAR2(n)varchar(n) or textOracle n may count bytes; PostgreSQL counts characters. Multi-byte data overflows
CHAR(n)char(n)Blank-padding and comparison semantics differ; prefer text unless the padding is load-bearing
DATEtimestamp(0)Oracle DATE includes time of day. Mapping to date discards it without an error
TIMESTAMP WITH TIME ZONEtimestamptzPostgreSQL normalises to UTC and does not retain the original zone
CLOB / NCLOB / LONGtextNo practical size limit; the problem is transfer and memory, not storage
BLOB / LONG RAWbyteaVery large objects may need large-object storage and their own load pass
RAW(16) used as a GUIDuuidCheck how the application formats and compares them before converting
BINARY_FLOAT / BINARY_DOUBLEreal / double precisionDirect equivalent
XMLTYPExmlXPath function coverage differs; stored XML queries need testing

One decision sits outside the table and has to be made before anything is generated: identifier case. Oracle folds unquoted identifiers to upper case, PostgreSQL folds them to lower case, and a converter that quotes everything leaves "EMPLOYEE_ID" and employee_id as different columns permanently. Pick unquoted lower case unless something specific forbids it, and apply the rule to the schema and the applications in one change.

Oracle SQL functions and their PostgreSQL equivalents

Most of this is substitution, and a converter handles it. Two rows in the table below are not substitutions at all, because the Oracle and PostgreSQL versions compute different things: ROWNUM and SYSDATE. Treat those as rewrites that need a decision, not as find and replace.

Oracle SQL constructs and their PostgreSQL equivalents.
OraclePostgreSQL
NVL(a, b)COALESCE(a, b)
NVL2(a, b, c)CASE WHEN a IS NOT NULL THEN b ELSE c END
DECODE(x, 1, ‘a’, ‘b’)CASE WHEN x = 1 THEN ‘a’ ELSE ‘b’ END
SELECT … FROM DUALSELECT … with no FROM clause
seq.NEXTVAL / seq.CURRVALnextval(‘seq’) / currval(‘seq’)
ROWNUM <= 10LIMIT 10, but see the ordering note below
a.id = b.id(+)LEFT JOIN
MINUSEXCEPT
SYSDATELOCALTIMESTAMP(0), or clock_timestamp() inside a long transaction
SUBSTR(s, -3)right(s, 3)
INSTR(s, t)position(t in s)
CONNECT BYWITH RECURSIVE

ROWNUM is assigned before ORDER BY runs. In Oracle, WHERE ROWNUM <= 10 ORDER BY created_at DESC returns ten arbitrary rows and then sorts them, which is almost never what the author intended. Converting it to ORDER BY created_at DESC LIMIT 10 gives the ten most recent, and that is a behaviour change. Decide which of the two you want rather than inheriting whichever the converter produced.

now() is not SYSDATE. PostgreSQL’s now() and CURRENT_TIMESTAMP return the moment the transaction began and hold that value for its duration, while Oracle’s SYSDATE advances. Audit columns usually want now(). Anything measuring elapsed time inside a transaction needs clock_timestamp(), or every row gets the same timestamp.

Converting PL/SQL procedures and functions

PL/pgSQL was designed to look like PL/SQL. Declarations, cursors, loops, %TYPE and %ROWTYPE, and exception blocks all carry across with small edits, and that familiarity is both the help and the trap: the first stretch moves quickly and then the remainder does not move at all.

The edits that recur. RAISE_APPLICATION_ERROR becomes RAISE EXCEPTION. Every function body needs a language declaration and dollar quoting. And a bare SELECT ... INTO no longer raises when it finds nothing: PostgreSQL only does that with STRICT, where the documentation states that the command “must return exactly one row or a run-time error will be reported, either NO_DATA_FOUND (no rows) or TOO_MANY_ROWS (more than one row)”. Omitting STRICT turns an Oracle NO_DATA_FOUND handler into dead code that silently leaves the variable NULL.

-- Oracle
CREATE OR REPLACE PROCEDURE set_tier(p_id NUMBER) IS
  v_tier VARCHAR2(10);
BEGIN
  SELECT DECODE(SIGN(total - 10000), 1, 'GOLD', 'STANDARD')
    INTO v_tier
    FROM accounts WHERE id = p_id;

  UPDATE accounts SET tier = v_tier WHERE id = p_id;
EXCEPTION
  WHEN NO_DATA_FOUND THEN
    RAISE_APPLICATION_ERROR(-20001, 'Account not found');
END;
-- PostgreSQL
CREATE OR REPLACE PROCEDURE set_tier(p_id bigint)
LANGUAGE plpgsql AS $$
DECLARE
  v_tier text;
BEGIN
  SELECT CASE WHEN total > 10000 THEN 'GOLD' ELSE 'STANDARD' END
    INTO STRICT v_tier
    FROM accounts WHERE id = p_id;

  UPDATE accounts SET tier = v_tier WHERE id = p_id;
EXCEPTION
  WHEN NO_DATA_FOUND THEN
    RAISE EXCEPTION 'Account not found' USING ERRCODE = 'P0001';
END;
$$;

Procedure or function? PostgreSQL 11 added procedures that may contain COMMIT and ROLLBACK. Functions still cannot. Any converted code that commits mid-body has to become a procedure, and every caller has to switch from SELECT to CALL. Deciding this per object as you go is slower than deciding it once from the inventory.

Install orafce early. The extension supplies PostgreSQL implementations of a wide range of Oracle built-in functions and some DBMS_ package behaviour. Installing it before conversion starts removes a large amount of mechanical rewriting and, more usefully, makes the differences that remain easier to see.

What to do with Oracle packages

A package has no PostgreSQL equivalent, and the PostgreSQL documentation is direct about the substitute: “use schemas to organize your functions into groups”. That part is clean. The part that is not is package state, because, as the same page puts it, since there are no packages, “there are no package-level variables either.”

An Oracle package converted into a PostgreSQL schema of functions plus session-level state An Oracle package containing a spec, a body of twelve procedures, and package-level variables. The spec and body become a PostgreSQL schema holding twelve functions. The package variables have no equivalent and move separately into session settings, set with set_config and read with current_setting. Oracle Package ORDERS_PKG Spec Body: 12 procedures Package variables Session state, no equivalent PostgreSQL Schema orders 12 functions orders.create_order() Session settings set_config() current_setting() An Oracle package converted into a PostgreSQL schema of functions plus session-level state An Oracle package containing a spec, a body of twelve procedures, and package-level variables. The spec and body become a PostgreSQL schema holding twelve functions. The package variables have no equivalent and move separately into session settings, set with set_config and read with current_setting. Oracle Package ORDERS_PKG Spec Body: 12 procedures Package variables PostgreSQL Schema orders 12 functions orders.create_order() Session settings set_config() current_setting()
The body converts almost mechanically. The package variables are the line item, because rehoming them changes every caller that read or wrote them.

Three options for that state, each suiting a different shape of variable. Session configuration parameters suit scalar values and need a dotted name to be accepted as a custom setting. A temporary table suits row sets and anything the package treated as a session-scoped cache. An explicit argument is the cleanest of the three and only works where the variable was effectively being passed through anyway.

-- Oracle: a package-level variable, persisting for the session
CREATE OR REPLACE PACKAGE orders_pkg AS
  g_region VARCHAR2(10);
  PROCEDURE set_region(p_region VARCHAR2);
  FUNCTION  current_region RETURN VARCHAR2;
END orders_pkg;
-- PostgreSQL: a schema of functions, with the state in a session setting
CREATE SCHEMA orders;

CREATE FUNCTION orders.set_region(p_region text) RETURNS void
LANGUAGE plpgsql AS $$
BEGIN
  PERFORM set_config('orders.region', p_region, false);
END;
$$;

CREATE FUNCTION orders.current_region() RETURNS text
LANGUAGE sql AS $$
  SELECT current_setting('orders.region', true);
$$;

The second argument to current_setting is what stops an unset parameter raising an error, returning NULL instead. That matters more than it looks: an Oracle package variable starts life as NULL on every new session, and without that argument the converted code raises where the original returned nothing.

Decide the pattern once and apply it to every package. A package of twenty procedures is twenty functions plus one state decision, and the state decision reaches every caller that read or wrote the variable, which is the part that makes a per-package choice expensive. If the estate runs to hundreds of packages, that single decision is worth more than any amount of conversion tooling, which is the kind of thing an Oracle to PostgreSQL migration services assessment is for.

Hundreds of packages to convert? See how much can be automated.

Send us the object counts and we will run an assessment against your actual code: an object inventory, a conversion-complexity grading per object type, and the constructs that will need rewriting by hand.

Get a Free Oracle Migration Assessment

Constructs with no direct equivalent

Five Oracle constructs have a workaround rather than a replacement. Each needs a decision rather than a conversion rule, and each one found late is a redesign rather than an edit, which is why they belong in the assessment and not in the conversion sprint.

Autonomous transactions. PRAGMA AUTONOMOUS_TRANSACTION commits independently of its caller, and a PostgreSQL function cannot. The stand-ins are dblink, which opens a second connection back to the same database, and the pg_background extension. Both work, and both give the logging or auditing code that depended on the pragma a new failure mode to handle.

Global temporary tables. Oracle’s are a permanent definition with session-private data. PostgreSQL creates and drops a temporary table per session, so the definition has to be issued at session start or wrapped in the function that uses it. Where the table was only ever a scratch area, an unlogged table or a CTE is usually a better answer than reproducing the original shape.

Synonyms. There is no synonym object. A view reproduces a read-only synonym, and search_path covers the common case of pointing a schema name somewhere else. Neither is a complete substitute, so inventory how the synonyms were actually used before choosing.

Database links. These become foreign data wrappers: postgres_fdw to another PostgreSQL instance, oracle_fdw to an Oracle one, or dblink for ad-hoc queries. The syntax changes everywhere the link was referenced.

Optimizer hints. PostgreSQL has no native hint mechanism, so hints are dropped in conversion. Better statistics is the first answer, a query rewrite the second, and the pg_hint_plan extension the third, because a plan pinned by a hint cannot adapt as the data changes. These sit alongside the behaviour differences in the challenges that cause most defects.

What tools convert and what you rewrite

Converters handle the mechanical layer well: tables, constraints, views, sequences, indexes, and a share of procedural code. Ora2Pg covers the widest object range and is free. AWS Schema Conversion Tool and Google Cloud Database Migration Service do the equivalent inside their own platforms. None of them converts package state, autonomous transactions or optimizer hints, because there is nothing to convert those into. Budget the engineer review as work, not as a check. What each one covers in detail is set out in migration tools compared.

Planning an Oracle to PostgreSQL migration?

Tell us the Oracle version, roughly how large the database is and where you want to land. You will talk to a database architect, not an account manager.

Talk to a Database Architect
#convert oracle to postgres #plsql to plpgsql conversion #oracle to postgresql data type mapping #convert oracle stored procedures to postgresql #oracle packages in postgresql #oracle to postgresql sql equivalents
Share

Frequently asked questions

How should Oracle DATE columns be mapped in PostgreSQL?
To timestamp(0), not to date. An Oracle DATE carries a time component down to the second, so mapping it to a PostgreSQL date discards the time of day without raising an error. Reports grouped by day keep agreeing with the old system, while anything ordering within a day or calculating an elapsed duration starts returning different answers.
Can PostgreSQL run Oracle PL/SQL directly?
No. PL/pgSQL was designed to resemble PL/SQL, so declarations, cursors, loops and exception blocks look familiar, but it is a different language and nothing runs unchanged. The orafce extension supplies PostgreSQL implementations of many Oracle built-in functions, which removes a chunk of the mechanical rewriting without removing the need to convert.
What replaces Oracle sequences and NEXTVAL?
PostgreSQL has sequences too, so seq.NEXTVAL becomes nextval('seq') and seq.CURRVAL becomes currval('seq'). For surrogate keys, prefer a GENERATED BY DEFAULT AS IDENTITY column, which owns its sequence and removes the trigger Oracle schemas often used. Reset every sequence above its column's maximum value after loading data.
Sajid Hussain
Lead Database Architect, Kansoft

Lead Database Architect at Kansoft with 21 years of experience designing, migrating and tuning database platforms for enterprises across India, UAE, USA, Europe and Australia. He writes about Oracle to PostgreSQL migration and the engineering decisions that determine whether one finishes on schedule.

Need help with your next project?

Our engineering experts can help you build something exceptional.

Book a Free Call