Let's say we have table Sales with 30 columns and 500,000 rows. I would like to delete 400,000 in the table (those where "toDelete='1'"
).
But I have a few constraints :
TRUNCATE
) but while doing a "DELETE ... WHERE..."
(I need to put a condition), but haven't found any way to do this...Any advice would be welcome to transform a
DELETE FROM Sales WHERE toDelete='1'
to something more partitioned & possibly transaction log free.
TRUNCATE is faster than DELETE , as it doesn't scan every record before removing it. TRUNCATE TABLE locks the whole table to remove data from a table; thus, this command also uses less transaction space than DELETE . Unlike DELETE , TRUNCATE does not return the number of rows deleted from the table.
If you need to remove 10 million rows and have 1 GB of log space available use Delete TOP(10000) From dbo. myTable (with your select clause) and keep running it till there are no more rows to delete.
To delete all rows from a big table fast, you use the following TRUNCATE TABLE statement: In this syntax, you specify the table_name that you want to delete data after the TRUNCATE TABLE clause.
The DELETE statement with a WHERE clause deletes partial data from a table while the TRUNCATE TABLE statement always removes all data from the table. Let’s take a look at an example of truncating a table.
If you are willing (and able) to implement partitioning, that is an effective technique for removing large quantities of data with little run-time overhead. Not cost-effective for a once-off exercise, though. Show activity on this post. I was able to delete 19 million rows from my table of 21 million rows in matter of minutes. Here is my approach.
Inserting rows in a table is faster than deleting them. Loading data into a new table using create-table-as-select (CTAS) is faster still. So if you're removing most of the rows from a table, instead of issuing a delete you can: Or there's another version of this technique which can be even faster.
Calling DELETE FROM TableName
will do the entire delete in one large transaction. This is expensive.
Here is another option which will delete rows in batches :
deleteMore: DELETE TOP(10000) Sales WHERE toDelete='1' IF @@ROWCOUNT != 0 goto deleteMore
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With