title: SQL query to calculate coordinate proximity
body: <p>I'm using this formula to calculate the distance between entries in my (My)SQL database which have latitude and longitude fields in decimal format:</p>
  <pre><code>6371 * ACOS(SIN(RADIANS( %lat1% )) * SIN(RADIANS( %lat2% )) + 
  COS(RADIANS( %lat1% )) * COS(RADIANS( %lat2% )) * COS(RADIANS( %lon2% ) - 
  RADIANS( %lon1% )))
  </code></pre>
  <p>Substituting %lat1% and %lat2% appropriately it can be used in the WHERE clause to find entries within a certain radius of another entry, using it in the ORDER BY clause together with LIMIT will find the nearest x entries etc.</p>
  <p>I'm writing this mostly as a note for myself, but improvements are always welcome. :)</p>
  <p>Note: As mentioned by Valerion below, this calculates in kilometers. Substitute 6371 by an <a href="http://en.wikipedia.org/wiki/Earth_radius" rel="nofollow noreferrer">appropriate alternative number</a> to use meters, miles etc.</p>