select nb, referer, case when referer ~ 'http://\\w+\.google\.*?q=(\.*?)' then regexp_replace(referer, 'http://\\w+\.google\.*?q=(\.*?)', '\\1', 'g') else regexp_replace(referer, 'http://\\w+\.yahoo\.*?p=(\.*?)', '\\1', 'g') end as query from stats_day_ref where idblog=2 and ( referer ~ 'http://\\w+\.google\.*?q=(\.*?)' OR referer ~ 'http://\\w+\.yahoo\.*?p=(\.*?)' );