0

I don't know why searching in my "cities" table is so slow. My query looking for a table "cities" located about 25km from the city. I use this simple query and the database takes almost 20 seconds to return results.

SELECT city_destination,distance FROM cities WHERE city_start='Wien' AND distance <= 25 ORDER BY distance ASC

Table engine is InnoDB. The table has approx. 7 millions of rows:

+--------------------+-------------+------+-----+---------+----------------+
| Field              | Type        | Null | Key | Default | Extra          |
+--------------------+-------------+------+-----+---------+----------------+
| id                 | int(11)     | NO   | PRI | NULL    | auto_increment |
| id_of_start        | int(11)     | NO   |     | NULL    |                |
| id_of_destination  | int(11)     | NO   |     | NULL    |                |
| city_start         | text        | NO   |     | NULL    |                |
| city_destination   | text        | NO   |     | NULL    |                |
| distance           | double      | NO   |     | NULL    |                |
+--------------------+-------------+------+-----+---------+----------------+

Can anyone advise me how to optimize a database or query?

Sahasrar
  • 3
  • 2

1 Answers1

0

For this query, you're supposed to use an index for city_start + distance

CREATE INDEX idx_citie_start_distance ON cities (city_start, distance);

You may also create two indexes: city_start and another for distance. That should work fine as well.

surfingonthenet
  • 695
  • 2
  • 6
  • It works, thank you. I also got a tip to change storage engine to MyISAM and query time is same than InnoDB with Index.... Is that the way too? or is it not a good way how to make DB for this solution? – Sahasrar Apr 16 '22 at 19:33
  • @Sahasrar, InnoDB allows you to use CONSTRAINTS and handles ROW LOCK, which means InnoDB is a better choice if your table process a higher volume or UPDATEs and/or DELETEs. MyISAM allows concurrent INSERTs and SELECTs, which might be a better choice if your table handles load bulk INSERTS and very little UPDATEs or DELETEs – surfingonthenet Apr 17 '22 at 21:09
  • This table si about search for nearest cities. So 99% of queries will be about reading. From your comment i think it is better for my table use MyISAM, am I wrong? – Sahasrar Apr 17 '22 at 21:27
  • @Sahasrar, that makes sense. I'd choose MyISAM in this case – surfingonthenet Apr 18 '22 at 17:45