move sql to function