SQLite User Forum

UNIQUE column constraint - where’s the UNIQUE INDEX?
Login

UNIQUE column constraint - where's the UNIQUE INDEX?

(1) By anonymous on 2022-11-12 13:07:50 [source]

From the docs:

<quote> 3.6. UNIQUE constraints ... In most cases, UNIQUE and PRIMARY KEY constraints are implemented by creating a unique index in the database... the following schemas are logically equivalent:

CREATE TABLE t1(a, b UNIQUE);

CREATE TABLE t1(a, b PRIMARY KEY);

CREATE TABLE t1(a, b); CREATE UNIQUE INDEX t1b ON t1(b); </quote>

Is this unique index "hidden"? It doesn't show up in ".schema TABLE"

Thanks!

(2) By Richard Hipp (drh) on 2022-11-12 13:17:07 in reply to 1 [link] [source]

The .schema command deliberately omits the magic indexes that SQLite creates in order to implement UNIQUE and (some) PRIMARY KEY constraints. Those indexes have names like: "sqlite_autoindex_t1_1". You can see all indexes by running:

  SELECT tbl_name, name FROM sqlite_schema
   WHERE type='index'
   ORDER BY tbl_name, name;

To see just the indexes that ".schema" omits, run:

  SELECT tbl_name, name FROM sqlite_schema
   WHERE type='index'
     AND name LIKE 'sqlite_autoindex%'
   ORDER BY tbl_name, name;

(3) By anonymous on 2022-11-12 13:45:09 in reply to 2 [link] [source]

Gotcha. I knew about those 'autoindexes' but the system doesn't say if they're UNIQUE or not, or which columns are part of the autoindex.

In fact, SQLiteStudio says they're NOT unique, even though the table create specifies unique for the column.

Thanks Dr Hipp!

(4.2) By Keith Medcalf (kmedcalf) on 2022-11-12 15:38:40 edited from 4.1 in reply to 3 [link] [source]

SQLiteStudio is in error. Technically, all indexes are unique. A "non-unique" index is made unique by including the referents primary key (or rowid), which makes the entry "unique". Indexes which are declared unique differ only in that the referents primary key (or rowid) is not part of the key but rather the payload.

That is to say that when an index is created on a rowid table column a then if the index is declared UNIQUE then you get an index on a with the rowid as the payload (not the key). If the index is not declared unique then the primary key or rowid is part of the key, and the payload is empty. In both cases the "entry" (key) itself is unique.

There are introspection pragma's which will retrieve information about tables and indexes.

(5) By anonymous on 2022-11-12 17:53:59 in reply to 4.2 [link] [source]

Thanks for the explanation.

How do I access those 'introspection pragmas'?

(6) By Keith Medcalf (kmedcalf) on 2022-11-12 18:20:25 in reply to 5 [link] [source]

Examples:

pragma table_info;
pragma table_xinfo;
pragma index_info;
pragma index_list;

and so on and so forth.

Go to the main page https://sqlite.org/index.html and look for a link entitled Pragmas and click on it https://sqlite.org/pragma.html

They are SQL statements.