title: Optimize expanding SQL query
body: <p>I need to do this algorithm as efficiently/quickly as possible in SQL. </p>
  
  <pre><code>while( numberOfResults  &lt; DesiredResults and NotCutOffCondition){
      retrieve and store up to (DesiredResults - numberOfResults) results 
          based on radius
      expand radius
  }
  </code></pre>
  
  <p>The query on radius is very basic just less than/ greater than limits. I have heard that while loops are inefficient in SQL because it's not set based but I can't think of a way to do this without one. Is there a better way? This will run on MySQL, maybe SQL Server if there are any differences in that regard that I am unaware of.</p>
  
  <p>consider the following table structure</p>
  
  <pre><code>id int
  x_position decimal indexed
  y_position decimal indexed
  </code></pre>
  
  <p>I need to find the nearest n points to a given x,y position. there could be thousands of possible points within a small area but not always. Therefore I need to spiral out from a small radius. Or at least I figured that would be most efficient if I only want around 20 points on a usual query.</p>