Updating internal SQL to be more database agnostic and work in both MySQl and Postgresql

Part 1 - still a bit more to do and needs further testing