Fixed error in database query and applied some best practices