Fixed PostgreSQL query issues