Deleting historical data from a large table in SQL.

Jinal Contractor 121 Reputation points
2022-03-22T14:14:06.177+00:00

Hello,
I've 5 different tables which are archive tables(Production Database)and I would like to delete records older than 5 years and move to different database(Archive Database) for those records so I can able to access in future as needed.
Is there way to do it?

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
14,318 questions
{count} votes

3 answers

Sort by: Most helpful
  1. Naomi Nosonovsky 8,051 Reputation points
    2022-06-15T20:35:13.76+00:00

    What is the AddDate data type? Most likely you need to use
    select * from tbl where AddDate <= dateadd(year,-5, CURRENT_TIMESTAMP)

    1 person found this answer helpful.
    0 comments No comments

  2. Sreeju Nair 12,536 Reputation points
    2022-03-22T14:53:28.61+00:00

    Based on your question I understand you want to copy the records older than five year to another database. right? I believe you have some timestamps in your fields so that you can identify the records older than 5 years, normally you may have created date, or last modified date that could be your column to decide the records that need to be archived.

    In order to automate the data archival process, you can create an SQL Server Job using the SQL Server agent.

    Reference
    https://learn.microsoft.com/en-us/sql/ssms/agent/create-a-job?view=sql-server-ver15
    https://learn.microsoft.com/en-us/sql/ssms/agent/create-a-transact-sql-job-step?view=sql-server-ver15

    In the SQL server job, you can add your query, something similar to the following.

    INSERT INTO TargetDatabase.Table (field1, field2, field3) SELECT field1, field2, field3 FROM SourceTable WHERE (some condition to determine the record is 5 year old )

    You may schedule the SQL server job to execute on a certain time of a day.
    Refer: https://learn.microsoft.com/en-us/sql/ssms/agent/create-and-attach-schedules-to-jobs?view=sql-server-ver15

    Hope this helps


  3. Erland Sommarskog 115.6K Reputation points MVP
    2022-03-22T22:47:59.607+00:00

    As Sreejukg said, yes, you can do it, provided that there is a way to identify the rows that are more then five years old. If there is not, it's starting to get tricky.

    Assuming that you know how to find which rows to archive, what is really your question? Do you want to us to write the INSERT and DELETE statements for you? Or are you asking if there are any special considerations you need to make?

    I ask these questions, because if just type something up, I may be answering a different question than you had in mind.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.