<!-- mobian-agent-page publisher="dailydev" canonical="https://daily.dev/posts/creating-foreign-keys-sql-fundamentals-with-postgresql-2vweyexuw" -->

---
title: Creating Foreign Keys | SQL Fundamentals with PostgreSQL
description: Learn to create and define foreign keys in PostgreSQL, set ON DELETE actions, and establish one-to-one and one-to-many relationships. Practical examples and...
canonical: https://daily.dev/posts/creating-foreign-keys-sql-fundamentals-with-postgresql-2vweyexuw
twitter:card: summary_large_image
twitter:site: @dailydotdev
og:type: website
og:site_name: daily.dev
og:title: Creating Foreign Keys | SQL Fundamentals with PostgreSQL | daily.dev
og:description: Learn to create and define foreign keys in PostgreSQL, set ON DELETE actions, and establish one-to-one and one-to-many relationships. Practical examples and...
og:url: https://daily.dev/posts/creating-foreign-keys-sql-fundamentals-with-postgresql-2vweyexuw
og:image: https://api.daily.dev/og/posts/2VwEYeXUW.png
og:image:alt: Creating Foreign Keys | SQL Fundamentals with PostgreSQL
og:image:width: 1200
og:image:height: 630
og:locale: en
---

> ## Documentation Index
> Fetch the complete documentation index at: https://daily.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Creating Foreign Keys | SQL Fundamentals with PostgreSQL

