Which partition contains a specific row in my PostgreSQL database?

September 09, 2020

If you are enjoying working with PostgreSQL declarative partitioning, you might be wondering how to check which partition contains a specific record. While it is quite obvious in the cases of list or range partitioning, it is a bit trickier with hash partitioning.

Don’t worry. Here you can find a quick way to determine which partition contains a given row, by simply taking advantage of PostgreSQL’s system columns – specifically tableoid.

The example below assumes we have a partitioned table called collections (parent table) which is partitioned by hash based on the value of its primary key, a serial field called collection_id (the number of partitions is irrelevant, but in the example I set up 32).

SELECT tableoid::pg_catalog.regclass, *
  FROM collections
  WHERE collection_id = 2;

The above query retrieves the name of the partition that contains the record with collection_id = 2 in the hash partitioned table called collections:

    tableoid    | collection_id | ...
----------------+---------------+ ...
 collections_26 |             2 | ...

As you can see, the record is stored, based on the naming I adopted, in the 27th partition: collections_26.

In order to adapt it to your case, you just need to change the names of tables and columns.

Share this

Relevant Blogs

Random Data

This post continues from my report on Random Numbers. I have begun working on a random data generator so I want to run some tests to see whether different random...
December 03, 2020

More Blogs

Full-text search since PostgreSQL 8.3

Welcome to the third – and last – part of this blog series, exploring how the PostgreSQL performance evolved over the years. The first part looked at OLTP workloads, represented...
November 05, 2020

Números aleatorios

He estado trabajando gradualmente en el desarrollo desde cero de herramientas para probar el rendimiento de los sistemas de bases de datos de código abierto. Uno de los componentes de...
November 04, 2020