PostgreSQL — Primary Key
Basic Primary Key
CREATE TABLE users (
id SERIAL PRIMARY KEY,
name VARCHAR(100)
);
Named Primary Key
CREATE TABLE users (
id SERIAL,
name VARCHAR(100),
CONSTRAINT pk_users PRIMARY KEY (id)
);
Composite Primary Key
CREATE TABLE enrollments (
student_id INTEGER,
course_id INTEGER,
PRIMARY KEY (student_id, course_id)
);
Add Primary Key
ALTER TABLE users ADD PRIMARY KEY (id);
ALTER TABLE users ADD CONSTRAINT pk_users PRIMARY KEY (id);
Drop Primary Key
ALTER TABLE users DROP CONSTRAINT pk_users;
Auto Increment
CREATE TABLE users (
id SERIAL PRIMARY KEY,
name VARCHAR(100)
);
UUID Primary Key
CREATE TABLE users (
id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
name VARCHAR(100)
);
Mini Practice
- Create primary key
- Create composite key
- Add primary key to existing table
- Use UUID as primary key
Up Next
Continue with Foreign Key — foreign key constraints.
Related Topics
Frequently Asked Questions about Primary Key
What is Primary Key in PostgreSQL?
Primary Key is a fundamental concept in PostgreSQL. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Primary Key?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Primary Key.
Why is Primary Key important in PostgreSQL?
Primary Key is essential for PostgreSQL development. Understanding this concept will help you write better code and solve real-world problems more effectively.