Fixed Postgres query bug