Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>@Jeremy Gustie's solution above almost works, but will do the wrong thing if the ordinals are off (or fail altogether if the re-ordered ordinals make incompatible types match). Give it a try:</p> <pre><code>CREATE TABLE test1 (one varchar, two varchar, three varchar); CREATE TABLE test2 (three varchar, two varchar, one varchar); INSERT INTO test1 (one, two, three) VALUES ('one', 'two', 'three'); INSERT INTO test2 SELECT * FROM test1; SELECT * FROM test2; </code></pre> <p>The results show the problem:</p> <pre><code>testdb=&gt; select * from test2; three | two | one -------+-----+------- one | two | three (1 row) </code></pre> <p>You can remedy this by specifying the column names in the insert:</p> <pre><code>INSERT INTO test2 (one, two, three) SELECT * FROM test1; </code></pre> <p>That gives you what you really want:</p> <pre><code>testdb=&gt; select * from test2; three | two | one -------+-----+----- three | two | one (1 row) </code></pre> <p>The problem comes when you have legacy that doesn't do this, as I indicated above in my comment on peufeu's reply.</p> <p><strong>Update:</strong> It occurred to me that you can do the same thing with the column names in the INSERT clause by specifying the column names in the SELECT clause. You just have to reorder them to match the ordinals in the target table:</p> <pre><code>INSERT INTO test2 SELECT three, two, one FROM test1; </code></pre> <p>And you can of course do both to be very explicit:</p> <pre><code>INSERT INTO test2 (one, two, three) SELECT one, two, three FROM test1; </code></pre> <p>That gives you the same results as above, with the column values properly matched.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload