Použijte IF SELECT SUBSTRING_INDEX(refurl, IF(LOCATE('?gclid', refurl), '?gclid', '&gclid'), 1) AS refurl, ...