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?
PostgreSQL has a special kind of database object generator called SERIAL. It is used to generate a sequence of integers which are often used as the Primary key of a table.
By simply setting our id column as SERIAL with PRIMARY KEY attached, Postgres will handle all the complicated behind-the-scenes work and automatically increment our id column with a unique, primary key value for every INSERT .
Each table can only have one primary key. Access can automatically create a primary key field for you when you create a table, or you can specify the fields that you want to use as the primary key.
PostgreSQL serial data type is used to define the auto increment number of column in a table; PostgreSQL serial will generate a serial sequence of integer numbers. We can also restart the serial number after creating a table using alter command in PostgreSQL; the serial data type's storage size is 4 bytes.
id serial primary key
for that.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With