I have a database with 1000 records containing a file name and a file size on each row. If the SUM of all file sizes exceeds a specific limit, then: - I need to create a sql query to delete all the remaining rows, from oldest to newest
Any suggestions? Thanks
Probably the easiest solution (that is still fast even with many rows) is to calculate the running total in the application:
Now read the result set, and in the loop use total += size. Once total is larger, delete everything older than the current createdDate:
Some other databases (for example MySQL and H2) support efficient running totals, but not SQLite.
Do binary search. Check if sum of 500 newest files is less then limit, if so, if sum of 750 is below limit etc. Until you get the row from which you should start deleting. Then just
DELETE WHERE file_date > date_of_your_last_row_below_limit
.Supposing a table created thus:
To get the running sum, use the following query:
To delete the file ID's above the threshold:
Note: The
order by
is optional.