Cleaned up querying and insert logic