some of the ugliest sql code ever written