12

I've created the following table in Postgres...

create table printq (
   model varchar(20),
   session integer,
   timestamp timestamp DEFAULT now(),
   id serial);

It seems to do exactly what I need it to... it auto-increments the id column, when I clear the table using truncate "RESTART IDENTITY" it resets the sequence (which is why I rebuilt the table in the first place -- the id column used to not restart upon truncation)

Anyway, when I do a \d on the table, I don't see anything about a primary key.

Table "public.printq"
  Column   |            Type             |                      Modifiers                      
-----------+-----------------------------+-----------------------------------------------------
 model     | character varying(20)       | 
 session   | integer                     | 
 timestamp | timestamp without time zone | default now()
 id        | integer                     | not null default nextval('printq_id_seq'::regclass)

Three questions:

  • Is the ID column already a primary key since it auto-increments, or not?

  • If not, why would this table need a primary key, since it seems to be working fine? I know basically every table is supposed to have a primary key, but why exactly?

  • Finally, would the \d command tell me if this table had a primary key? If not, what would tell me?

1 Answer 1

16
  1. No, use id serial primary key for that.
  2. Well, a table doesn't actually "need" a primary key. It can live without PK, it can live without an autoincrementing field, it can contain duplicate rows all right. But in relational theory (on top of which SQL is built) each relation (i. e. table) is a set (in mathematical sense) of rows. So duplicate rows are not allowed, they are simply not possible in sets. And hence each relation has a field (or several fields) which has unique values for all the relation. Such field can be used to uniquely identify a row, and one of possible unique keys is called a primary key. Such a key is usually very useful for identifying the rows, that's why tables are supposed to have them. But technically they are not required.
  3. Yes, it will.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.