title: Rails Nested SQL Queries
body: <p>I have a database model <code>Position(lat,lon)</code> which holds <code>latitudes</code> and <code>longitudes.</code></p>
  
  <p>I have a controller action called <code>show_close_by</code> which recieves a position in degrees <code>(my_lat, my_lon)</code>, a tolerance (in kilometers) and should return the list of positions in the database that are within tolerance range.</p>
  
  <p>For that, I use the haversine_distance formula which calculates the distance in kilometers (on the surface of the Earth) between two coordinates <code>(lat1, lon1, lat2, lon2)</code>.</p>
  
  <p>To make the query faster, I wrote the whole <code>haversine_distance</code> formula in the query:</p>
  
  <pre><code>... WHERE 2*6371*asin(sqrt( power( sin( (:lat2-latitude)*pi()/(180*2) ) ,2) + cos(latitude*pi()/180)*cos(:lat2*pi()/180)*power(sin( (:lon2-longitude)*pi()/(180*2) ),2) )) &lt; tolerance
  </code></pre>
  
  <p>The specifics of the query don't matter. My doubt is: is it necessary to calculate this huge function for EVERY position in the database? Can I filter out some positions that are clearly too far away with a simpler function?</p>
  
  <p>Well, I can: With a nested SQL query, I can query the database for positions that are within a large "square" (in lat/lon space), and then filter those with the more costly trigonometric function. Something like the following:</p>
  
  <pre><code>SELECT * FROM ( SELECT * FROM Positions WHERE lat-latitude &lt; some_reasonable_upper_bound AND lon-longitude &lt; same_upper_bound ) WHERE costly_haversine_distance &lt; tolerance
  </code></pre>
  
  <p>Finally, my question: how can I implement this in Rails (without writing the whole query myself)? Does <code>Positions.where(reasonable_upper_bound).where(costly_but_accurate_restriction)</code> make a nested query? If not, how?</p>
  
  <p>Thanks a lot!</p>