Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if table inherits from other table in PostgreSQL

In PostgreSQL for these tables

CREATE TABLE cities (
    name            text,
    population      float,
    altitude        int     -- in feet
);

CREATE TABLE cities_capitals (
    state           char(2)
) INHERITS (cities);

How can I programmatically check whether one of these tables inherits from another table or not? (Think information_schema, pg_catalog, ...)

Should be true for cities_capitals and false for cities.

like image 302
Axel Fontaine Avatar asked Oct 07 '11 16:10

Axel Fontaine


People also ask

What are descendant tables Postgres?

So if table B inherits table A , and table C inherits table B , then: Tables B and C are descendant tables of A .

How can I list all foreign keys referencing a given table in Postgres?

To get a list of all foreign keys of the table using psql you can use the \d your_table_name command line.

How does table inheritance work in Postgres?

Inheritance in PostgreSQL allows you to create a child table based on another table, and the child table will include all of the columns in the parent table. Let's take a database that's used to store blueprints for different types of homes.


1 Answers

There is a catalog table for that: pg_inherits.

The catalog pg_inherits records information about table inheritance hierarchies. There is one entry for each direct child table in the database. (Indirect inheritance can be determined by following chains of entries.)

Here's a query that fits your question:

SELECT EXISTS (
   SELECT 1
   FROM   pg_catalog.pg_inherits
   WHERE  inhrelid = 'public.cities_capitals'::regclass
   );

TRUE if table cities_capitals inherits from somewhere, else FALSE.
Schema-qualify the name to be sure.

like image 151
Erwin Brandstetter Avatar answered Oct 23 '22 05:10

Erwin Brandstetter