Refactored SQL queries/commands so they are less horrible