Search code examples
postgresqlcreate-table

PostgreSQL - CREATE TABLE - Apply constraints like PRIMARY KEY in attributes that are inside composite types


I want to implement an object-relational database, using PostgreSQL. I do not want to use ORACLE. Can I create a composite type, and then use it in a table, adding a restriction for example of a primary key in one of its attributes? Below I leave an example:

CREATE TYPE teamObj AS (
    idnumeric,
    name character varying,
    city character varying,
    estadiumName character varying,
    jugadores playerObj[]
);

CREATE TABLE teamTable (
    equipo equipoobj,
    PRIMARY KEY (equipo.id)
);

The line PRIMARY KEY (equipo.id) gives an error, and I've read a lot of documentation of this topic, and I don't find the solution, maybe PostgreSQL has not implemented yet, or will never implement it, or I don't understand how runs PostgreSQL...

Does somebody have a solution?

Thank you.


Solution

  • No, you cannot do that, and I recommend that you do not create tables like that.

    Your table definition should look pretty much like your type definition does. There is no need for an intermediate type definition.

    Reasons:

    • that will not make your schema more readable

    • that violates the first normal form for relational databases

    • that does not match an object oriented design any better than the simple table definition

    As a comfort, PostgreSQL will implicitly define a composite type of the same name whenever you define a table, so you can do things like

    CAST(ROW(12, 'Raiders', 'Wolfschoaßing', 'Dorfwiesn', NULL) AS team)
    

    or

    CREATE FUNCTION getteam(id) RETURNS team