Delete all rows in table

Sql ServerTsql

Sql Server Problem Overview


Normaly i would do a delete * from XXX but on this table thats very slow, it normaly has about 500k to 1m rows in it ( one is a varbinary(MAX) if that mathers ).

Basicly im wondering if there is a quick way to emty the table of all content, its actualy quicker to drop and recreate it then to delete the content via the delete sql statement

The reason i dont want to recreate the table is because its heavly used and delete/recreate i assume will destroy indexs and stats gathered by sql server

Im also hoping there is a way to do this because there is a "clever" way to get row count via sys.sysindexes , so im hoping there is a equaly clever way to delete content

Sql Server Solutions


Solution 1 - Sql Server

Truncate table is faster than delete * from XXX. Delete is slow because it works one row at a time. There are a few situations where truncate doesn't work, which you can read about on http://msdn.microsoft.com/en-us/library/aa260621(SQL.80).aspx">MSDN</a>;.

Solution 2 - Sql Server

As other have said, TRUNCATE TABLE is far quicker, but it does have some restrictions (taken from [here][1]):

> You cannot use TRUNCATE TABLE on tables that:

  • Are referenced by a FOREIGN KEY constraint. (You can truncate a table that has a foreign key that references itself.)
  • Participate in an indexed view.
  • Are published by using transactional replication or merge replication.

    For tables with one or more of these characteristics, use the DELETE statement instead.

The biggest drawback is that if the table you are trying to empty has foreign keys pointing to it, then the truncate call will fail. [1]: http://msdn.microsoft.com/en-us/library/ms177570.aspx

Solution 3 - Sql Server

You can rename the table in question, create a table with an identical schema, and then drop the original table at your leisure.

See the MySQL 5.1 Reference Manual for the [RENAME TABLE][1] and [CREATE TABLE][2] commands.

RENAME TABLE tbl TO tbl_old;

CREATE TABLE tbl LIKE tbl_old;

DROP TABLE tbl_old; -- at your leisure

This approach can help minimize application downtime.

Solution 4 - Sql Server

I would suggest using TRUNCATE TABLE, it's quicker and uses less resources than DELETE FROM xxx

Here's the related MSDN article

Solution 5 - Sql Server

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEKSView Question on Stackoverflow
Solution 1 - Sql ServerScottView Answer on Stackoverflow
Solution 2 - Sql ServeradrianbanksView Answer on Stackoverflow
Solution 3 - Sql ServerDuncan BeeversView Answer on Stackoverflow
Solution 4 - Sql ServerSteve TempleView Answer on Stackoverflow
Solution 5 - Sql ServerSrikar DoddiView Answer on Stackoverflow