Faster geospatial queries in MySQL
Searching a table in MySQL based on latitude and longitude columns.
Everything I said
This is a point. In fact, let's call this a point of interest. It's not interesting yet, but I promise it'll get more interesting. Let's say that this point of interest is on a map, and around this point of interest are a bunch of other points. What we're looking for is we're looking for all of the points within half a mile of this point of interest at the middle.
And to do that, we're gonna use something called the Haversine formula because we need to calculate the distance between two points across a sphere, not straight, but across a sphere because the Earth is not flat. The Earth is not flat. Now, the Haversine formula is a little bit complicated. I'm gonna see if I can explain it to you very, very quickly. What the ?
Okay, new plan. We're not gonna talk about the details of the Haversine formula because MySQL has a function that wraps that up and hides the complexity from you, and it is called ST_Distance_Sphere. It calculates the distance across a sphere between two points. Let's look at this ST_Distance_Sphere thing. So if we do select ST_Distance_Sphere, and we're just gonna, we're just gonna run this.
What we need to pass here is we need to pass two different points, and these two points are gonna be latitude and longitude pairs. You can pass a third argument here, and that's the radius in meters of the sphere that you want to calculate the distance on. Um, if you leave it off, it's gonna use the radius of the Earth, eh, which is what we're after anyway.
So in here, you're gonna have to put longitude and latitude and longitude and latitude. We have some, so let's go ahead and just do select star from addresses. We'll look at this table in a second. But if we do select star from addresses limit two, we'll get some latitude and longitude here. So we'll take this latitude, put it up there, and we're just gonna fill this function with some longitude and latitude so that we can see what comes out of it.
Now, if we run this, we get the distance in meters that these two points are from each other. So we can say as distance in meters. So this is the distance in meters between those two points. We're off to a pretty good start. But what we actually wanted to do is we wanted to filter the table based on some distances.
So if we look at this, we've got this addresses table here. We've got this addresses table. Um, it's got a type, a primary, secondary line that's just the address, and then the latitude and longitude of that property. Now, there are, I think, two million rows in here. So if we do select count star from addresses, we'll see we've got two million rows in here.
So not a huge amount of data, but still pretty good for testing purposes. Okay, because I don't speak meters, we're gonna take this and multiply it by this constant, and this will give us the distance in miles from each other. So these two properties are one point nine five miles away from each other. So this is just a calculation that I looked up earlier.
Okay. What we wanna do now is we wanna start filtering. So let's say select star from addresses limit ten again. And we wanna find all of the, let's say, all of the properties, doesn't matter of what type, all of the properties within one mile of this property right here, eighty-two fifteen Wine Cup Hill.
So the way that we're gonna do this is we're gonna say, select star from addresses where, and we're gonna take this ST_Distance_Sphere, where ST_Distance_Sphere, and this is our point of interest. Remember earlier, we talked about the point of interest and the extra points? This is our point of interest. So our point of interest is this first guy here, and we're gonna copy those and put those in there.
And then what we're gonna say is the, are, are the other points is we're gonna feed in, we're gonna feed in the columns from the table. So now we're saying, "All right, one fixed point in the middle, and then for every row, feed it in and do this calculation. Give me the distance in miles, but I wanna see where it's less than one mile away." So this should give us all of the properties near this other property.
So if we run that, well, we're gonna see it takes a little bit of time. So that took, uh, two point two seconds, and it looks like we got back about five hundred and ninety-seven rows. If this is fast enough for your application, you're good. Take the rest of the day off. Tell your boss some YouTuber said you can go home early. This is probably not gonna be fast enough for most applications, unfortunately.
Two and a half seconds across two million rows, I don't love it. So the problem is this is not super easy to index, right? Because these columns in here, they're all wrapped up inside this point function, inside this ST_Distance_Sphere function. And the, the real problem here is that this value, the distance between these two points, is different for every single row.
And so there's not even a good, like, there's not even a good functional index we can put anywhere because the value is dependent on what is the point of interest, right? And so there's no real way to index this. So now we're gonna start talking about bounding boxes. Bounding boxes are just boxes that fully contain objects. So in our case, the bounding box is going to be around this circle.
Now, to draw this bounding box, what we're gonna do is we're gonna calculate a minimum longitude, a maximum longitude, a minimum latitude, and a maximum latitude. And this is going to create a bounding box. Technically, it's gonna create two giant rectangles, but where they cross, that's the bounding box. And because this bounding box fully contains the circle, every point that we're looking for is inside this bounding box.
So by drawing this bounding box, we're able to eliminate potentially millions of other points that we know are not going to be inside the circle. Now, we are left with a few points that are inside the bounding box but not inside the circle. And so these would be false positives. So we're not going to get rid of our expensive Haversine calculation, but instead, what we're gonna do is we're gonna use the bounding box to limit the universe that we have to run that expensive calculation on.
We're still gonna run the expensive calculation for accuracy, but we're gonna use the bounding box for speed. Calculating the values for the bounding box is kind of outside the scope of this video. It's pretty straightforward. There are a lot of ways to do it online. In almost every single language, there's a function to do that for you. Theoretically, all you do is you have your point in the middle, and then you have your circle around it, and then from that point, you go just a little bit bigger than the circle.
So if it's a one-mile circle, you go one point zero one miles, and there's one line, one point zero one the other way, there's one line, and same for the top and bottom. That's basically it. I ran that calculation off-camera, and this is what you get. So when the latitude is between these two values and the longitude is between those two values, that entirely encompasses the circle.
One way to test that is we should be able to run this and get back the exact same five hundred and ninety-seven rows. So if we run that, we get the exact same five hundred and ninety-seven rows. So what happened was our bounding box didn't actually change anything, which is what we were after, right? So the bounding box is supposed to not change the results but make the query faster.
And it is faster. It's five hundred and eighty milliseconds instead of, if we run this again, I think it's, like, two point two seconds. There you go. So this is a good example of something that is called a redundant condition. It is a condition that doesn't and logically can't change the results of the query but can make the query quite a bit faster. What's interesting is if we do it the other way, if we drop out our accuracy condition and just leave in the gross bounding box and we run that, it's still pretty fast, but it's super-duper
wrong, right? We get nine hundred and twenty rows back instead of the five ninety-seven because this includes all of those false positives that are inside of the bounding box but outside of the circle of accuracy. And we haven't even talked about adding an index yet. So let's turn, let's turn our accuracy condition back on, run that again, five ninety-seven, and let's talk about adding an index.
We can't add, um, a compound index that covers latitude and longitude. We can. The database just isn't gonna use that. Because both of these are range conditions, when you have a compound index, MySQL will work that index from the left to the right, and it'll stop the first time it reaches a range condition.
So putting a compound, put it-- putting a compound index across latitude and longitude doesn't make a whole lot of sense here. But what we're gonna do is we're gonna alter... Let's go ahead and alter table addresses, add index. We'll just add one for each. Latitude, we'll let that run, and then longitude, we'll let that run.
You probably only need one or the other, but we'll add them both and let the database decide. So now if we run this again, you see we're, we're all the way down to a hundred and seventy-eight milliseconds. That is pretty good. Two hundred milliseconds. Getting, getting speed heuristics by just running the query, eh, it's not the worst thing in the world, honestly. It's a lot faster.
It's an order of magnitude faster. We were at two point two seconds. Now we're at two hundred milliseconds. Hey, pretty good. Let's go ahead and explain it and see what's actually happening for real. If we explain it, we see that it is doing a range scan on the longitude key right there. So now instead of doing an expensive calculation over the entire table, we are using that longitude index to bring the universe of possibilities in via index.
And then beyond that, we're using the latitude part of the bounding box to bring the universe of possibilities in, not via index, but also not via Haversine calculation. And then finally, when we have the universe really, really small, ah, we run an expensive calculation over it, and it's honestly, it's honestly not that bad. So we get all the way down to two hundred milliseconds.
We've already improved it by a factor of ten. Now, one other thing we can do if we're not purely searching on location is we can make a compound index out of something else as long as we leave the latitude or longitude at the end of that compound index. So if we say alter table addresses, add index, we'll say it's the, uh, type longitude, and we'll say it's type.
Type is the first column, and longitude is the second column. So if we add a compound index to this table, what we can do now is we can say, "All right. Well, I want where type equals restaurant." And if we run that, we're down to fifty-one milliseconds, and let's go ahead and explain that, and we see that it's using our new compound index.
So even beyond the bounding box, we're now using a compound index to first get down to just restaurants. Then we're using longitude to lop off all of the restaurants that are outside of the bounding box. Then we're using the latitude to lop off all of them that are outside of the bounding box on the latitude condition, and then we're using Haversine to get down to restaurants that are within one mile of this address as the crow flies.
If you want driving directions, I wouldn't use MySQL for that. Everything we've done in this video has been using distinct latitude and longitude columns, right? They're just, they're just floating-point numbers in a column. Don't use strings. They are numbers. Um, MySQL does have support for geometry and GIS, and you can actually create a point column that contains the latitude and longitude as a special and different data type.
It, it might be, it might be worth looking into. I will cover that in a future video. There's a lot to cover there. But just quickly, some of the differences are you can create a spatial index on a point column. A spatial index is fundamentally different than, um, a traditional index, which is, which is a B-tree. A spatial index is an R-tree.
And so you can create a spatial index on a point column. Now, the thing that we did where we had the type of restaurant and then the latitude as, as a compound index, you can't do that with a spatial index. So it kind of depends on what your application's needs are. If you do end up needing a compound index, you can't really do that with an R-tree.
It just indexes that particular point or location column. They're a little bit more finicky to work with, but they are a lot more powerful. So that might be worth considering. We'll talk about it in the future. If you do end up using the bounding box latitude, longitude method, I would encourage you to wrap that up inside your application in some sort of, um, scope, query builder, ORM, whatever it is.
Wrap it up so that you can pass in, um, you can pass in a point and a distance, and it will calculate the bounding box for you. It'll put in the ST_Distance_Sphere function for you. All of that will be bound into the query, and it'll be transparent from you. So remember, the bounding box gets you there quickly, and then the ST_Distance_Sphere gets you there accurately.
Hide all of that behind a beautiful interface, and never think about it again. Please, if you liked this video, that's great. Go buy a bunch of databases from PlanetScale, or just stay tuned to this channel where we will have a lot more videos. See ya.