Made sql checking slightly more robust