Query help - delete all but 50 rows of data

Hi:

What is the fastest way to delete all but 50 rows  of data from a database table? Thanks.
sdc248Asked:
Who is Participating?
 
pai_prasadConnect With a Mentor Commented:
depends on the number of records in the table...
 if u have 100 recds above query is gud ./

if u have 2 millon recds.. i wud pref

Select Top 50*
into myTable_bkp
from myTable

Truncate MyTable

Insert into myTable
Select * from myTable_bkp

0
 
Chris MangusDatabase AdministratorCommented:
Do you care which 50 rows you keep?  If not:

Delete From myTable Where myPK Not In (Select Top (50) myPK From myTable)
0
 
Chris MangusConnect With a Mentor Database AdministratorCommented:
Assuming the table doesn't have an identity value that needs to be retained this will work.  If you have an identity value you'll need to turn Identity Insert on if you put records back into myTable.
0
 
imitchieConnect With a Mentor Commented:
seeing that you are "removing all but 50", this is probably a dev db. i assume there aren't any foreign keys to care about? you probably want the "latest" data then?

delete mytable where idcol < (
select min(idcol) from
(select top 50 idcol from mytable order by idcol desc) x)

you can want raw speed, nothing beats truncate. but it has two major drawbacks:
resets identity columns, and fails when certain constraints are defined (i.e. foreign keys)
it's   TRUNCATE TABLE <tablename> btw, you can drop the "from" in DELETE FROM but not the "table" from TRUNCATE TABLE
0
 
sdc248Author Commented:
Thanks guys. The "truncate table" command helps a lot. The old "delete from mytable where" method took forever to delete data from a couple of huge tables (200 million rows) and eventually failed because the transaction log grew rapidly and fill up the server.  Luckily these huge tables don't have identity columns or foreign keys.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.