Use functions instead of duplicated sqls