Attempting to build the SQL query

Expect a lot of bug “fixes”