tags:

views:

57

answers:

2

Here is what im trying to do explained in a query

DELETE FROM table ORDER BY dateRegistered DESC LIMIT 1000 *

I want to run such query in a script which i have already designed. Every time it finds older records that are 1001th record or above it deletes

So kinda of setting Max Row size but deleting all the older records.

Actually is there a way to set that up in the CREATE statement.

Therefore: If i have 9023 rows in the database, when i run that query it should delete 8023 rows and leave me with 1000

+2  A: 

The only way that immediately occurs to me for this exact job is to do it manually.

First, get a lock on the table. You don't want the row count changing while you're doing this. (If a lock is not practical for your app, you'll have to work out a more clever queuing system rather than using this method.)

Next, get current row count:

SELECT count(*) FROM table

Once you have that, you should with simple maths be able to figure out how many rows need deleting. Let's say it said 1005 - you need to delete 5 rows.

DELETE FROM table ORDER BY dateRegistered ASC LIMIT 5

Now, unlock the table.


If a lock isn't practical for your scenario, you'll have to be a bit more clever - for example, select the unique ID of all the rows that need deleting, and queue them for gradual deletion. I'll let you work that out yourself :)

Matchu
Yes but that will delete 1000 rows... and not leave 1000 rows if you know what i mean. Let me try edit the questions a bit
Shahmir Javaid
Ahh, I see. Hmm...
Matchu
And yes you are right on the ASC... my brain is failing to function
Shahmir Javaid
Updated to fit newly understood question restraints :)
Matchu
Could i put Maths in the Limit Senario? For example can i do: LIMIT (SELECT .....). Or would i have to do it in a different query?
Shahmir Javaid
+2  A: 

If you have a unique ID for rows here is the theoretically correct way, but it is not very efficient (not even if you have an index on the dateRegistered column):

DELETE FROM table
WHERE id NOT IN (
    SELECT id FROM table
    ORDER BY dateRegistered DESC
    LIMIT 1000
)

I think you would be better off by limiting the DELETE directly by date instead of number of rows.

I don't think there is a way to set that up in the CREATE TABLE statement, at least not a portable one.

Bandi-T
Ooh, I like this. I tend to stray away from subqueries since they're generally inefficient, but this seems much more efficient at first glance, especially since it doesn't have to re-run for each row.
Matchu