Is it bad practice not to specify NOT NULL in a SERIAL field? Postgresql

Asked

Viewed 31 times

1

Hello, I was doing some activities and I differed from some colleagues. The end result was the same, but I was wondering if it is bad practice to use the following code

CREATE TABLE Estudio (
    codEst SERIAL PRIMARY KEY,
    nomeEst VARCHAR(25)
);

Instead of what my colleagues used:

CREATE TABLE Estudio (
    codEst SERIAL NOT NULL,
    nomeEst VARCHAR(25),
    
    CONSTRAINT pk_est PRIMARY KEY(codEst)
);

The result, for me, was the same. I read the documentation but found nothing about it, nor in questions here at Stack.

The two are 'acceptable' and only writing style, or should I get used to using the second, in the sense that this may cause problems in the future?

Thank you!

P.S.: the specifications of this table, were those:

inserir a descrição da imagem aqui

1 answer

1


The theory is that a field (or combination of fields of the same table) is a primary key so NOT NULL and UNIQUE are implicit, and so I think NOT NULL would not even need to be explained in the declaration.

Even by what you say here (worth visiting for more information) declare the field as SERIAL also implies in NOT NULL.

So I think it’s just a matter of style to choose which way you prefer to declare PRIMARY KEY, and I also don’t see why to explain this NOT NULL in the field declaration.

The second case would make more sense if the primary key was composed of more than one field. I find your statement more readable than your colleagues.

And the name of the studio in my view should be declared NOT NULL, but it will depend on the business rule.

In practice it is certainly very common and appropriate to combine SERIAL and PRIMARY KEY, as both complement each other when generating an artificial identity based on a numerical sequence automatically generated and already indexed for the records of the table, usual need in relational databases.

  • Thank you so much for the answer. I also came across this site, but I was kind of 'like' because it was the only place that mentioned it. Taking advantage, the way to declare the PK, in postgresql, always follows the standard table_field_tipochave. Would it be more appropriate to use a Constraint, as well as my colleagues, and declare as tipochave_tabela_fieldname? I wondered of using this other format, in a larger database would be easier to identify Fks and Pks. What do you think? Thank you once again.

  • 1

    Trust the manual: https://www.postgresql.org/docs/current/datatype-numeric.html#DATATYPE-SERIAL

  • @Alecsandercamilo I will leave it to others to give an opinion, I do not have an opinion formed.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.