Skip to content
Advertisement

Set empty strings (”) to NULL in the whole database

In my database are many text columns where values are empty strings (''). The empty strings need to be set to NULL. I do not know the exact schemas, tables and columns in this database or rather I want to write a general solution which can be reused.

How would I write a query / function to find all text columns in all tables in all schemas and update all columns with empty strings ('') to NULL?

Advertisement

Answer

The most efficient way to achieve this:

  • Run a single UPDATE per table.
  • Only update nullable columns (not defined NOT NULL) with any actual empty string.
  • Only update rows with any actual empty string.
  • Leave other values unchanged.

This related answer has a plpgsql function that builds and runs the UPDATE command using system catalog pg_attribute automatically and safely for any given table:

Using the function f_empty2null() from this answer, you can loop through selected tables like this:

Careful! This updates all empty strings in all columns of all user tables in the DB. Be sure that’s what you want or it might nuke your database.

You need UPDATE privileges on all selected tables, of course.

As a child safety device I commented the payload.

You may have noted that I use the system catalogs directly, not the information schema (which would work, too). About this:

For repeated use

Here is an integrated solution for repeated use. Without safety devices:

Call:

Returns:

Note how I escaped both table and columns names properly!

Consider:

Careful! Same warning as above.
Also consider the basic explanation in the answer I linked above:

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement