DEV Community

Cover image for How to Use PostgreSQL Foreign Keys the Right Way
DbVisualizer
DbVisualizer

Posted on

How to Use PostgreSQL Foreign Keys the Right Way

PostgreSQL foreign keys allow you to define relationships between tables — like ensuring that every comment belongs to a valid post, or every order has a matching customer.

In this post, you’ll learn how to create foreign keys, how they work, and how to handle changes with actions like CASCADE, SET NULL, and RESTRICT.

Foreign Key Syntax

FOREIGN KEY (child_col)
REFERENCES parent_table (parent_col)
[ON DELETE action]
[ON UPDATE action]
Enter fullscreen mode Exit fullscreen mode

This constraint makes sure that each value in the child column matches a value in the referenced parent column.

Example: Users and Posts

CREATE TABLE users (
  id SERIAL PRIMARY KEY,
  username TEXT
);

CREATE TABLE posts (
  id SERIAL PRIMARY KEY,
  user_id INT,
  FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);
Enter fullscreen mode Exit fullscreen mode

Now if a user is deleted, all their posts are deleted too.

Common Referential Actions

  • CASCADE: Delete/update child rows automatically
  • SET NULL: Clear the foreign key
  • SET DEFAULT: Use the default value
  • RESTRICT / NO ACTION: Block changes if relationships exist

FAQ

What is a foreign key used for?

To create and enforce relationships between tables, ensuring your data remains valid.

What happens if I don't define a foreign key?

PostgreSQL won’t enforce any rules — which could lead to inconsistent or orphaned data.

Should I always use CASCADE?

Not always. It's convenient but dangerous if you're not careful. Test thoroughly before using it in production.

Do foreign keys affect performance?

They can slightly affect performance on inserts and deletes, but the benefits in data consistency usually outweigh that.

Conclusion

Postgres foreign keys are essential for creating reliable and connected databases. They help enforce structure, prevent broken relationships, and define clear behavior when changes occur.

By understanding foreign key syntax and using the right actions, you can design safer schemas and avoid data integrity issues. To simplify foreign key management, consider using a visual SQL tool like DbVisualizer — it supports PostgreSQL and helps you explore relationships quickly and clearly.

Read a Definitive Guide to Postgres Foreign Key for more insights.

Top comments (0)