G
G
grigorie19902019-12-24 14:33:19
PostgreSQL
grigorie1990, 2019-12-24 14:33:19

How to make a table in postgres with fields that are required depending on the field type?

How to make field1 or field2 in a table in postges one field mandatory and the other field zero when type_id field values ​​are 1 or 2. I.e. if one is filled, the other must not be filled, it must be null.
Here is an example using "limits":

col1 CHECK (((col2 IS NULL) AND (col1 IS NOT NULL)) AND type_id ==2) OR (((col1 IS NULL) AND (col2 IS NOT NULL)) AND type_id == 1)
  type_id integer
  col2 CHECK (((col1 IS NULL) AND (col2 IS NOT NULL)) AND type_id ==1) OR (((col2 IS NULL) AND (col1 IS NOT NULL)) AND type_id == 2)

And now if I add fields, it turns out I need to rewrite the old conditions. In theory, if the table is filled with data and you change the value by migration, and there are no contradictions, then it should work.
In general, such a task is a table of transactions and a table of operations, they are connected by the field operation_id, many transactions correspond to one operation. The question is if there are types of operations that differ in fields, should they be written in the same table with the type field or in different ones? If in different then several fields-keys must be added. The problem with a single table is that, firstly, it can grow in width, and you need to rewrite the constraints of the old fields as you add operations of new types, what to do?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikita Krasnikov, 2019-12-26
@YekitKsv

Can you show the table schema? It seems to me that you have an error in the architecture ... Or I did not quite understand what "types of operations that differ in fields" means

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question