restructured and updated sql code