SQL Query to delete oldest rows over a certain row count?
Posted
by Casey
on Stack Overflow
See other posts from Stack Overflow
or by Casey
Published on 2010-04-01T14:35:14Z
Indexed on
2010/04/01
14:43 UTC
Read the original article
Hit count: 340
sql
|sql-server-2005
I have a table that contains log entries for a program I'm writing. I'm looking for ideas on an SQL query (I'm using SQL Server Express 2005) that will keep the newest X number of records, and delete the rest. I have a datetime column that is a timestamp for the log entry.
I figure something like the following would work, but I'm not sure of the performance with the IN clause for larger numbers of records. Performance isn't critical, but I might as well do the best I can the first time.
DELETE FROM MyTable WHERE PrimaryKey NOT IN
(SELECT TOP 10,000 PrimaryKey FROM MyTable ORDER BY TimeStamp DESC)
© Stack Overflow or respective owner