StateHistoryQuery: Make whereToSql robust

This fixes bugs is a array for expression comes in or types
does not exist.

fixes #7133