Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Database Index not used if the where criteria is !=?

Tags:

sql

database

I have a index on a column and it is correctly used when the query is

select * from Table where x = 'somestring'

However it seems to be not used when the query is something like

select * from Table where x != 'someotherstring'

Is this normal or am I missing something else in the query? The actual query is of course much larger and so it could be caused by some other factor. Any other ideas why an index would not be used in a query?

like image 718
erotsppa Avatar asked Nov 18 '09 22:11

erotsppa


People also ask

When should database indexes not be used?

Indexes should not be used on tables containing few records. Tables that have frequent, large batch updates or insert operations. Indexes should not be used on columns that contain a high number of NULL values. Indexes should not be used on the columns that are frequently manipulated.

Can we use index in WHERE clause?

Indexes are also used to aid in filtering tables to assist in optimizing queries. The most obvious case of this is to optimize WHERE clauses. For example, the query "select * from employee where lastname = 'Jones'" results in a live cursor.

Why index is not used in query?

The reason the non-clustered index is not used is because it is more efficient to select the single row using the unique primary key clustered index. You can't get any faster than that to select all columns for a single row (barring a hash index on an in-memory table). Save this answer.

Can we use not in WHERE clause in SQL?

The SQL NOT condition (sometimes called the NOT Operator) is used to negate a condition in the WHERE clause of a SELECT, INSERT, UPDATE, or DELETE statement.


2 Answers

This is normal. Index will only be used if you have a '=' condition. Searching index for != condition is not effective.

Similarly, this may use the index (in Oracle)

select * from Table where x like 'some%'

but this wouldn't

select * from Table where x like '%thing%'

Also, select * from Table where x between 1 and 10 will use the index

but not select * from Table where x not between 1 and 10

like image 171
Chip Avatar answered Sep 22 '22 13:09

Chip


this is absolutely normal. index is used to look for exact something. where you start when I ask you to look a dictionary when I told you not start with 'S'.

you can always do this.

select * from Table a
where not exist (select * from table b where x = 'somestring' and a.key = b.key)
like image 32
Henry Gao Avatar answered Sep 21 '22 13:09

Henry Gao