Added query error checking