Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Delete all rows in table except the first row?

Author  Topic 

OldMySQLUser
Constraint Violating Yak Guru

301 Posts

Posted - 2008-01-18 : 11:37:00
How can I delete all the rows in a table except the first row please?

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-01-18 : 11:42:56
DELETE FROM Table t
LEFT OUTER JOIN (SELECT MIN(pk) FROM TABLE) tmp
ON tmp.pk=t.pk
WHERE tmp.pk IS NULL

pk is primary key of table
Go to Top of Page

AndrewMurphy
Master Smack Fu Yak Hacker

2916 Posts

Posted - 2008-01-18 : 12:42:31
depending on how big the tqble is....it might be faster/easier to script the 1st record into an insert statement, delete all records (using truncate) and then insert in the 1 record.
Go to Top of Page

AndrewMurphy
Master Smack Fu Yak Hacker

2916 Posts

Posted - 2008-01-18 : 12:44:00
you also have to properly define "First"....in this instance visakh16 has assumed that the primary key is an ascending number (which may not be right in your circumstance)
Go to Top of Page

OldMySQLUser
Constraint Violating Yak Guru

301 Posts

Posted - 2008-01-18 : 15:03:17
Thanks everyone.
Go to Top of Page
   

- Advertisement -