I need to be able to query a PostgreSQL database to obtain information about the indexes present and their details.
On SQL Server, I can do the following to get a list of all tables/indexes/columns for all indexes:
select TABLE_NAME, INDEX_NAME, NON_UNIQUE, COLUMN_NAME
from INFORMATION_SCHEMA.STATISTICS
where TABLE_SCHEMA = 'my_schema'
order by TABLE_NAME, INDEX_NAME, SEQ_IN_INDEX
It seems that the STATISTICS table of INFORMATION_SCHEMA is a SQL Server extension. How can I do the equivalent in PostgreSQL?
EDIT: I'm specifically trying to return a denormalized result set as follows
TableName, IndexName, UniqueFl, ColumnName
So I get a row back for each column in all indexes.
Thanks, Jon
The SQL shell(psql): If we use psql to retrieve the PostgreSQL database, the \d command is used to view the index data for a table. The pg_indexes view: The pg_indexesview provides us to access useful information on each index in the PostgreSQL database.
The PostgreSQL Metadata processor determines the PostgreSQL table where each record should be written, compares the record structure against the table structure, then creates or alters the table as needed. For information about supported versions, see Supported Systems and Versions.
Postgres primarily caches indexes based on how often they're used, and it will not use an index if the stats suggest that it shouldn't -- hence the need to analyze after an import. Giving Postgres plenty of memory will, of course, increase the likelihood it's in memory too, but keep the latter points in mind.
All indexes in PostgreSQL are secondary indexes, meaning that each index is stored separately from the table's main data area (which is called the table's heap in PostgreSQL terminology). This means that in an ordinary index scan, each row retrieval requires fetching data from both the index and the heap.
What metadata are you looking for?
There are all sorts of swell things you can find out, if you know what you're looking for. For example, here's a dump of index stats and metadata.
SELECT *, pg_size_pretty(pg_relation_size(indexrelname::text))
FROM pg_stat_all_indexes
WHERE schemaname = 'public'
Digging through the postgresql wiki will turn up all sorts of good stuff.
I don't think this is possible from the information_schema see this discussion. Indexes created other than from constraints won't be in the information schema.
However from the system tables you can see this question
The query i'm using to see the list of indexes and it's actual size:
SELECT relname AS name,
reltuples as count, (c.relpages * (8192 /1024) / 1024 ) as size_mb,
c.relfilenode::regclass, cast(c.oid::regclass as TEXT), c.relnatts, c.relkind
FROM pg_class c, pg_namespace n
WHERE
n.nspname ='MyNamespace'
and n.oid = c.relnamespace
and c.relkind = 'i'
ORDER BY c.relpages DESC;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With