Improve sql query for external links