Question

Good day,

I have a table with some records that should be deleted. I would like to keep track of the deleted records and place such records in a new table. I would like to do the following:

SELECT * INTO TEMP FROM TABLE WHERE criteria < 1;

And then delete these records with DELETE query. Later on I would like to do a new SELECT query:

SELECT * INTO TEMP FROM TABLE WHERE new_criteria > 2;

And then delete those records as well. I will be working from only one table and just place the selected records into the same, new table (just for reference).

Thanks!

Was it helpful?

Solution

INSERT INTO temp (SELECT * FROM tbl WHERE criteria < 1);

OTHER TIPS

Does you temp table have the same structure as the original. if the temp does not exist you might want to do this.

create table temp as select * from TABLE where criteria <1

If you are using Postgresql 9.3 You could also do everything in one command:

WITH deleted_rows AS (
    DELETE FROM tbl
    WHERE criteria<1
    RETURNING *
)
INSERT INTO temp
SELECT * FROM deleted_rows;

(see http://www.postgresql.org/docs/9.3/static/queries-with.html#QUERIES-WITH-MODIFYING )

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top