Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL MOVE Records to another table

I have a number of functions which MOVE records from one table to another (generally for a form of archiving the data) and wondered if there was a "best practice" for doing this, or a more efficient method than I am currently using.

At the moment, I am running something like:

INSERT INTO archive_table
SELECT [ROWID], [COL1], [COL2]
FROM live_table
WHERE <criteria>

DELETE FROM live_table
WHERE [ROWID] IN
(
   SELECT [ROWID] FROM archive_table
)

This is also throwing up a warning on the SQL performance software that the query may cause index suppression and performance degradation; due to a SCAN being performed, rather than a SEEK.

Worth adding that the archive_table is an exact copy of the live_table, with the exception that we have removed the identity and primary key off of the [ROWID] column and that this table is not used within the 'live' environment, other than having the old data inserted, as described.

[edit]

Would seem that the answer from Alex provides a really simple resolution to this; the comment about using a trigger doesn't resolve the issue in this instance as the event happens a number of days later and the criteria is dependant on events during that period.

DELETE 
FROM live_table 
OUTPUT DELETED.* INTO archive_table
WHERE <criteria>
like image 799
Sean Avatar asked Apr 20 '15 14:04

Sean


People also ask

How do I move records from one table to another in SQL?

The SQL INSERT INTO SELECT Statement The INSERT INTO SELECT statement copies data from one table and inserts it into another table. The INSERT INTO SELECT statement requires that the data types in source and target tables match. Note: The existing records in the target table are unaffected.

How do I move data from one table to another in mysql?

To copy the data between the tables, we use the combination of CREATE TABLE and SELECT statement. If you want to copy the specific dataset from the table, we can filter the records by adding a WHERE clause.


1 Answers

If you have to move large number of records from one table to another, i suggest you check the possibility to partition your "active table". Each time, you copy data from one (or more) partitions to the "achieve table" and drop those partitions. It will be much faster than delete records from an "online" table.

like image 147
Tim3880 Avatar answered Oct 03 '22 02:10

Tim3880