Re: Copy data from one table to another

From: "Keith Worthington" <keithw(at)narrowpathinc(dot)com>
To: "Guido Barosio" <gbarosio(at)gmail(dot)com>, "Sean Davis" <sdavis2(at)mail(dot)nih(dot)gov>
Cc: "PostgreSQL Novice" <pgsql-novice(at)postgresql(dot)org>
Subject: Re: Copy data from one table to another
Date: 2006-02-25 03:31:43
Message-ID: 20060225032311.M7340@narrowpathinc.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-novice

> On Fri, 24 Feb 2006 19:19:58 +0000, Guido Barosio wrote
> > On 2/24/06, Sean Davis <sdavis2(at)mail(dot)nih(dot)gov> wrote:
> > > On 2/24/06 1:42 PM, "Keith Worthington" <keithw(at)narrowpathinc(dot)com> wrote:
> > >
> > > Hi All,
> > >
> > > Would someone be so kind as to remind me of the syntax
> > > required to copy data from one table to another?
> >
> > Hi, Keith. Will:
> >
> > Insert into table2 [column1, ...]
> > Select * from table1;
> >
> > Do what you want?
> >
> > Sean
>
> If you want an exact copy (using another method), without indexes or relying
> objects, you shall try:
>
> `SELECT * INTO table_b FROM table_a`
>
> Check the manpages, SELECT, or in the psql shell: \h SELECT
> --------------
>
> Another option:
>
> pg_dump the data as INSERT replacing the table name on the result with
> the new table name, then psql'it.
>
> ----------
>
> Another option:
>
> run a classic pg_dump, using COPY, and replace the table name with the
> new one.
>
> -------
>
> Consider in all cases, that the index maintenance will be a cost if you
> already have the indexes created before running the populate. You may want
> to drop that indexes, populate and recreate indexes after.
>
> Vacuum analyze should be the last command on this move, afaik.
>
> Best wishes,
> Guido

Thank you both Sean and Guido.

One problem I was having was that I didn't want to use a SELECT INTO to create a
temporary table. Then have to use the COPY command to write the data to a file
and finally a second COPY command to read the data into the target table.

The other challenge was that I couldn't just use the SELECT INTO command because
the target table already existed.

I ended up with an insert and a subselect. I do not know if this is the best
way but it worked for me.

INSERT INTO tbl_target
(
SELECT column_a,
column_b,
column_c
FROM tbl_source
WHERE condition
);

Kind Regards,
Keith

In response to

Browse pgsql-novice by date

  From Date Subject
Next Message Krishnaprasad 2006-02-25 05:22:56 Regarding PL/SQL with C
Previous Message Richard Kut 2006-02-24 20:38:10 Re: Transaction Questions