Search code examples
sqlhql

Error when list used as an `IN` comparison is empty


I have the following update query:

  @Transactional
  @Modifying
  @Query("UPDATE DailyEntry dailyEntry SET dailyEntry.status = :status WHERE dailyEntry.id IN :id")
  void updateDailyEntriesStatus(@Param("status") EntryStatus status, @Param("id") List<Long> id);

It works fine, but I get an error when :id is empty. The error message isn't really helpful:

could not execute statement

I would like to understand why an empty list would be a problem here. If its empty, the condition should just be false for every dailyEntry.

But if that's the behaviour, is there a way to prevent that error and make the query still work if :id is empty? I could also just check whether it's empty inside my service and only call that query when its not empty. I'm not sure what's the better approach.


Solution

  • IN() is expecting an expression, in the same way that a comparison operator needs both a left-hand side and a right-hand side to be meaningful. In other words,

    ... WHERE value IN ();
    

    is kinda like saying

    if value = 
    

    It's just not a complete expression. But you already have a good answer:

    I could also just check whether it's empty inside my service and only call that query when its not empty. I'm not sure what's the better approach.

    Executing the query only when the IN clause won't be empty is the better approach. You can, as I believe you are also saying, do this within the same function that calls the query; just return an empty result before calling the query, so that the caller does not need to worry about such details.