SQL Tips & Tricks – PostgreSQL Queries – Part 1

If you are working daily with PostgreSQL database, sometimes you may have a need to get some information or valid stuff that normally are inside of a Database Administrator scope.

In this article I will share with you 3 useful queries mainly for working with indexes in PostgreSQL, version 9.6+.

Duplicate Indexes

When multiple developers are working on a database and they have a possibility to create indexes, it may be a bit troublesome. There may be a case that one or many indexes will be created for same field (or fields). To check for duplicate indexes you can use query below. It uses standard pg_index results prepared key. One flaw of this query is that if you have more then 4 indexes duplicated it will show only 4, but hopefully it is not your case 🙂

Query Results:

idx1, idx2 … idx4 are Indexes names that are duplicates on a certain fields.

Indexes With Less Than 300 Scans

Another popular case is when your created index is not being used by query plan, either because of a way data are being queried or due to simple design issue.

With below query, you can verify all non unique (it is important to remove from analysis indexes created on unique keys) indexes with less than 300 scans, on schema different than postgres.

Query Results:

As a result, you will receive information about an index, its size, definition, table size, table name, schema name and usage information.

List Number Of Database Elements

This one is not perfomance specific, but still quite a nifty script to list number of database elements: tables, views, indexes, sequences and special.

Query Results:

As a results you will see number of mentioned elements for specific schema.

This is Part 1 and if so, there will be Part 2. With in depth information about tables and indexes in your database.

Data Craze Newsletter

If you want to be notified about new posts, and you want to get weekly dose of information from data world, feel free to sign up to this newsletter – join Data Craze community!

By clicking “Subscribe” you agree to send to You marketing information and to our Privacy Policy.




Leave a Reply

Your email address will not be published. Required fields are marked *