**[Collections](https://daily.dev/sources/collections)** · 3 min read · 2 upvotes · 0 comments

## Summary

Learn to create and define foreign keys in PostgreSQL, set ON DELETE actions, and establish one-to-one and one-to-many relationships. Practical examples and SQL code snippets are included to help understand foreign key constraints and maintain referential integrity between tables.

## Content

# Comprehensive Guide to Creating Foreign Keys and Relationships in PostgreSQL

## Introduction
In PostgreSQL, foreign keys are crucial for maintaining referential integrity between tables by defining relationships. This guide covers creating and defining foreign keys, setting on delete actions, and establishing one-to-one and one-to-many relationships. Moreover, it provides practical examples and SQL code snippets to help you understand the appropriate scenarios for various foreign key constraints.

## Creating Foreign Keys
Foreign keys establish a connection between tables by ensuring that a value in one table corresponds to a value in another table. This guide will walk you through the steps to create foreign keys to maintain data integrity and referential relationships.

### One-to-Many Relationships
To create a one-to-many relationship, a foreign key is defined in the child table referencing the primary key of the parent table. This relationship ensures that each record in the child table corresponds to one record in the parent table.

#### Example SQL Code
```sql
ALTER TABLE child_table
ADD CONSTRAINT fk_parent
FOREIGN KEY (parent_id)
REFERENCES parent_table (id);
```

### Understanding `ON DELETE` Actions
When a parent record is deleted, foreign keys can define specific actions:
- `CASCADE`: Automatically deletes child records.
- `SET NULL`: Sets the foreign key in child records to `NULL`.
- `RESTRICT`: Prevents deletion of parent records if related child records exist.
- `NO ACTION`: Prevents deletion but defers constraint checking.

#### Example SQL Code with `ON DELETE` Action
```sql
ALTER TABLE child_table
ADD CONSTRAINT fk_parent
FOREIGN KEY (parent_id)
REFERENCES parent_table (id)
ON DELETE CASCADE;
```

## One-to-One Relationships
Creating a one-to-one relationship involves linking one record in a table to only one record in another table using a foreign key with a unique constraint. This maintains data integrity by ensuring each child record is uniquely related to a parent record.

### Ensuring Unique Foreign Keys
To maintain a one-to-one relationship, the foreign key in the child table should have a unique constraint.

#### Example SQL Code
```sql
ALTER TABLE child_table
ADD CONSTRAINT fk_parent
FOREIGN KEY (parent_id)
REFERENCES parent_table (id),
ADD CONSTRAINT unique_parent_id
UNIQUE (parent_id);
```

### Self-Referring Foreign Keys
In some cases, a table may reference itself to build hierarchical structures. This can be achieved by defining a foreign key that references the table's primary key.

#### Example SQL Code
```sql
ALTER TABLE employee
ADD CONSTRAINT fk_manager
FOREIGN KEY (manager_id)
REFERENCES employee (employee_id);
```

## Conclusion
Understanding how to effectively create and manage foreign key relationships in PostgreSQL is critical for maintaining data integrity. This guide provides a comprehensive overview of different types of foreign key relationships and the use of `ON DELETE` actions. By applying these principles and SQL examples, you can ensure your database design maintains robust referential integrity across all related tables.

## Similar posts on daily.dev

- [Don’t just attend KubeCon \+ CloudNativeCon, Merge Forward your experience\!](https://daily.dev/posts/don-t-just-attend-kubecon-cloudnativecon-merge-forward-your-experience--l0rpp73x8) · CNCF · 1 upvotes · 0 comments
- [Announcing H2 2026 KCDs](https://daily.dev/posts/announcing-h2-2026-kcds-m96goajm1) · CNCF · 1 upvotes · 0 comments
- [Two months of Open Community Groups](https://daily.dev/posts/two-months-of-open-community-groups-asf52zhbs) · CNCF · 0 upvotes · 0 comments
- [CNCF Unveils Schedule for KubeCon \+ CloudNativeCon Europe 2026](https://daily.dev/posts/cncf-unveils-schedule-for-kubecon-cloudnativecon-europe-2026-ikhcoa5cb) · CNCF · 2 upvotes · 0 comments
- [CNCF Debuts KubeCon \+ CloudNativeCon Japan 2026 Schedule](https://daily.dev/posts/cncf-debuts-kubecon-cloudnativecon-japan-2026-schedule-xp5pyudub) · CNCF · 1 upvotes · 0 comments

---

Tags: [#webdev](https://daily.dev/tags/webdev), [#backend](https://daily.dev/tags/backend), [#sql](https://daily.dev/tags/sql), [#postgresql](https://daily.dev/tags/postgresql)

[View this post on daily.dev](https://daily.dev/posts/creating-foreign-keys-sql-fundamentals-with-postgresql-2vweyexuw)

```json
{"@context":"https://schema.org","@graph":[{"@type":"Organization","@id":"https://daily.dev/#organization","name":"daily.dev","url":"https://daily.dev","logo":{"@type":"ImageObject","url":"https://daily.dev/apple-touch-icon.png","width":180,"height":180},"sameAs":["https://twitter.com/dailydotdev","https://github.com/dailydotdev","https://www.linkedin.com/company/daily-dev-ltd"]},{"@type":"WebSite","@id":"https://daily.dev/#website","url":"https://daily.dev","name":"daily.dev","publisher":{"@id":"https://daily.dev/#organization"},"potentialAction":{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https://daily.dev/search?q={search_term_string}"},"query-input":"required name=search_term_string"}}]}
{"@context":"https://schema.org","@type":"TechArticle","headline":"Creating Foreign Keys | SQL Fundamentals with PostgreSQL","url":"https://daily.dev/posts/creating-foreign-keys-sql-fundamentals-with-postgresql-2vweyexuw","mainEntityOfPage":{"@type":"WebPage","@id":"https://daily.dev/posts/creating-foreign-keys-sql-fundamentals-with-postgresql-2vweyexuw"},"datePublished":"2025-04-04T08:14:38.787Z","dateModified":"2025-04-05T08:18:08.048Z","description":"Learn to create and define foreign keys in PostgreSQL, set ON DELETE actions, and establish one-to-one and one-to-many relationships. Practical examples and...","image":"https://i.ytimg.com/vi/YGLdcki5TV4/sddefault.jpg","thumbnailUrl":"https://i.ytimg.com/vi/YGLdcki5TV4/sddefault.jpg","isAccessibleForFree":true,"articleSection":"Collections","inLanguage":"en","publisher":{"@type":"Organization","name":"daily.dev","url":"https://daily.dev","logo":{"@type":"ImageObject","url":"https://daily.dev/apple-touch-icon.png","width":180,"height":180}},"author":{"@type":"Organization","name":"Collections","logo":"https://media.daily.dev/image/upload/s--fk_6ycEi--/f_auto,q_auto/v1780996001/logos/collections?_a=BAMAMiWQ0","url":"https://daily.dev/sources/collections"},"commentCount":0,"discussionUrl":"https://daily.dev/posts/creating-foreign-keys-sql-fundamentals-with-postgresql-2vweyexuw","interactionStatistic":[{"@type":"InteractionCounter","interactionType":{"@type":"LikeAction"},"userInteractionCount":2},{"@type":"InteractionCounter","interactionType":{"@type":"CommentAction"},"userInteractionCount":0}],"keywords":"webdev,backend,sql,postgresql","timeRequired":"PT3M"}
{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https://daily.dev"},{"@type":"ListItem","position":2,"name":"Collections","item":"https://daily.dev/sources/collections"},{"@type":"ListItem","position":3,"name":"Creating Foreign Keys | SQL Fundamentals with PostgreSQL"}]}
```

