0

I am running Postgres version 10.01

psql -V
psql (PostgreSQL) 10.5

I have a table mytable with about 250 million rows - my objective is to create a new table newtable and copy about half of the mytable into newtable (SELECT * WHERE time > '2019-01-01 ), then to delete the records I copied from mytable

Of course, I want to keep all indices in mytable

What is the most efficient command to do this in psql ? TRUNCATE TABLE is efficient but will remove all rows. DELETE would probably take a lot of time and prevent inserts from happening (INSERTS are scheduled every 10 mins)

Any suggestions would be helpful

4
  • Insert all your rows into the new table and then do INNER JOIN deletes Commented Jan 16, 2019 at 17:32
  • Unrelated, but: psql -V prints the version of the command line utility psql. It's not the version of the Postgres server. That can reliably only obtained by running select version(); Commented Jan 16, 2019 at 17:52
  • DELETE will not prevent inserts Commented Jan 16, 2019 at 17:53
  • If you had created a partitioned table, it would have been very simple. Commented Jan 16, 2019 at 19:13

2 Answers 2

2

You would need to proceed in two steps.

First, copy the rows to the new table. You can use a CREATE..AS SELECT statement (but you will need to recreate indexes and other objects such as constraints manually on the new table after that).

CREATE TABLE  new_table
AS SELECT * FROM old_table WHERE time > '2019-01-01

Then, delete records from the old table. It looks like an efficient way would be to JOIN with the new table, using the DELETE...USING syntax. Assuming that you have a primary key called id :

DELETE FROM old_table o
USING new_table n
WHERE n.id = o.id

(Be sure to create an indice on id in the new table before running this).

Sign up to request clarification or add additional context in comments.

Comments

0

If you are just trying to delete rows couldn't you just treat your delete as a transaction. Unless your insert is dependent on the existing data in the table, there should be no blocking.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.