Improved SQL query for getVersion