AI Hints
Home›PostgreSQL Tutorial›Creating Tables
PostgreSQL · Lesson 17 of 120

Identity Columns

IDs that count themselves.

⏱ 2 min read▶ Video at 14:08🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

Every event needs a unique ID. You don't want to pick numbers by hand. An identity column fills itself in, one, two, three, and so on.

  • Unique ID
  • Not by hand
  • Identity

An identity primary key

Event ID is generated always as identity, and it's the primary key. We insert two events without giving an ID. Run it. Postgres numbered them one and two.

query.sqlsql
CREATE TABLE events (
  event_id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  title    text NOT NULL
);

INSERT INTO events (title) VALUES ('Poetry Night'), ('Kids Story Hour');
SELECT * FROM events;
Output
CREATE TABLE
INSERT 0 2
 event_id |      title
----------+-----------------
        1 | Poetry Night
        2 | Kids Story Hour
(2 rows)

Identity vs serial

Identity is the modern, standard way. Serial is the older Postgres way, and still common in old code. Generated always stops people from setting IDs by accident. And for IDs that are safe to share, look at UUIDs later.

keyvalue
IDENTITYmodern standard
serialolder style
ALWAYSno manual IDs
UUIDshareable IDs

Summary

Identity columns number rows automatically, and make great primary keys. Next, rules that protect your data.

Key takeaways
  • IDENTITY
  • PRIMARY KEY
  • No manual IDs
Next up: Constraints — rules for your data