patternsqlMinor
MySql: Delete all rows greater than n entries ordered by datetime
Viewed 0 times
rowsdeleteallgreaterthanmysqlordereddatetimeentries
Problem
Can someone help me with a MySql query to delete all rows greater than n entries ordered by date?
I.e. say I have 1200 rows of data with a timestamp column. I need to order it by date and preserve rows only up to the first 200.
If I have only 199 rows of data, then I need to preserve them all.
I.e. say I have 1200 rows of data with a timestamp column. I need to order it by date and preserve rows only up to the first 200.
If I have only 199 rows of data, then I need to preserve them all.
Solution
This will keep the first 200 rows (and possibly a few more, with identical timestamps):
Additional question: Keep the first 200 rows for every user (by the
A
DELETE t
FROM
tableX AS t
JOIN
( SELECT timestampColumn AS ts
FROM tableX
ORDER BY ts ASC
LIMIT 1 OFFSET 199
) tlimit
ON t.timestampColumn > tlimit.tsAdditional question: Keep the first 200 rows for every user (by the
uid column):DELETE tt
FROM
( SELECT DISTINCT uid --- these 3 lines can be replaced
FROM tableX --- with: UserTable AS du
) AS du --- a table that you probably have
JOIN
tableX AS tt
ON tt.uid = du.uid
AND tt.timestampColumn >
( SELECT timestampColumn AS ts
FROM tableX
WHERE uid = du.uid
ORDER BY ts ASC
LIMIT 1 OFFSET 199
)A
(uid, timestampColumn) will be useful with a big table.Code Snippets
DELETE t
FROM
tableX AS t
JOIN
( SELECT timestampColumn AS ts
FROM tableX
ORDER BY ts ASC
LIMIT 1 OFFSET 199
) tlimit
ON t.timestampColumn > tlimit.tsDELETE tt
FROM
( SELECT DISTINCT uid --- these 3 lines can be replaced
FROM tableX --- with: UserTable AS du
) AS du --- a table that you probably have
JOIN
tableX AS tt
ON tt.uid = du.uid
AND tt.timestampColumn >
( SELECT timestampColumn AS ts
FROM tableX
WHERE uid = du.uid
ORDER BY ts ASC
LIMIT 1 OFFSET 199
)Context
StackExchange Database Administrators Q#11258, answer score: 4
Revisions (0)
No revisions yet.