// SQL snippet

List indexes of a table with their columns

Before adding an index, check what is already there; a second index on the same columns doubles the write cost and buys nothing. This recipe lists every index on one table with the columns it covers.

Main statement
PostgreSQL
Também cobre
SQL Server MySQL SQLite

The task

A query is slow and you are tempted to add an index, or writes are slow and you suspect too many. Either way, start by seeing exactly which indexes exist and what they cover.

The snippet

Written for PostgreSQL. Versions for SQL Server, MySQL and SQLite are under Variations.

PostgreSQL
SELECT indexname AS index_name,
       indexdef AS definition
FROM pg_indexes
WHERE schemaname = 'public' AND tablename = 'users'
ORDER BY indexname;

Como funciona

pg_indexes is a convenience view over pg_index that renders each index through pg_get_indexdef, so the definition column already includes column list, uniqueness, partial predicates and operator classes. It is the fastest way to eyeball a table's indexing. For column-level detail, join pg_index and unnest indkey the way the foreign-key recipe does.

Variations

MySQL

MySQL
SHOW INDEX FROM users;
-- Seq_in_index gives column position; Column_name the column

SQLite

SQLite
PRAGMA index_list(users);
PRAGMA index_info(idx_users_email);
-- run index_info once per index from index_list

SQL Server

SQL Server
SELECT i.name AS index_name,
       c.name AS column_name,
       ic.key_ordinal, ic.is_included_column
FROM sys.indexes i
JOIN sys.index_columns ic ON ic.object_id = i.object_id AND ic.index_id = i.index_id
JOIN sys.columns c ON c.object_id = ic.object_id AND c.column_id = ic.column_id
WHERE i.object_id = OBJECT_ID('dbo.Users')
ORDER BY i.name, ic.key_ordinal;

Questions that come up

Why does an index show up that I never created?

Primary-key and unique constraints are enforced through indexes that the engine creates for you, usually named after the constraint (users_pkey on PostgreSQL, PRIMARY on MySQL, sqlite_autoindex_users_1 on SQLite). MySQL also creates an index on the referencing column of a foreign key if none exists. PostgreSQL never does that, though ORM migrations often add one.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.