Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

postgresql: how list indexed columns?

There is a lot of information, that can be retrieved from information_schema and pg_catalog in postgresql. I would like to retrieve information about columns indexed by a certain index, similar to what I would achieve with pragma index_info(<index_name>) in sqlite3. How can this be achieved without parsing create index statement?

like image 928
gruszczy Avatar asked Mar 20 '11 20:03

gruszczy


People also ask

How do I view PostgreSQL index?

If you use psql to access the PostgreSQL database, you can use the \d command to view the index information for a table.

How do I get a list of columns in PostgreSQL?

To list down all tables columns on a specific table in the a PostgreSQL database using psql command-line, you can use \dS your_table_name.

How do I check if a column is indexed?

To check if index exists on column uses sp_helpindex function or extract information from sys. tables, sys. columns, sys. indexes, sys.


1 Answers

Those things are pretty easy to find out.

Simply run psql with the -E option and it will show you the SQL statements that are used. So when running \d index_name the following statement (among others) is used to retrieve the index columns:

SELECT a.attname,
       pg_catalog.format_type (a.atttypid,a.atttypmod),
       (SELECT SUBSTRING (pg_catalog.pg_get_expr (d.adbin,d.adrelid) FOR 128)
        FROM pg_catalog.pg_attrdef d
        WHERE d.adrelid = a.attrelid
        AND   d.adnum = a.attnum
        AND   a.atthasdef)a.attnotnull,
       a.attnum,
       pg_catalog.pg_get_indexdef (a.attrelid,a.attnum,TRUE) AS indexdef
FROM pg_catalog.pg_attribute a
WHERE a.attrelid = (SELECT oid FROM pg_class WHERE relname = 'index_name')
AND   a.attnum > 0
AND   NOT a.attisdropped
ORDER BY a.attnum;
like image 187
a_horse_with_no_name Avatar answered Nov 15 '22 03:11

a_horse_with_no_name