Query Formation and writing to file functionality