Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sqlite. How to create an index in attached DB?

I have a problem with adding index to memory database attached to main database.

1) I open the database (F) from file

2) Attach the :memory: (M) database

3) Create tables in database M

4) Copy data from F to M

I would also like to create an index in database M, but don't know how to do that. This code creates index but in F database:

sQuery = "CREATE INDEX IF NOT EXISTS [INDID] ON [PANEL]([ID]  ASC);";

I tried to add the name qualifier before table name like this:

sQuery = "CREATE INDEX IF NOT EXISTS [INDID] ON [M.PANEL]([ID]  ASC);";

but SQLite returns with message that column main.M.PANEL does not exist.

What can I do?

like image 808
kappa Avatar asked Nov 15 '11 09:11

kappa


People also ask

How does database CREATE INDEX?

Indexes can be created using one or more columns of a database table, providing the basis for both rapid random lookups and efficient access of ordered records. An index is a copy of selected columns of data, from a table, that is designed to enable very efficient search.

How do I index a table in SQLite?

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.

Does SQLite CREATE INDEX on primary key?

In an ordinary SQLite table, the PRIMARY KEY is really just a UNIQUE index. The key used to look up records on disk is the rowid. The special "INTEGER PRIMARY KEY" column type in ordinary SQLite tables causes the column to be an alias for the rowid, and so an INTEGER PRIMARY KEY is a true PRIMARY KEY.


1 Answers

just put the square brackets around the prefix [M].[panel] or just skip them

UPD: you shoud set prefix before the index name instead of the table name:

sqlite> attach database ":memory:" as m;
sqlite> .databases
seq  name             file
---  ---------------  ----------------------------------------------
0    main
2    m
sqlite> create table m.users (id int, name TEXT);
sqlite> create unique index m.qwe on users (name);
sqlite> insert into m.users VALUES(2,'asd');
sqlite> insert into m.users VALUES(3,'asd');
Error: column name is not unique
like image 105
newtover Avatar answered Oct 22 '22 08:10

newtover