Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find out if a SQLite index is unique? (With SQL)

Tags:

sqlite

I want to find out, with an SQL query, whether an index is UNIQUE or not. I'm using SQLite 3.

I have tried two approaches:

SELECT * FROM sqlite_master WHERE name = 'sqlite_autoindex_user_1'

This returns information about the index ("type", "name", "tbl_name", "rootpage" and "sql"). Note that the sql column is empty when the index is automatically created by SQLite.

PRAGMA index_info(sqlite_autoindex_user_1);

This returns the columns in the index ("seqno", "cid" and "name").

Any other suggestions?

Edit: The above example is for an auto-generated index, but my question is about indexes in general. For example, I can create an index with "CREATE UNIQUE INDEX index1 ON visit (user, date)". It seems no SQL command will show if my new index is UNIQUE or not.

like image 381
Christian Davén Avatar asked Oct 01 '08 12:10

Christian Davén


People also ask

Is index unique in SQL?

Provided that the data in each column is unique, you can create both a unique clustered index and multiple unique nonclustered indexes on the same table. Unique indexes ensure the data integrity of the defined columns.

Which is the syntax for unique index is?

The syntax to create an index in SQL is: CREATE [UNIQUE] INDEX index_name ON table_name (column1, column2, ... column_n); UNIQUE.

What is unique in SQLite?

Introduction to SQLite UNIQUE constraintA UNIQUE constraint ensures all values in a column or a group of columns are distinct from one another or unique. To define a UNIQUE constraint, you use the UNIQUE keyword followed by one or more columns. You can define a UNIQUE constraint at the column or the table level.

Does unique constraint create index SQLite?

Yes, they are the same. A unique constraint in a table definition is exactly and precisely the same as an explicit unique index, save for what is different: an explicit UNIQUE index may contain expressions, a UNIQUE constraint in a table may only contain bare columns.


1 Answers

PRAGMA INDEX_LIST('table_name');

Returns a table with 3 columns:

  1. seq Unique numeric ID of index
  2. name Name of the index
  3. unique Uniqueness flag (nonzero if UNIQUE index.)

Edit

Since SQLite 3.16.0 you can also use table-valued pragma functions which have the advantage that you can JOIN them to search for a specific table and column. See @mike-scotty's answer.

like image 91
finnw Avatar answered Sep 27 '22 19:09

finnw