Search code examples
sql-server-2008selectsql-server-2005sql-deletetruncate

Simultaneous select and truncate or delete in SQL Server


I have a table in SQL Server 2005 and 2008 databases that has a periodic job which truncates the table and another table that has a periodic job that deletes rows from the end. My question is if I have a select that has started before the truncate or delete jobs start, will the select query the pre truncate/delete data or could some data be removed before the select reads it? The selects would be using one table or the other not joining both.

The statements would be along these lines:

select * from someTable where id > x and id < y

truncate table someTable

delete from otherTable where id < z

Solution

  • Truncate will wait for the SELECT to finish. DELETE will not. DELETE can remove rows before the SELECT had a chance to read them. Whether this will really happen or not depends on more factors, like your table organization (indexes, clustered index) and cardinality (number of rows in table, number of rows between lower and upper, number of rows lower than upper).

    You can prevent this from happening by deploying row versioning