Contact us
Backend 1 min read · 11/2021

MariaDB, ST_Contains and boundary points

The MariaDB function ST_Contains is not compatible with MySQL ST_Contains in that it does not find points lying on the boundary of the searched polygon.

Unfortunately, the following example returns a different result in MySQL 5.7+ and MariaDB 10+:

sql
SET @area = ST_GEOMFROMTEXT('POLYGON((0 0, 10 0, 10 10, 0 10, 0 0))');
SET @point = ST_GEOMFROMTEXT('POINT(0 9)');
SELECT ST_Contains(@area,@point);

In MySQL, the result is that the polygon @area contains @point (which lies on the boundary of the area), whereas MariaDB tells us that it does not. I haven’t found an explanation for this difference in behavior anywhere, and the MariaDB documentation for ST_Contains doesn’t really explain it either:

Returns 1 or 0 to indicate whether a geometry g1 completely contains geometry g2.

So if we want to test for or search for boundary points in MariaDB as well, we have to extend the test with ST_Touches:

sql
SET @area = ST_GEOMFROMTEXT('POLYGON((0 0, 10 0, 10 10, 0 10, 0 0))');
SET @point = ST_GEOMFROMTEXT('POINT(0 9)');
SELECT ST_Contains(@area,@point) || ST_Touches(@area, @point);

For completeness, this behavior applies to points. When testing polygons, a shared boundary does not affect the result, as the following example shows:

sql
SET @area = ST_GEOMFROMTEXT('POLYGON((0 0, 10 0, 10 10, 0 10, 0 0))');
SET @subarea = ST_GEOMFROMTEXT('POLYGON((0 0, 5 0, 5 5, 0 5, 0 0))');
SELECT ST_Contains(@area,@subarea);

In this case, MariaDB also returns the result that the subarea @subarea lies entirely within the area @area.

Share
LinkedIn Facebook

Need more than an article?

Get in touch with no obligation – a few sentences about what you are dealing with are enough.

Read on

Similar articles

More notes from operations and development.

All advice