1

I found the similar question and solution for the SQL server. I want to replace all my null values with zero or empty strings. I can not use the update statement because my table has 255 columns and using the update for all columns will consume lots of time.

Can anyone suggest to me, how to update all the null values from all columns at once in PostgreSQL?

2
  • 1
    You can't. You have to specify each column, but you could write a script which uses dynamic SQL to iterate over all columns. Commented Jan 10, 2022 at 4:00
  • I am looking for a similar kind of solution in PostgreSQL: stackoverflow.com/a/7930913/9354344 Commented Jan 10, 2022 at 4:09

1 Answer 1

4

If you want to replace the data on the fly while selecting the rows you need:

SELECT COALESCE(maybe_null_column, 0)

If you want the change to be saved on the table you need to use an UPDATE. If you have a lot of rows you can use a tool like pg-batch

You can also create a new table and then swap the old one and the new one:

# Create new table with updated values
CREATE TABLE new_table AS
SELECT COALESCE(maybe_null_column, 0), COALESCE(maybe_null_column2, '')
FROM my_table;

# Swap table
ALTER TABLE my_table RENAME TO obsolete_table;
ALTER TABLE new_table RENAME TO my_table;
Sign up to request clarification or add additional context in comments.

1 Comment

Actually, there are lots of columns, I can not write each column name in the query. I want to update the values on the same table.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.