Fixed error in database query and applied some best practices for the database queries