SQLite Forum

INDEX usage on inequality and IN
Login
Others have already mentioned analyze so I won't repeat that here.

One other complication though for using an index when using inequality matching is "where is the inequality in the set". Using your example, let's say type has four possible values, 1, 2, 3, and 4.

```
SELECT * FROM table WHERE type != 1
SELECT * FROM table WHERE type != 2
```

The first of these example queries will return all rows where type is 2, 3, or 4, which would be a contiguous set of index entries.

The second of the examples will return all rows where type is 1, 3, or 4, which would be two sets of index entries (get all rows that match type 1, skip all rows that match type 2, then get all rows that match type 3 & 4). Certainly this can be done, but it complicates the query planner based on a number of variables, especially if using prepared statements.

One way to rewrite the query:

```
SELECT * FROM table WHERE type < 2 OR type > 2
```

That might better indicate to the query planner that it can divide it up into two subqueries. Or perhaps even better:

```
SELECT * FROM table WHERE type < 2
UNION ALL
SELECT * FROM table WHERE type > 2
```

There are other possibilities that have been recommended in other responses.

In the end, you can't assume that the query plan is legitimate unless you are running it against the actual data. It is not enough to simply have a schema and explain a query plan, as the SQLite query planner takes a lot more information into account.