HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Is there a way to avoid duplicating the definition of a foreign key?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
definitionthewayforeignavoidduplicatingtherekey

Problem

I was wondering about this example

CREATE TABLE cities (
        city     varchar(80) primary key,
        location point
);

CREATE TABLE weather (
        city      varchar(80) references cities(city),
        temp_lo   int,
        temp_hi   int,
        prcp      real,
        date      date
);


The definition of city as varchar(80) is duplicated here. Is there a PostgreSQL syntax that allows not to duplicate varchar(80), only basing itself on references cities(city) so as to create the weather table?

Solution

There is no way to do that. And, frankly, I don't see the need.

Remember that referenced and referencing column don't have to share the same data type. They just have to have an = operator defined between them.

If your aim is to shorten the syntax, you could omit the column (or column list) of the referenced column(s) if it's the PK:

CREATE TABLE weather (
    city      text references cities,
    temp_lo   int,
    ...


Data type in the example is compatible but not the same (textvs. varchar(80)), referenced column is assumed to be the primary key of the table cities.

I quote the manual on CREATE TABLE:


If refcolumn is omitted, the primary key of the reftable is used

Code Snippets

CREATE TABLE weather (
    city      text references cities,
    temp_lo   int,
    ...

Context

StackExchange Database Administrators Q#33624, answer score: 6

Revisions (0)

No revisions yet.