Languages
[Edit]
EN

PostgreSQL - Full Outer Join

0 points
Created by:
Wade
562

In this article, we would like to show you how to do FULL OUTER JOIN in PostgreSQL.

Quick solution:

SELECT * FROM "table1"
FULL OUTER JOIN "table2" ON "table2"."column_name" = "table1"."column_name"

Practical example

To show how the FULL OUTER JOIN works, we will use the following tables:

PostgreSQL - Full Outer Join
Tables in the database

Note:

At the end of this article you can find databases preparation SQL queries.

Example 

In this example, we will select all information about users and departments.

Query:

SELECT * 
FROM "users" 
FULL OUTER JOIN "departments" ON "departments"."id" = "users"."department_id"

Output:

PostgreSQL - Full Outer Join
Results - HeidiSQL

Database preparation

create_tables.sql file:

CREATE TABLE "departments" (
	"id" SERIAL,
	"department_name" VARCHAR(50) NOT NULL,
	"location" VARCHAR(50) NULL,
	PRIMARY KEY ("id")
);

CREATE TABLE "users" (
	"id" SERIAL,
	"name" VARCHAR(50) NOT NULL,
	"surname" VARCHAR(50) NOT NULL,
	"department_id" INTEGER,
	PRIMARY KEY ("id"),
	FOREIGN KEY ("department_id") REFERENCES "departments" ("id")
);

insert_data.sql file:

INSERT INTO "departments"
	("id", "department_name", "location")
VALUES
	(1, 'Sales', 'New York'),
	(2, 'Finance', NULL),
	(3, 'HR', 'Atlanta'),
	(4, 'Purchase', 'New Orlean'),
	(5, 'Operations', 'Boston');

INSERT INTO "users"
	( "name", "surname", "department_id")
VALUES
	('John', 'Stewart', 1),
	('Chris', 'Brown', 2),
	('Kate', 'Lewis', 3),
	('Ailisa', 'Gomez', NULL),
	('Gwendolyn', 'James', 2),
	('Simon', 'Collins', 4),
	('Taylor', 'Martin', 2),
	('Andrew', 'Thompson', NULL);
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Cross technology - Full Outer Join

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join