Moved the code around a little to get all the SQL into one place