Deleting A Small Number Of Rows From A Big Table

Kevin Feasel

2018-04-30

T-SQL

Brent Ozar has a tip for deleting a relatively small percentage of data from a very large table:

Say you’ve got a table with millions or billions of rows, and you need to delete some rows. Deleting ALL of them is fast and easy – just do TRUNCATE TABLE – but things get much harder when you need to delete a small percentage of them, say 5%.

It’s especially painful if you need to do regular archiving jobs, like deleting the oldest 30 days of data from a table with 10 years of data in it.

The trick is making a view that contains the top, say, 1,000 rows that you want to delete:

Read on for a demo.

Related Posts

T-SQL Join Delete

Steve Stedman walks us through a bit of T-SQL proprietary syntax: 1 2 3 DELETE t2 FROM [dbo].[Table1] t1 INNER JOIN [dbo].[Table2] t2 on t1.favColor = t2.id; Names have been changed to protect the innocent. In the above delete statement which table will have rows deleted from it? A: Table1 B: Table2 C: Both Table1 […]

Read More

Date And Time Functions To Avoid

Randolph West shares his thoughts on three functions he’d rather you avoid: CURRENT_TIMESTAMP is the ANSI-equivalent of GETDATE(). ANSI is an acronym for the American National Standards Institute, and sometimes vendors will include ANSI functions in their products so they can say that they’re ANSI-compliant (which is not a bad thing, in most cases). There are three main problems […]

Read More

Categories

April 2018
MTWTFSS
« Mar May »
 1
2345678
9101112131415
16171819202122
23242526272829
30