Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I delete only the top 100 rows?

I have 100,000 rows to delete in DB2. I use Hibernate (HQL) something like delete from than query.executeQuery().

Is it possible in HQL to limit the number of rows to delete? For example:

query.setMaxRowTodelete(100); //  this is just an example.
query.executeQuery();
like image 276
bambozi papazoni Avatar asked Nov 19 '12 21:11

bambozi papazoni


People also ask

How do I delete a specific number of rows in SQL?

If you wanted to delete a number of rows within a range, you can use the AND operator with the BETWEEN operator. DELETE FROM table_name WHERE column_name BETWEEN value 1 AND value 2; Another way to delete multiple rows is to use the IN operator.

Can we use top in delete query?

If you need to use TOP to delete rows in a meaningful chronological order, you must use TOP together with an ORDER BY clause in a subselect statement.


1 Answers

Saddly, you can not limit with HQL and query.setMaxResults(number) won't work with UPDATEs or DELETEs. Your options are:

  • iterate over/load each object and delete it. Yuck!
  • write two separate HQL queries where the results of the first query are fed into another query (which does the actual delete). Might or might not be possible in your situation.
  • use raw SQL/JDBC.
  • make two queries: first query on IDs only (without loading actual objects) having limited result set (100 in your case). Second query would delete WHERE someid IN (id1, id2, ..., id100)
like image 169
mindas Avatar answered Sep 21 '22 16:09

mindas