Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL using constants in foreign key

The syntax for Foreign Key, as described in official documentation, includes set of column from table A referencing set of column from table B.

Is it possible to use Constant in foreign key declaration?

The problem is, I have table DICTIONARIES which contains all dictionary values, discriminated by TYPE. I know it's not good design, but unfortunatelly, I have not much to say, as the DB admin wants to 'minimize the number of tables'...

Is it possible to achieve something like that:

CREATE TABLE PERSON (
  id integer primary key,
  country_id integer,
  ...
  FOREIGN KEY ('COUNTRY', country_id) REFERENCES DICTIONARIES(TYPE, ID)
)

It would effectively solve the issue. I'm aware I can add column to the table person, which will has only one possible value 'COUNTRY', or I could write a trigger, but I'd prefer to avoid that to keep design cleaner.

like image 793
Danubian Sailor Avatar asked Nov 11 '22 05:11

Danubian Sailor


1 Answers

A foreign key constraint is from one table's columns to another's columns, so, no.

Of course the database should have a table COUNTRY(country_id). Commenters have pointed out that your admin is imposing an anti-pattern.

Good, you are aware that you can define a column and set it to the value you want and make the foreign key on that. That is an idiom used for avoiding triggers in constraining some subtyping schemes.

You may be able to compute a 'COUNTRY' column depending on your DBMS, at least.

Your question is essentially this one, see the end of the question & the comments & answers.

(Lots of functionality would be trivial to implement. Perhaps the difficulty (besides ignorance of consumers) is that arbitrary constraints become quickly expensive computationally. That might just get vendors aggravation. Also, optimization in SQL is impeded by its differences from the relatonal model.)

like image 159
philipxy Avatar answered Nov 14 '22 21:11

philipxy