cheslijones
cheslijones

Reputation: 9194

Change all columns in table of a certain data type in PostgreSQL 9.6

It seems like several months ago I came across a SO question covering this but I can't seem to find it now.

Basically, I want to do two things.

First, a number of tables were made with several columns numeric(20,2) and I want to just change them all to numeric. The statement is simple enough for one column:

ALTER TABLE table_name
ALTER COLUMN code
TYPE numeric;

Takes care of that.

Second, on these columns I want to remove any trailing zeros:

UPDATE table_name
SET code = replace(replace(code::text, '.50', '.5'), '.00', '')::numeric;

Having difficulty figuring out how to automate it so I only have to specify the table and it will clean up the table. Pretty sure this is possible.

Upvotes: 3

Views: 2695

Answers (1)

rd_nielsen
rd_nielsen

Reputation: 2459

You can find all of the columns with the data type that you want to change with a statement like:

select column_name, table_name
from information_schema.columns
where data_type='numeric'
    and numeric_precision = 20
    and numeric_scale = 2;

You can iterate over the result with a custom function or with a DO command such as:

do $$
declare
t record;
begin
    for t IN select column_name, table_name
            from information_schema.columns
            where data_type='numeric'
                and numeric_precision = 20
                and numeric_scale = 2;
    loop
        execute 'alter table ' || t.table_name || ' alter column ' || t.column_name || ' type numeric';
    end loop;
end$$;

Also, to remove trailing zeroes, a more general solution is to cast the value to float or double precision and then back to numeric, e.g:

set code = cast(cast(code as double precision) as numeric);

Upvotes: 9

Related Questions