Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a query in postgres

insert into c_d (select * from cd where ak = '22019763');

And I get the following error

ERROR:  column "region" is of type integer but expression is of type character varying
HINT:  You will need to rewrite or cast the expression.
share|improve this question
3  
are you sure the c_d and and cd table have the same fields order? otherwise explicitly indicate the fields in your query –  Michael Buen Nov 6 '09 at 9:55
 
There are more fields in the c_d table than in the cd table. Are there any other ways of doing this? –  Roland Nov 6 '09 at 10:10
add comment

2 Answers

up vote 1 down vote accepted

An "INSERT INTO table1 SELECT * FROM table2" depends entirely on order of the columns, which is part of the table definition. It will line each column of table1 up with the column of table2 with the same order value, regardless of names.

The problem you have here is whatever column from cd with the same order value as c_d of the table "region" has an incompatible type, and an implicit typecast is not available to clear the confusion.

INSERT INTO SELECT * statements are stylistically bad form unless the two tables are defined, and will forever be defined, exactly the same way. All it takes is for a single extra column to get added to cd, and you'll start getting errors about extraneous extra columns.

If it is at all possible, what I would suggest is explicitly calling out the columns within the SELECT statement. You can call a function to change type within each of the column references (or you could define a new type cast to do this implicitly -- see CREATE CAST), and you can use AS to set the column label to match that of your target column.

If you can't do this for some reason, indicate that in your question.

share|improve this answer
add comment

Check out the PostgreSQL insert documentation. The syntax is:

INSERT INTO table [ ( column [, ...] ) ] { DEFAULT VALUES | VALUES ( { expression | DEFAULT } [, ...] ) | query }

which here would look something like:

INSERT INTO c_d (column1, column2...) select * from cd where ak = '22019763'

This is the syntax you want to use when inserting values from one table to another where the column types and order are not exactly the same.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.