Length of a line

Points have no length and if they intersect, they have the same coordinates. Lines, however, have a length and can intersect at a point not specified in the table, between two of the points used to create the line.
The following code will return the length of all of the lines:

cu.execute("SELECT id, ST_Length(location::geography) FROM lines ")
cu.fetchall()

The previous code uses the ST_Length function. The function will accept both geometry and geography. In this example, ::geography was used to convert the geometry so meters would be returned.

The results are as follows:

[(1, 4415.21026808109),
(2, 7835.65405408195),
(3, 7059.45840502359)]

You can add an ORDER BY clause to the previous query and the database will return the lines from shortest to longest. The following code adds the clause:

cu.execute("SELECT id, ST_Length(location::geography) 
FROM lines ORDER BY ST_Length(location::geography)")
cu.fetchall()

Adding ORDER BY will return the records, swapping the position of 2 and 3, as follows:

[(1, 4415.21026808109),
(3, 7059.45840502359),
(2, 7835.65405408195)]
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset