Say I have a table (id int, Name varchar) of 1000 rows. Now I wish to delete every nth record (every 2nd, 3rd or 5th) . What is the most efficient way to do this ?
For SQL Server 2005+
WITH example AS (
SELECT t.*, ROW_NUMBER() OVER (ORDER BY t.id) AS rank
FROM TABLE t)
DELETE example
WHERE rank%2 = 0
For every 3rd row, change the WHERE clause to:
WHERE rank%3 = 0
Anf for every fifth row:
WHERE rank%5 = 0
This uses modulus, which returns the remainder from division. If the remainder is zero, the value being divided is a multiple of the divisor.
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