views:

130

answers:

4

I'm having two tables:
A [ID, column1, column2, column3]
B [ID, column1, column2, column3, column4]

A table will always be subset of B table (meaning all columns of A are also in B).

I want to update a record with a specific ID in B with their data from A for all columns of A. This ID exists both in A and B.

Is there an UPDATE syntax or any other way to do that without specifying the column names, just saying "set all columns of A"?

I'm using postgresql, so a specific non-standard command is also accepted (however, not preferred).

Thanks.

+1  A: 

you can build and execute dynamic sql to do this, but its really not ideal

Daniel Brink
I thought about that. I thought I could make my query compliant with later changes to both tables, but dynamic sql seems to be too complicated than just specify all fields and forget about forward compatibility.
Nir
yes, it will be complicated, but should be forward compatible with later columns being added or removed. You'll have to first do a query to get the column names from both tables, then match the column names and then write the dynamic sql to do the update based on the matching column names. a fun project actually :)
Daniel Brink
A: 

Try Following

Update A a, B b, SET a.column1=b.column1 where b.id=1

EDITED:- Update more than one column

Update A a, B b, SET a.column1=b.column1, a.column2=b.column2 where b.id=1
Salil
I don't understand how it copies column1, column2 and column3. And I do need to explicit mention column1.
Nir
+1  A: 

Not necessarily what you asked, but maybe using postgres inheritance might help?

CREATE TABLE A (
    ID            int,
    column1       text,
    column2       text,
    column3       text
);

CREATE TABLE B (
    column4       text
) INHERITS (A);

This avoids the need to update B.

But be sure to read all the details.

Otherwise, what you ask for is not considered a good practice - dynamic stuff such as views with SELECT * ... are discouraged (as such slight convenience might break more things than help things), and what you ask for would be equivalent for the UPDATE ... SET command.

Unreason
I not sure how inheritance will solve this. Do you mean adding an update trigger for A that also updates B?I don't want to synchronize A with B all the time, only upon request. And in such case, I can't use the triggers.
Nir
Yes, if it is only in certain cases then inheritance would not work and in that case I advise against dynamic query approach.(still there are ways to achieve this using postgres procedural languages. also if you want to use triggers you can use them as well - by adding sync field for example firing trigger only when it is set).
Unreason
A: 

You can use the non-standard FROM clause.

UPDATE b
SET column1 = a.column1,
  column2 = a.column2,
  column3 = a.column3
FROM a
WHERE a.id = b.id
AND b.id = 1
Scott Bailey