Reputation: 42602
I am using MySQl database.
I know if I create a index for a column, it will be fast to query data from a table by using that column index. But, I still have the following questions:
(suppose I have a table named cars, there is a column named country, and I have created index for country column)
I know for example the query SELECT * FROM cars WHERE country='japan'
will use the index on column country to query data which is fast. How about !=
operation? will SELECT * FROM cars WHERE country!='japan';
also use index to query data?
Does WHERE ... IN ...
operation use index to query data? For example SELECT * FROM cars WHERE country IN ('japan','usa','sweden');
Upvotes: 3
Views: 304
Reputation: 14911
You can use EXPLAIN SELECT
to find out if your query uses an index or not.
For example:
EXPLAIN SELECT *
FROM A
WHERE foo NOT IN (1,4,5,6);
Might yield:
+----+-------------+-------+------+---------------
| id | select_type | table | type | possible_keys
+----+-------------+-------+------+---------------
| 1 | SIMPLE | A | ALL | NULL
+----+-------------+-------+------+---------------
+------+---------+------+------+-------------+
| key | key_len | ref | rows | Extra |
+------+---------+------+------+-------------+
| NULL | NULL | NULL | 2 | Using where |
+------+---------+------+------+-------------+
In this case, the query had no possible_keys
and therefore used no key
to do the query. It's the key
column you'd be interested in.
More information here:
Upvotes: 2
Reputation: 1064
Use 'EXPLAIN' to see what happens with your query. You will probably be interested in the 'possible_keys' and 'key' column.
EXPLAIN SELECT * FROM CARS WHERE `country` != 'japan'
Upvotes: 0
Reputation: 79185
The general answer is: it depends. It depends on what the database optimizer thinks is the best way to retrieve the data, and its decision may need on the distribution of the data.
For example, if 99% of your rows have country = 'japan', maybe the first query (=
) will not use the index, but the country with !=
will use it.
Upvotes: 3