Emulate Oracle’s NVL function by using COALESCE (or a tiny wrapper) to substitute default values when a column is NULL.
NVL(expr1, expr2) returns expr1 unless it is NULL, in which case it returns expr2. PostgreSQL lacks NVL but offers the ANSI-standard COALESCE that behaves the same when given two arguments.
Use COALESCE(column, default).It inspects arguments left to right and returns the first non-NULL value, matching NVL when only two arguments are supplied.
SELECT COALESCE(email,'unknown@example.com') AS email FROM Customers;
returns a fallback address whenever email is NULL.
Yes.COALESCE supports any number of arguments, letting you chain fallbacks such as column, derived value, then literal default.
Teams migrating from Oracle often create CREATE FUNCTION nvl(a anyelement,b anyelement)
that simply calls COALESCE for smoother porting. Use it sparingly to avoid hiding PostgreSQL idioms from new developers.
1) Always cast literals to the target type to avoid ambiguous-type errors. 2) Keep data types consistent across all COALESCE arguments.3) Prefer IS DISTINCT FROM for NULL-safe comparisons.
ERROR: function nvl(text, unknown) does not exist → replace with COALESCE or create a typed NVL wrapper. ERROR: could not determine data type → cast each literal, e.g., '0'::numeric
.
.
No. COALESCE is part of PostgreSQL’s core and is optimized; performance is comparable or faster than a user-defined NVL wrapper.
Yes. Create a functional index such as CREATE INDEX ON Customers (COALESCE(email,'unknown@example.com'));
to speed up searches.
Absolutely. Use COALESCE(data->>'phone', 'not-provided')
to supply defaults when a key is missing or NULL.