Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting every nth row SQL

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 ?

like image 567
Richard Avatar asked Aug 18 '10 05:08

Richard


1 Answers

For SQL Server 2005+

Every 2nd row

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.

like image 153
OMG Ponies Avatar answered Sep 18 '22 17:09

OMG Ponies