Wednesday, March 28, 2012

Use Sql To Determine The Closest Xy Coordinates

SQL makes it easy to search through large amounts of data.


Databases power the top businesses and websites in the world today, allowing for the efficient querying of large amounts of data. Structured Query Language is used to retrieve information from databases. Spatial information, such as coordinates are commonly stored in databases. You can find the entry in a database that is closest to a specific position using SQL with a few lines of code.


Instructions


1. Use the correct column names from the database in the query or else the search returns an error. For instance, the following query will return a single row with the column names from the table named "mytable":


SELECT TOP 1 * from mytable


Note the names of the columns that hold the positional information.


2. Take the distance between two points at positions (X1,Y1) and (X2, Y2) given as:


( (X1 - X2)^2 + (Y1 - Y2) )^2


Assuming that the spatial information is stored in the table named "mytable" in the columns named "POSX" and "POSY", the following query will return the data that is closest to the point at the coordinates X=10.0, Y=10.0:


SELECT TOP 1 *, ( (POSX - 10.0)^2 + (POSY - 10.0) )^0.5 as Distance from mytable


Adjust the X and Y values to reflect the location of the point in question.


3. Input the following query if more than one value is desired to return the 20 closest rows in the table nearest to the point at X=10.0, Y=10.0:


SELECT *, ( (POSX - 10.0)^2 + (POSY - 10.0) )^0.5 as Distance from mytable ORDER BY Distance LIMIT 20







Tags: following query, from mytable, POSX POSY, amounts data, column names, column names from