Search code examples
postgresqlprimary-keyddlcreate-table

Is using SERIAL fine for the primary key when creating a table of all the comments made by users?


I am trying to learn postgres after working with mongodb for a while, and I'm wondering how to have a unique ID for each comment.

I have a foreign key userId for which user created the comment, but for primary key I need some kind of commentId. Is it fine to use SERIAL for my commentId? Or, is there a better approach like UUIDs? I don't know if I will ever have to migrate the data.


Solution

  • Since the actual value of the comment id does not interest you (just the fact that it's there and it's unique), serial is a good choice for such a column. Note that in modern PostgreSQL databases (since 7.3), creating a serial does not automatically mean it will have a unique constraint, so you'd have to handle that explicitly. E.g.:

    CREATE TABLE comments (
        comment_id SERIAL PRIMARY KEY,
        user_id INT REFERENCES users(id), -- You should probably also index it
        comment VARCHAR(200) -- Or any other reasonable size
    )
    

    EDIT:
    To answer the question in the comments, a similar behavior could be created for a UUID column by giving it a default value of a newly generated UUID.

    First, you'd have to install the postgres-contrib` package (if you don't have it installed yet). E.g., On Red Hat based linuxes, you could run (as root):

    $ dnf install postgresql-contrib
    

    Then, from a privileged user, you need to create the extension:

    CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
    

    This will create a generate_uuid_v1 function you could use:

    CREATE TABLE comments (
        comment_id UUID DEFAULT UUID_GENERATE_V1() PRIMARY KEY,
        user_id INT REFERENCES users(id), -- You should probably also index it
        comment VARCHAR(200) -- Or any other reasonable size
    )