I need to insert some data from one table to another in Postgresql. Schema of the table I need to fill with data looks like this:
create table public.test_int_table( id int, description text, hash_code int );
The issue is that id column in another table is of bigint type. So when I try to insert biting data into int column I get an exception:
insert into public.test_int_table select * from public.test_table SQL Error [22003]: ERROR: integer out of range
How can I trim bigint data for insert in Postgresql? Usual cast operator seems to work only for upcasting (from int to bigint and not otherwise). Id it not a constantly increasing value and it fits into int in most of the cases so I don’t really care about loosing precision here.
Advertisement
Answer
This could be quite dangerous, because you might get duplicates. But you can use direct comparison and then handle the values that are too large. The following “trims” them to NULL
:
insert into public.test_int_table (id, description, hash_code) select (case when id < 2^31 - 1 then id::int end) as id, description, hash_code from public.test_table;
Note that this might totally mess up the data. If you can change the value, then you could replace with a new value:
insert into public.test_int_table (id, description, hash_code) select dense_rank() over (order by id), description, hash_code from public.test_table;