A
A
AnjeyTsibylskij2017-05-11 15:48:17
PostgreSQL
AnjeyTsibylskij, 2017-05-11 15:48:17

[PostgreSQL] What data type to choose?

There is a simple task, the table contains data for different types of entities. For example, there is a table of comments, and it stores comments for posts, photos, videos.
The table has two fields that are responsible for the entity entity_id - this is the id of the entity, and entity_type - the type of entity (post, photo, video).
The entity_id field is naturally int (bigint NOT NULL)
But the entity_type field makes me doubt it. Now I made them of type enum (character varying(255) NOT NULL) CONSTRAINT comments_entity_type_check CHECK (entity_type::text = ANY (ARRAY['post'::character varying, 'image'::character varying, 'video'::character varying]::text[]))
But I doubt the performance of this approach. Isn't it better to make entity_type -
small int? As though with int and it is simpler to build an index, and on the other hand enum limits possible options.
Is there a big performance gain between enum and small int?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
T
terrier, 2017-05-11
@terrier

Some kind of enum you don't have. the enum of a healthy person is:
Well, respectively, in the enum_type table there will be an entity_enum_type type.
https://www.postgresql.org/docs/9.6/static/datatyp...
Here is an enum that takes 4 bytes per value on disk, is clear and very efficient.

K
Konstantin Stepanov, 2017-05-11
@koronabora

Make a table of entity types. Each entity type will have its own id. Next in the object table, let's go to the entity type number.

R
romy4, 2017-05-11
@romy4

> Is there a big performance gain between enum and small int?
There is a gain in logic from the enum approach, it is convenient to use the type as an entity in functions.

L
lega, 2017-05-12
@lega

You can also combine entity_id and entity_type into one column (bigint),
if you need to join, you can use unique ids throughout the database (prefix ids),
it will also be convenient to refer to objects from other places with just one number, without specifying the type, i.e. to. the type is sewn into the id.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question