• SQLkiwi (3/4/2011)


    HowardW (3/4/2011)


    It's important to note that none of these solutions will guarantee to delete the same rows as are being returned by the select statement...

    Hi Howard,

    I agree with your comments about the reason for deleting the 'nth' row in no particular order, but I can't for the life of me understand what the extract above is getting at. A query like the following is guaranteed to delete the row identified as #4 (peculiar though the logic is):

    DELETE E

    FROM (

    SELECT rn = ROW_NUMBER() OVER (ORDER BY (SELECT 0))

    FROM dbo.Example

    ) AS E

    WHERE E.rn = 4

    ;

    Naturally, we would normally use a deterministic order by with the row number window function to identify the row or rows to delete.

    Paul

    It's guaranteed to delete the nth row within that delete statement, but as far as I'm aware, you could run the select (which will generate one plan) and assume that the delete statement will delete the same rows. However, the delete statement could reasonably generate a different plan and delete different arbitrary rows than your original select statement did. Unless I'm misunderstanding how the optimiser works in this case and it doesn't generate a plan based on the overall query and will always generate the plan based on the sub query alone.

    Hopefully the above makes sense (even if it's wrong!) 🙂