select * from tab_name order by decode(instr(id, 'ab'), 0, 9999, instr(id, 'ab')), decode(instr(id, 'ab', 2), 0, 9999, instr(id, 'ab', 2)), id