Fixed broken query on PostgreSQL and MS SQL Server, closes #786