• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 162
  • Last Modified:

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.
0
sdc248
Asked:
sdc248
3 Solutions
 
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
 
pai_prasadCommented:
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:
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
 
imitchieCommented:
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

Featured Post

[Webinar On Demand] Database Backup and Recovery

Does your company store data on premises, off site, in the cloud, or a combination of these? If you answered “yes”, you need a data backup recovery plan that fits each and every platform. Watch now as as Percona teaches us how to build agile data backup recovery plan.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now