Good job!. As you saw in the previous example,
ST_Centroid can return a point that lies outside a given linestring (or a polygon, too). More specifically, this happens when you work with convex geometries.
If you wish to have a central point that is guaranteed to lie inside your geometry, you need to use the
ST_PointOnSurface function, like so:
There are two drawbacks to using
ST_PointOnSurface. First, under the hood, it is much more complex to compute than
ST_Centroid, so you should only use it when you really need it. Second, the point returned by
ST_PointOnSurface is not guaranteed to be at the exact center of the polygon. In fact, the PostGIS documentation doesn't explain how it is calculated at all. The center that this function returns is merely a point that lies somewhere near the geometric center of the polygon, but always inside it.