To replace NULL values with an empty string, use COALESCE(column_name, ''). You'll need to know the column name and do this for each column name.

To convert a column into text, you can use column_name::TEXT or CAST(column_name AS TEXT). You'll also need to know the column names.

If you just want something quick and dirty that achieves something close to your goal, you can convert the whole row tuple into text:

SELECT my_table::TEXT FROM my_table

In this case, you'll get parentheses around the row which each value separated by a column. It's generally not ideal, and you'll lose the column name information, but could be handy if you want a quick and simple text search for example. (I'm sure there are better solutions to that particular problem.)

Another option, which may depend on the client you're using, is to use COPY (or psql's \copy) and export your data in CSV format to the standard output or to a file. There are more details on this in other answers.

The default CSV value for NULL is the empty string, but you could have quotes or something else using WITH NULL AS ...


You could also use some dynamic PL/pgSQL to create your query. Building the query could look like this:

SELECT 'SELECT '
       || string_agg('COALESCE('
                     || attname::TEXT
                     || '::TEXT, '''')' , ',' ORDER BY attnum)
       || ' FROM my_table'
    INTO q
    FROM pg_attribute WHERE  attrelid = 'my_table'::regclass
     AND attnum > 0 AND NOT attisdropped;

It's then a problem regarding how you want to return those results (since you'd may to know the columns in advance for using record or row types).

Since you're only interested in text, you might as well return each row as a TEXT array:

CREATE OR REPLACE FUNCTION my_function() RETURNS SETOF TEXT[]
AS $$
DECLARE
    q TEXT;
    r TEXT[];
BEGIN
    SELECT 'SELECT ARRAY['
           || string_agg('COALESCE('
                         || attname::TEXT
                         || '::TEXT, '''')' , ',' ORDER BY attnum)
           || '] FROM my_table'
        INTO q
        FROM pg_attribute WHERE  attrelid = 'my_table'::regclass
         AND attnum > 0 AND NOT attisdropped;
    FOR r IN EXECUTE q
    LOOP
        RETURN NEXT r;
    END LOOP;
END
$$ LANGUAGE plpgsql;

SELECT my_function();
Answer from Bruno on Stack Overflow
🌐
Readthedocs
pyhelpers.readthedocs.io › en › 2.0.0 › _generated › pyhelpers.dbms.PostgreSQL.null_text_to_empty_string.html
PostgreSQL.null_text_to_empty_string - PyHelpers
column_names (str | list | None) – (List of) column name(s) to convert null values to empty strings; if column_names=None (default), all available columns are included. schema_name (str | None) – Name of the schema; defaults to None. ... >>> from pyhelpers.dbms import PostgreSQL >>> from ...
Top answer
1 of 1
1

To replace NULL values with an empty string, use COALESCE(column_name, ''). You'll need to know the column name and do this for each column name.

To convert a column into text, you can use column_name::TEXT or CAST(column_name AS TEXT). You'll also need to know the column names.

If you just want something quick and dirty that achieves something close to your goal, you can convert the whole row tuple into text:

SELECT my_table::TEXT FROM my_table

In this case, you'll get parentheses around the row which each value separated by a column. It's generally not ideal, and you'll lose the column name information, but could be handy if you want a quick and simple text search for example. (I'm sure there are better solutions to that particular problem.)

Another option, which may depend on the client you're using, is to use COPY (or psql's \copy) and export your data in CSV format to the standard output or to a file. There are more details on this in other answers.

The default CSV value for NULL is the empty string, but you could have quotes or something else using WITH NULL AS ...


You could also use some dynamic PL/pgSQL to create your query. Building the query could look like this:

SELECT 'SELECT '
       || string_agg('COALESCE('
                     || attname::TEXT
                     || '::TEXT, '''')' , ',' ORDER BY attnum)
       || ' FROM my_table'
    INTO q
    FROM pg_attribute WHERE  attrelid = 'my_table'::regclass
     AND attnum > 0 AND NOT attisdropped;

It's then a problem regarding how you want to return those results (since you'd may to know the columns in advance for using record or row types).

Since you're only interested in text, you might as well return each row as a TEXT array:

CREATE OR REPLACE FUNCTION my_function() RETURNS SETOF TEXT[]
AS $$
DECLARE
    q TEXT;
    r TEXT[];
BEGIN
    SELECT 'SELECT ARRAY['
           || string_agg('COALESCE('
                         || attname::TEXT
                         || '::TEXT, '''')' , ',' ORDER BY attnum)
           || '] FROM my_table'
        INTO q
        FROM pg_attribute WHERE  attrelid = 'my_table'::regclass
         AND attnum > 0 AND NOT attisdropped;
    FOR r IN EXECUTE q
    LOOP
        RETURN NEXT r;
    END LOOP;
