Fix sort_query handling of polymorphic inheritance