Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a list of indexed Columns for a given Table

Tags:

c#

sqlite

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      |
 ------------------------------------
like image 695
ctacke Avatar asked Nov 16 '12 23:11

ctacke


People also ask

How do I find a list of indexes on a table?

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.

How do I get a list of indexes in SQL?

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.

How do I get a list of indexes on a table in SQL Server?

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.

How do I get a list of all columns?

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'


2 Answers

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.

like image 112
Neil Avatar answered Oct 20 '22 18:10

Neil


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'
like image 45
John Ward Avatar answered Oct 20 '22 18:10

John Ward