Score:0

Why my simple searching query is too slow?

ru flag

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?

Score:0
st flag

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.

Sahasrar avatar
ru flag
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?
st flag
@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
Sahasrar avatar
ru flag
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?
st flag
@Sahasrar, that makes sense. I'd choose MyISAM in this case
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.