I have a database being used to cache entities. The tables looks like this:
| Persons | Addresses
----------------- --------------
PK| id <--| PK| id
| last_accessed |--- FK| persons_id
| [some] | [more]
| [other] | [address]
| [data] | [stuff]
So a person has zero or more addresses. These tables are accessed by a Java application using Hibernate and also directly from the same application using SQL over JDBC.
I now need to trim the size of the Persons table to a fixed value – say 50,000 records. I need to delete the oldest records (based on last_accessed) to do this.
is there an ANSI-SQL or HQL query that could do this easily? A pure ANSI-SQL solution would be ideal, since:
- we’re trying to remain database agnostic;
- we want to avoid having to load objects into application memory to get Hibernate cascading deletes to work…
This is pure ANSI SQL:
Another alternative would be to define the FK constraint with “ON DELETE CASCADE” and then just delete the rows from the
personstable. That would get rid of the extra SQL for deleting the addresses first.