pledgehollywood
pledgehollywood

Reputation: 109

Query for deleting entries while ignoring the last X entries?

I'm trying to figure out a query to delete rows from a database where we leave a certain number.

For example, if we have 10 entries and want to delete all but 2, how would I do this?

I was thinking I could count the number of entries in the table, then run a delete query using a limit of (Max Size - X), but I feel like there should be a more efficient way to do this.

Upvotes: 1

Views: 40

Answers (1)

CL.
CL.

Reputation: 180060

First find a query for the rows you want to keep, then exclude them from the deletion:

DELETE FROM MyTable
WHERE ID NOT IN (SELECT ID
                 FROM MyTable
                 ORDER BY Whatever
                 LIMIT 2)

Upvotes: 1

Related Questions