END
$$ LANGUAGE plpgsql;

SELECT my_function();
Discussions

How to convert empty string ('') as NULL in postgres in config level.
Well, if you don't want to use the obvious and simple solution nullif(.., '') is null then you need to check for both an empty string and null: where the_column is null or the_column = '' Note that Oracle's behaviour is non-standard and no other DBMS treats '' the same as null in comparisons. Btw: your condition WHERE ( SELECT '' FROM dual) IS NULL could be simplified to WHERE '' IS NULL. There is no need to use a SELECT statement to use a constant value. Edit: it just occurred to me what you might mean with "config level". There is no configuration option that will make Postgres behave like Oracle here. If you really need this, you will have to convert empty strings to null when you save them (e.g. through triggers). However, that will still not make Postgres behave like Oracle. Because Oracle also is non-standard when the concatenation operator || is involved (just the other way round: null is treated as ''). In general all expressions involving NULL should yield NULL. However in Oracle 'foo'||null yields 'foo' whereas in every other database that yields null - and there is no way you can make Postgres do that (unless you change Postgres' source code) So you will have to bite the bullet and adjust your code. If this is a migration, then you only need to do it once. If you need to support Postgres and Oracle from within the same code base, then you'll need to find a way to use different SQL depending on which database you connect to. More on reddit.com
🌐 r/PostgreSQL
15
9
November 26, 2021
sql - PostgreSql remove difference between null and empty string - Stack Overflow
Making the OWASP top ten in the vibe code... Creating checkpoints by gaslighting a Postgres... More on stackoverflow.com
🌐 stackoverflow.com
sql - Cast string to number, interpreting null or empty string as 0 - Stack Overflow
I have a Postgres table with a string column carrying numeric values. I need to convert these strings to numbers for math, but I need both NULL values as well as empty strings to be interpreted as ... More on stackoverflow.com
🌐 stackoverflow.com
php - How to convert empty to null in PostgreSQL? - Stack Overflow
The Postgres extension uses pg_prepare for this. They have the distinct advantage of, say, allowing you to pass a PHP null instead of having to worry about all of that null-detection and quoting. If you insist on keeping toDB as-is, consider adding one of the pg_escape_ functions, like pg_escape_string... More on stackoverflow.com
🌐 stackoverflow.com
🌐
AWS
aws.amazon.com › blogs › database › handle-empty-strings-when-migrating-from-oracle-to-postgresql
Handle empty strings when migrating from Oracle to PostgreSQL | Amazon Web Services
May 23, 2022 - Converting code from Oracle to a PostgreSQL-compatible engine may involve multiple corner cases that are important for your overall migration success. Handling empty strings (”) with all NULL-compatible operators or expressions while migrating from Oracle to PostgreSQL is vital to achieve ...
🌐
Reddit
reddit.com › r/postgresql › how to convert empty string ('') as null in postgres in config level.
r/PostgreSQL on Reddit: How to convert empty string ('') as NULL in postgres in config level.
November 26, 2021 -

HI Team,

Kindly help to convert empty string to null in postgres.

SELECT 1 FROM DUAL WHERE ( SELECT '' FROM dual) IS NULL

In the above query SELECT '' FROM dual returns empty string in postgres. but in oracle it is returning as null.

hence there is a functionality mismatch in the output. how can i convert this empty string as null in config level. other than nullif function.

Top answer
1 of 4
17
Well, if you don't want to use the obvious and simple solution nullif(.., '') is null then you need to check for both an empty string and null: where the_column is null or the_column = '' Note that Oracle's behaviour is non-standard and no other DBMS treats '' the same as null in comparisons. Btw: your condition WHERE ( SELECT '' FROM dual) IS NULL could be simplified to WHERE '' IS NULL. There is no need to use a SELECT statement to use a constant value. Edit: it just occurred to me what you might mean with "config level". There is no configuration option that will make Postgres behave like Oracle here. If you really need this, you will have to convert empty strings to null when you save them (e.g. through triggers). However, that will still not make Postgres behave like Oracle. Because Oracle also is non-standard when the concatenation operator || is involved (just the other way round: null is treated as ''). In general all expressions involving NULL should yield NULL. However in Oracle 'foo'||null yields 'foo' whereas in every other database that yields null - and there is no way you can make Postgres do that (unless you change Postgres' source code) So you will have to bite the bullet and adjust your code. If this is a migration, then you only need to do it once. If you need to support Postgres and Oracle from within the same code base, then you'll need to find a way to use different SQL depending on which database you connect to.
2 of 4
7
There is no such setting. You could theoretically modify Pg source to be less standards-compliant and more "looks like oracle", but perhaps just ditch oraclisms?
🌐
PostgreSQL
postgresql.org › message-id › 20021212040347.81662.qmail@web80305.mail.yahoo.com
PostgreSQL: Re: convert NULL into a value
December 12, 2002 - --- Jonathan Man <jman(at)equityunderwriters(dot)com(dot)hk> wrote: > Hi, > > There is a function on the Oracle. That is > NVL(field, 0) to convert null into a value (e.g. > ZERO). > > Can I use this function on the PostgreSQL??
Top answer
1 of 2
100

There is the NULLIF() function:

SELECT NULLIF(var, '');

If var equals the 2nd parameter, you get NULL instead.
The example replaces the empty string '' with NULL.

There is no "empty string" for the type integer. Both parameters must be of compatible type, so sanitize your input in PHP.

If you did not define a column default, you can also just omit the column in the INSERT command and it will be filled with NULL (which is the default DEFAULT).

Check if the parameter is empty in PHP and don't include the column in the INSERT command if it is.

Or use the PHP literal NULL instead like Quassnoi demonstrates here.

The rest only makes sense for string types

To make absolutely sure, nobody can enter an empty string add a CHECK constraint to the table:

ALTER TABLE tr_view
ADD CONSTRAINT tr_view_age_not_empty CHECK (age <> '');

To avoid exceptions caused by this, you could add a trigger that fixes input automatically:

CREATE OR REPLACE FUNCTION trg_tr_view_avoid_empty()
  RETURNS trigger
  LANGUAGE plpgsql AS
$func$
BEGIN
   IF NEW.age = '' THEN
      NEW.age := NULL;
   END IF;

   IF NEW.month = '' THEN
      NEW.month := NULL;
   END IF;

   RETURN NEW;
END
$func$;

CREATE TRIGGER tr_view_avoid_empty
BEFORE INSERT OR UPDATE ON tr_view
FOR EACH ROW
WHEN (NEW.age = '' OR NEW.month = '')
EXECUTE FUNCTION trg_tr_view_avoid_empty();
2 of 2
9

While Erwin's answer about NULLIF is awesome, it doesn't address your syntax error.

Let's take a look at the query:

$query="Insert Into tr_view(name,age,month,year) values ({toDB($name)},{toDB($age)},{toDB($month)},{toDB($year)})

Earlier you defined a function called toDB. Unfortunately the syntax you are using here is not how to call a function from within a double-quoted string, so the curlies and toDB( bits are still being passed through. There are two alternatives:

  1. Concatenation using .:

    $query='insert Into tr_view(name,age,month,year) values (' . toDB($name) . ',' . toDB($age) . ',' . toDB($month) . ',' . toDB($year) . ')')
    
  2. You can interpolate a callable variable into a double-quoted string thusly:

    $fn = 'toDB';
    $query="Insert Into tr_view(name,age,month,year) values ({$fn($name)},{$fn($age)},{$fn($month)},{$fn($year)})";
    

The first is clear and sane, the second is vague to the unfamiliar and downright insane.

However, you still should not be assembling input like this. You still may be vulnerable to SQL injection attacks. You should be using prepared statements with parameterized placeholders.

The Postgres extension uses pg_prepare for this. They have the distinct advantage of, say, allowing you to pass a PHP null instead of having to worry about all of that null-detection and quoting.

If you insist on keeping toDB as-is, consider adding one of the pg_escape_ functions, like pg_escape_string, to the thing that builds quoted strings.

Find elsewhere
🌐
PostgreSQL
postgresql.org › docs › 8.3 › sql-copy.html
PostgreSQL: Documentation: 8.3: COPY
March 8, 2023 - The CSV format has no standard way to distinguish a NULL value from an empty string. PostgreSQL's COPY handles this by quoting. A NULL is output as the NULL string and is not quoted, while a data value matching the NULL string is quoted.
🌐
EnterpriseDB
enterprisedb.com › postgres-tutorials › how-null-and-empty-strings-are-treated-postgresql-vs-oracle
How NULL and empty strings are treated in PostgreSQL vs Oracle | EDB
This tells us that the empty string ... compared to regular values as if it were an empty string because it's a full-fledged NULL. So, empty strings cannot be stored in the database. However, if we have a single space, this isn't converted, as it isn't an empty string. The same goes for when we have any non-whitespace characters; it's all the same. But in PostgreSQL, the story ...
🌐
DB Vis
dbvis.com › thetable › postgresql-coalesce-function-handling-null-value
PostgreSQL COALESCE Function: Handling NULL Values
July 5, 2024 - COALESCE can be used with timestamps or dates in PostgreSQL to replace NULL values with strings, provided that you convert the column of type TIMESTAMP or DATE to string with a cast.
🌐
PostgreSQL
postgresql.org › message-id › cb13bf640806181022x1cf5d841s82586de4b8096e11@mail.gmail.com
PostgreSQL: migrating from mysql: need to convert empty string to null
June 18, 2008 - PostgreSQL objects to empty strings for certain column types, particularly numeric columns. We're trying to get this conversion done quickly, and so a solution involving customization of string to X type conversion is what we're after. ... CREATE OR REPLACE FUNCTION varchar_to_int_with_empty_string_handling(varchar) RETURNS integer AS $$ SELECT CASE WHEN $1 = '' THEN NULL ...
🌐
Narkive
pgsql-general.postgresql.narkive.com › A02yAksi › migrating-from-mysql-need-to-convert-empty-string-to-null
migrating from mysql: need to convert empty string to null
PostgreSQL objects to empty strings for certain column types, particularly numeric columns. We're trying to get this conversion done quickly, and so a solution involving customization of string to X type conversion is what we're after. What I first tried to do was, CREATE OR REPLACE FUNCTION varchar_to_int_with_empty_string_handling(varchar) RETURNS integer AS $$ SELECT CASE WHEN $1 = '' THEN NULL ...
🌐
GitHub
github.com › PostgREST › postgrest › issues › 1240
convert empty string to null · Issue #1240 · PostgREST/postgrest
February 12, 2019 - Would it be possible for postgrest to convert empty string values to null, (or have it as a configuration value) ?
Author: PostgREST
🌐
Reddit
reddit.com › r/database › convert empty string to null-value?
r/Database on Reddit: Convert empty String to null-Value?
May 21, 2019 -

Hello!

I am making an application with a postgres interface. The Framework I am working with allows me to to instantiate variables in the form of $var. The Postgres part is actually fine, the framework is what is causing me problems and I wanted to ask if I could solve this problem within postgres myself.

Say, in my framework I have a variable $var, which I have assigned $var = null

The crucial part looks like this:

case when $var is not null then name else 'NULLVALUE' end 
= coalesce($var , 'NULLVALUE')

If I do:

case when null is not null then name else 'NULLVALUE' end 
= coalesce(null , 'NULLVALUE')

Then the query works fine. However, the interface, translates $var = null as an empty string. So, in my query, instead of null, I have an empty string, like so:

case when  is not null then name else 'NULLVALUE' end 
= coalesce( , 'NULLVALUE')

Is there any workaround? Any way you would achieve this works for starters, really.

I was thinking that if we could actually check before running the query, so check if $var is an empty string or assign the values to variables within the postgres part and null to the empty values - is there a way to do this? (Aside from Rel Algebra (inc. calculus), Normalization and Database design, I've learnt how do many sorts of queries in SQL and how to manipulate tables - things such as this I haven't had experience with, I'm sorry)

While I am looking into a solution in my framework, there's just a handful of people who know their way around this. So while I've asked in this framework's respective forum, I've figured it might be faster, if there is a possible solution within postgres itself.

🌐
CommandPrompt Inc.
commandprompt.com › education › how-to-replace-null-values-with-default-values-in-postgresql
How to Replace Null Values With Default Values in PostgreSQL — CommandPrompt Inc.
February 1, 2023 - In Postgres, “NULL” refers to an entry with no value or missing entry. PostgreSQL offers various built-in functions and operators to work with null values, such as COALESCE() function, IS NULL operator, etc.
Address: 2950 Newmarket ST STE 101 - 231, 98226, Bellingham
🌐
ABCloudz
abcloudz.com › handling null and empty string differences in oracle and postgresql
Handling null and empty string differences in Oracle and PostgreSQL | ABCloudz
September 23, 2024 - For example, the following Oracle query works as expected: SELECT decode(NULL, NULL, 'is null', '1', '1', 'default') AS example_1, decode(NULL, '', 'is empty string', '1', '1', 'default') AS example_2 FROM dual; When using SCT to convert this to ...
🌐
Blogger
florentpousserot.blogspot.com › 2012 › 11 › postgresql-cast-null-or-empty-string-to.html
Florent Pousserot: Postgresql : Cast NULL or empty string to int
Actually, you can cast NULL to int, you just can't cast an empty string to int. Assuming you want NULL in the new column if data1 co...