Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Another possible way of doing this is</p> <pre><code>; --Ensure that any immediately preceding statement is terminated with a semicolon above WITH cte AS (SELECT ROW_NUMBER() OVER (PARTITION BY Col1, Col2, Col3 ORDER BY ( SELECT 0)) RN FROM #MyTable) DELETE FROM cte WHERE RN &gt; 1; </code></pre> <p>I am using <code>ORDER BY (SELECT 0)</code> above as it is arbitrary which row to preserve in the event of a tie. </p> <p>To preserve the latest one in <code>RowID</code> order for example you could use <code>ORDER BY RowID DESC</code> </p> <p><strong>Execution Plans</strong></p> <p>The execution plan for this is often simpler and more efficient than that in the accepted answer as it does not require the self join.</p> <p><a href="https://i.stack.imgur.com/ZJiWF.jpg"><img src="https://i.stack.imgur.com/ZJiWF.jpg" alt="Execution Plans"></a></p> <p>This is not always the case however. One place where the <code>GROUP BY</code> solution might be preferred is situations where a <a href="http://blogs.msdn.com/b/craigfr/archive/2006/09/20/hash-aggregate.aspx">hash aggregate</a> would be chosen in preference to a stream aggregate. </p> <p>The <code>ROW_NUMBER</code> solution will always give pretty much the same plan whereas the <code>GROUP BY</code> strategy is more flexible.</p> <p><a href="https://i.stack.imgur.com/iUlWm.jpg"><img src="https://i.stack.imgur.com/iUlWm.jpg" alt="Execution Plans"></a></p> <p>Factors which might favour the hash aggregate approach would be </p> <ul> <li>No useful index on the partitioning columns</li> <li>relatively fewer groups with relatively more duplicates in each group </li> </ul> <p>In extreme versions of this second case (if there are very few groups with many duplicates in each) one could also consider simply inserting the rows to keep into a new table then <code>TRUNCATE</code>-ing the original and copying them back to minimise logging compared to deleting a very high proportion of the rows.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload