Delete duplicate entries with lower IDs I have a function that deletes duplicate entries.  The highest ID is kept and the older ones are removed.

function:

DELETE [tableName]
FROM [tableName]
INNER JOIN (SELECT * , ROW_NUMBER() OVER 
           (PARTITION BY [fork_id] ORDER BY ID DESC) 
           AS RowNumber FROM [tableName])
Numbered ON [tableName].ID = Numbered.ID
WHERE RowNumber &gt; 1


For example, it changes

|------|---------|--------|
|  ID  | fork_id |   Car  |
|------|---------|--------|
|  1   |    2    |  AUDI  | &lt;--- removed
|  2   |    1    |  AUDI  |
|  3   |    2    |  BMW   |
|------|---------|--------|


to 

|------|---------|--------|
|  ID  | fork_id |   Car  |
|------|---------|--------|
|  2   |    1    |  AUDI  |
|  3   |    2    |  BMW   |
|------|---------|--------|


The problem with that query is the execution time exceed time when with have many rows (more than 50k) in the table.

I have a primary key for the ID column

I'm In the sql server, I have a limitation about execution time.


  A connection can be cut off by the server for a number of reasons:
  
  
  Idle connection longer than 5 minutes.
  Long running query.
  Long running open transaction.
  Excessive resource usage.
  
  
  sources
This would probably be better on DBA
You can use a CTE
An index on fork_id should help  

with cte as 
( SELECT ROW_NUMBER() OVER (PARTITION BY [fork_id] ORDER BY ID DESC) AS RowNumber 
  FROM [tableName]
)
delete from cte 
WHERE RowNumber &gt; 1  


Optimize 

select * from cte 
WHERE RowNumber &gt; 1


If that is fast it is volume thing and you could delete in batches