Rearange sql code