The code was
if ($sortorder === false) {
however, on Postgres (at lease)
get_field_sql('SELECT MIN(sortorder)-1 AS min
FROM ' . $CFG->prefix . 'course WHERE category=' . $categoryid);
returns NULL, not false, if the category you are moving to is empty.