3

I have a DDL for some tables similar to the following:

CREATE TABLE devices
(
  device_uuid            uuid NOT NULL,
  manufacturer_uuid       NOT NULL,
  ...
  CONSTRAINT device_manufacturer_uuid_fkey FOREIGN_KEY (manufacturer_uuid)
      REFERENCES manufacturer (manufacturer_uuid) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT devices_device_uuid_key UNIQUE (device_uuid),
  CONSTRAINT devices_pkey PRIMARY KEY (device_uuid)
);

I might have different types of devices, e.g. "peripherals", "power", "graphics", etc.

There are two approaches I can take:

  1. Add a simple type column to this table

    • Pros: I have a pretty simple database structure.

    • Cons: There could potentially be hundreds of thousands of entries, which could lead to performance problems. The list of "devices" would be searched fairly regularly, and searching through all those entries to find all those of type "peripherals" every time might not be great.

  2. Inherit from the above table for every type.

The DDL for this would look similar to the following (I believe):

CREATE TABLE devicesperipherals 
(
  type                       device NOT NULL,
  CONSTRAINT devicesperipherals_manufacturer_uuid_fkey FOREIGN_KEY (manufacturer_uuid)
      REFERENCES manufacturer (manufacturer_uuid) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT devicesperipherals_device_uuid_key UNIQUE (device_uuid)
  CONSTRAINT devices_manufacturer_uuid_fkey FOREIGN_KEY (manufacturer_uuid)
      REFERENCES manufacturer (manufacturer_uuid) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION, 
)
INHERITS (devices)
WITH (
  OIDS=FALSE
);
  • Pros: From what I know about table inheritance, this approach should have better performance.

  • Cons: More complex database structure, more space required for indexing.

Which is the preferred approach in such a case? Why?

filpa
  • 3,651
  • 8
  • 52
  • 91
  • 2
    For your inheritance **pros**: why should that approach have better performance? It should only have that if you could use [constraint exclusion](https://www.postgresql.org/docs/current/static/ddl-partitioning.html#DDL-PARTITIONING-CONSTRAINT-EXCLUSION) (but that requires the `type` column on the parent table anyway) -- For its **cons**: I highly recommend that you read the [caveats](https://www.postgresql.org/docs/current/static/ddl-inherit.html#DDL-INHERIT-CAVEATS) section on inheritance. – pozs Mar 24 '17 at 09:54
  • If you have a few (and limited) `type`s you might be better off with [partial indexes](https://www.postgresql.org/docs/current/static/indexes-partial.html) for each type. – pozs Mar 24 '17 at 10:02
  • A primary key implies unique and so you do not need a second unique index on `device_uuid` – Clodoaldo Neto Mar 24 '17 at 11:49

0 Answers0