Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using SQLite how do I index columns in a CREATE TABLE statement?

Tags:

sqlite

People also ask

How do I index a column in SQLite?

1. Syntax. The CREATE INDEX command consists of the keywords "CREATE INDEX" followed by the name of the new index, the keyword "ON", the name of a previously created table that is to be indexed, and a parenthesized list of table column names and/or expressions that are used for the index key.

How does index work in SQLite?

A table may have multiple indexes. Whenever you create an index, SQLite creates a B-tree structure to hold the index data. The index contains data from the columns that you specify in the index and the corresponding rowid value. This helps SQLite quickly locate the row based on the values of the indexed columns.

Does SQLite automatically create index?

Indexes are automatically created for primary key constraints and unique constraints.


You can't do precisely what you're asking, but unlike some RDBMSs, SQLite is able to perform DDL inside of a transaction, with the appropriate result. This means that if you're really concerned about nothing ever seeing file_hash_list without an index, you can do

BEGIN;
CREATE TABLE file_hash_list (
  id INTEGER PRIMARY KEY,
  hash BLOB NOT NULL,
  filesize INTEGER NOT NULL
);
CREATE INDEX file_hash_list_filesize_idx ON file_hash_list (filesize);
COMMIT;

or the equivalent using the transaction primitives of whatever database library you've got there.

I'm not sure how necessary that really is though, compared to just doing the two commands outside of a transaction.

As others have pointed out, SQLite's indexes are all B-trees; you don't get to choose what the type is or what portion of the column is indexed; the entire indexed column(s) are in the index. It will still be efficient for range queries, it just might take up a little more disk space than you'd really like.


I don't think you can. Why can't you use a second query? And specifying the size of the index seems to be impossible in SQLite. But then again, it is SQ_Lite_ ;)

create index
    myIndex
on
    myTable (myColumn)