Modified SQL query and fixed null pointer issue