Given a SQLite database, I need to get a list of what columns in a given Table are indexed, and the sort order. I need to do this from code (C#, though that shouldn't matter), so what I really need is a SQL statement, if one exists, that does this.
I know that I can do this:
SELECT sql FROM SQLite_master WHERE type = 'index' AND tbl_name = 'MyTableName'
And then manually parse the resulting SQL, but is there some metadata somewhere that I can just query that would give me something along these lines?
------------------------------------ | name | column | direction | ------------------------------------ | idx_a | ColA | ASC | ------------------------------------ | idx_a_b | ColB, ColB | DESC | ------------------------------------
To see indexes for all tables within a specific schema you can use the STATISTICS table from INFORMATION_SCHEMA: SELECT DISTINCT TABLE_NAME, INDEX_NAME FROM INFORMATION_SCHEMA. STATISTICS WHERE TABLE_SCHEMA = 'your_schema'; Removing the where clause will show you all indexes in all schemas.
You can use the sp_helpindex to view all the indexes of one table. And for all the indexes, you can traverse sys. objects to get all the indexes for each table.
sp_helpindex is a system stored procedure which lists the information of all the indexes on a table or view. This is the easiest method to find the indexes in a table. sp_helpindex returns the name of the index, description of the index and the name of the column on which the index was created.
To get the column name of a table we use sp_help with the name of the object or table name. sp_columns returns all the column names of the object. The following query will return the table's column names: sp_columns @table_name = 'News'
Use the PRAGMA index_list(table-name);
and PRAGMA index_info(index-name);
extensions.
Update: PRAGMA schema.index_xinfo(index-name);
will return the sort order for key columns.
Add whatever conditions you want in where clause. Fields are:
CREATE TABLE sqlite_master (
type TEXT,
name TEXT,
tbl_name TEXT,
rootpage INTEGER,
sql TEXT
);
Pastable select...the important field to include for indexes is "sql". Will not list primary keys defined in the create table statment.
select type, name, tbl_name, sql
FROM sqlite_master
WHERE type='index'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With