EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login

PostgreSQL NATURAL JOIN

Home » Data Science » Data Science Tutorials » PostgreSQL Tutorial » PostgreSQL NATURAL JOIN

PostgreSQL NATURAL JOIN

Introduction to PostgreSQL NATURAL JOIN

In simple terms, the join is where two or more tables are joined, and as a result, we will get the new set of rows for combined columns requested for each of the tables. A joint operation creates an implicit join clause on the common columns for the tables that we have defined in the join clause. A Join operation actually creates a temporary table for a set of rows to work on two or more tables. The tables defined in the join clause should have at least one common column, and the common columns should have a relation between them.

Syntax

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

SELECT *
FROM table_name_1
NATURAL [INNER, LEFT, RIGHT] JOIN table_name_2;

Explanation: The table_name_1 and table_name_2 are the two tables on which we perform a joining to get the combined result for the columns having the same name in both tables. The table_name_1 is generally read as a left (first) table, and The table_name_2 is generally read right (second) table.

Joins in PostgreSQL NATURAL JOIN

NATURAL JOIN operation can be any of the following:

  • Inner join
  • Left join
  • Right join

The PostgreSQL uses the INNER JOIN by default if we do not define a name of join explicitly as INNER JOIN, LEFT JOIN, or RIGHT JOIN.

How NATURAL JOIN works in PostgreSQL?

If we create a SQL statement having an asterisk (*) instead of column names in the SELECT clause with the NATURAL JOIN operation, then the columns will be considered in the following order for an asterisk (*) :

  • All the common columns from the left (first) table and right (second) table.
  • Every column in the left (first) table which is not common with the right (second) table columns.
  • Every column in the second (right) table which is not common with the left (first) table columns.

In PostgreSQL, the NATURAL JOIN is an INNER JOIN where we combine all columns with the same name in both tables.

Examples to Implement NATURAL JOIN in PostgreSQL

Let’s create two tables named’ transaction’ and ‘invoices’ to understand the PostgreSQL NATURAL JOIN examples.

Example #1

The following CREATE TABLE statements will create the transaction and invoices table. 

Code:

CREATE TABLE transaction (
transaction_id serial PRIMARY KEY,
transaction_data VARCHAR (256) NOT NULL
);
CREATE TABLE invoices (
invoice_id serial PRIMARY KEY,
transaction_id INT NOT NULL,
invoice_data VARCHAR (256) NOT NULL,
FOREIGN KEY (transaction_id) REFERENCES transaction (transaction_id)
);

  • The transaction_id is the primary key of the transaction table, which is referred to as a foreign key for the invoices table. So while performing natural join operation, we will use the transaction_id column as it is the common column for both tables. The transaction may have zero or more invoices, and the invoice will belong to one and only one transaction.

Now insert some data into the transaction and invoices tables using INSERT statement as follows:

Code:

INSERT INTO transaction (transaction_data)
VALUES
('Purchase of Mobile'),
('Purchase of PC'),
('Purchase of Headphone');
INSERT INTO invoices (invoice_data, transaction_id)
VALUES
('Purchase of Mobile', 1),
('Purchase of Mobile', 1),
('Purchase of PC', 2),
('Purchase of PC', 2),
('Purchase of Headphone', 3),
('Purchase of Headphone', 3);

  • Illustrate the content of the transaction table using the following statement and snapshot.

Code:

select * from transaction;

Output:

PostgreSQL NATURAL JOIN - 1

  • Illustrate the content of the invoices table using the following statement and snapshot.

Code:

select * from invoices;

Output:

PostgreSQL NATURAL JOIN - 2

  • Join the invoices table with the transaction table using the NATURAL JOIN clause:

Code:

SELECT
*
FROM
invoices
NATURAL JOIN transaction;
Illustrate the result of the above statement using the following snapshot.

Output:

PostgreSQL NATURAL JOIN - 3

  • The above statement with the NATURAL JOIN clause similar to the statement with the INNER JOIN clause as follows:

Code:

SELECT
*
FROM
invoices
INNER JOIN transaction USING (transaction_id);

  • Illustrate the result of the above statement using the following snapshot.

Output:

INNER JOIN clause

  • It is not required to define the join clause as the NATURAL JOIN uses an implicit join clause based on the common column.
  • But if possible, we should avoid using the NATURAL JOIN because if we are having multiple common columns, it gives us an unexpected result.

Example #2

Consider the following example for two tables named COUNTRIES and CITIES. The following CREATE TABLE statements will create the COUNTRIES and CITIES table.

Code:

CREATE table COUNTRIES
(
country_id serial PRIMARY KEY,
country_name VARCHAR (256) NOT null,
last_updated DATE NULL
);
CREATE table  CITIES
(
CITY_id serial PRIMARY KEY,
country_id INT NOT NULL,
city_name VARCHAR (256) NOT NULL,
last_updated DATE null,
FOREIGN KEY (country_id) REFERENCES COUNTRIES (country_id)
);

  • Now insert some data into the COUNTRIES and CITIES tables using INSERT statement as follows:

Code:

INSERT INTO COUNTRIES (country_name,last_updated)
VALUES
('India','06-01-2020'),
('US','07-01-2020'),
('CHINA','08-01-2020');
INSERT INTO CITIES (country_id, city_name,last_updated)
VALUES
(1,'Pune','06-02-2020'),
(1,'Mumbai', '07-02-2020'),
(2,'New York', '08-02-2020'),
(2,'Los Angeles', '09-02-2020'),
(3,'Beijing ', '10-02-2020'),
(3,'Shanghai', '11-02-2020');

Code:

select * from COUNTRIES;

  • Illustrate the content of the COUNTRIES table using the following statement and snapshot.

Output:

COUNTRIES table

Code:

select * from CITIES;

  • Illustrate the content of the CITIES table using the following statement and snapshot.

Output:

CITIES table

  • Here, Both COUNTRIES and CITIES tables have two common columns named country_id and last_updated, so to join these tables, we can use the NATURAL JOIN as follows:

Code:

SELECT
*
FROM
COUNTRIES
NATURAL JOIN CITIES;

  • In the above statement, the COUNTRIES and CITIES tables having common columns country_id and last_updated. Even if the last_updated column is common, it should not be used in the joint operation.
  • However, the last_updated column is getting used in the NATURAL JOIN clause, ending in an unexpected result.

Conclusion

We hope from the above article you have learned how the PostgreSQL NATURAL JOIN works. Also, we have added some examples to demonstrate to you how to use the NATURAL JOIN to query data from two or more tables.

Recommended Articles

This is a guide to PostgreSQL NATURAL JOIN. Here we discuss Syntax to NATURAL JOIN, how does it work, with examples to implement join. You can also go through our other related articles to learn more –

  1. Joins in PostgreSQL
  2. PostgreSQL Data Types
  3. PostgreSQL WHERE Clause
  4. PostgreSQL GROUP BY

All in One Data Science Bundle (360+ Courses, 50+ projects)

360+ Online Courses

50+ projects

1500+ Hours

Verifiable Certificates

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
PostgreSQL Tutorial
  • Joins
    • Joins in PostgreSQL
    • PostgreSQL Inner Join
    • PostgreSQL Outer Join
    • LEFT OUTER JOIN in PostgreSQL
    • PostgreSQL FULL OUTER JOIN
    • PostgreSQL LEFT JOIN
    • PostgreSQL Full Join
    • PostgreSQL Cross Join
    • PostgreSQL NATURAL JOIN
    • PostgreSQL UPDATE JOIN
  • Basic
    • What is PostgreSQL
    • PostgreSQL Features
    • How to Install PostgreSQL
    • PostgreSQL Versions
    • PostgreSQL Architecture
    • PostgreSQL GUI
    • PostgreSQL Variables
    • PostgreSQL Data Types
    • PostgreSQL NOT NULL
    • PostgreSQL Integer
    • PostgreSQL Boolean
    • PostgreSQL NULLIF
    • PostgreSQL Administration
    • PostgreSQL Commands
    • PostgreSQL Operators
    • PostgreSQL IN Operator
  • Control Statement
    • PostgreSQL IF Statement
    • PostgreSQL if else
    • PostgreSQL CASE Statement
    • PostgreSQL LOOP
    • PostgreSQL For Loop
    • PostgreSQL While Loop
  • Queries
    • PostgreSQL Queries
    • PostgreSQL WHERE Clause
    • PostgreSQL WITH Clause
    • PostgreSQL ORDER BY
    • PostgreSQL ORDER BY Random
    • PostgreSQL GROUP BY
    • PostgreSQL group_concat
    • PostgreSQL HAVING
    • PostgreSQL Recursive Query
  • Advanced
    • PostgreSQL Schema
    • Postgres List Schemas
    • PostgreSQL VARCHAR
    • Array in PostgreSQL
    • PostgreSQL DDL
    • PostgreSQL List Users
    • Postgres Default User
    • Postgres add user
    • PostgreSQL log_statement
    • PostgreSQL String Functions
    • PostgreSQL Compare Strings
    • PostgreSQL Text Search
    • PostgreSQL TEXT
    • PostgreSQL String Array
    • PostgreSQL Constraints
    • PostgreSQL UNIQUE Constraint
    • PostgreSQL INTERSECT
    • PostgreSQL Like
    • Cursors in PostgreSQL
    • PostgreSQL UNION ALL
    • Indexes in PostgreSQL
    • PostgreSQL Index Types
    • PostgreSQL REINDEX
    • PostgreSQL UNIQUE Index
    • PostgreSQL Clustered Index
    • PostgreSQL DROP INDEX
    • PostgreSQL DISTINCT
    • PostgreSQL FETCH
    • PostgreSQL RAISE EXCEPTION
    • PostgreSQL Auto Increment
    • Sequence in PostgreSQL
    • Wildcards in PostgreSQL
    • PostgreSQL Subquery
    • PostgreSQL Alias
    • PostgreSQL LIMIT
    • PostgreSQL Limit Offset
    • PostgreSQL LAG()
    • PostgreSQL Table
    • Postgres Show Tables
    • PostgreSQL Describe Table
    • PostgreSQL Lock Table
    • PostgreSQL ALTER TABLE
    • Postgres Rename Table
    • Postgres DROP Table
    • PostgreSQL Functions
    • PostgreSQL Math Functions
    • PostgreSQL Window Functions
    • Aggregate Functions in PostgreSQL
    • PostgreSQL Primary Key
    • Foreign Key in PostgreSQL
    • PostgreSQL Procedures
    • PostgreSQL Stored Procedures
    • PostgreSQL Views
    • PostgreSQL Materialized Views
    • Postgres Create View
    • PostgreSQL Triggers
    • PostgreSQL DROP TRIGGER
    • PostgreSQL Date Functions
    • PostgreSQL TO_DATE()
    • PostgreSQL Timestamp
    • PostgreSQL CURRENT_TIMESTAMP()
    • PostgreSQL Notify
    • PostgreSQL RANK()
    • PostgreSQL Select
    • PostgreSQL Average
    • PostgreSQL DATE_PART()
    • PostgreSQL EXECUTE
    • PostgreSQL COALESCE
    • PostgreSQL EXTRACT()
    • PostgreSQL Sort
    • PostgreSQL TO_CHAR
    • PostgreSQL Interval
    • PostgreSQL Number Types
    • PostgreSQL ROW_NUMBER
    • Alter Column in PostgreSQL
    • PostgreSQL Identity Column
    • PostgreSQL SPLIT_PART()
    • PostgreSQL CONCAT()
    • PostgreSQL replace
    • PostgreSQL TRIM()
    • PostgreSQL MAX
    • PostgreSQL DELETE
    • PostgreSQL Float
    • PostgreSQL OID
    • PostgreSQL log
    • PostgreSQL REGEXP_MATCHES()
    • PostgreSQL MD5 
    • PostgreSQL NOW()
    • PostgreSQL RANDOM
    • PostgreSQL round
    • PostgreSQL Trunc()
    • PostgreSQL TIME
    • PostgreSQL IS NULL
    • PostgreSQL CURRENT_TIME
    • PostgreSQL MOD()
    • Postgresql Count
    • PostgreSQL Datetime
    • PostgreSQL MIN()
    • PostgreSQL age()
    • PostgreSQL enum
    • PostgreSQL OR
    • PostgreSQL Wal
    • PostgreSQL NOT IN
    • PostgreSQL SET
    • PostgreSQL Current Date
    • PostgreSQL Compare Date
    • PostgreSQL SERIAL
    • PostgreSQL Database
    • PostgreSQL Clone Database
    • PostgreSQL Copy Database
    • PostgreSQL Restore Database
    • PostgreSQL DROP DATABASE
    • PostgreSQL ALTER DATABASE
    • Postgres DROP Database
    • Postgres Dump Database
    • PostgreSQL OFFSET
    • PostgreSQL GRANT
    • PostgreSQL COMMIT
    • PostgreSQL ROLLUP
    • PostgreSQL JSON
    • EXPLAIN ANALYZE in PostgreSQL
    • PostgreSQL Temporary Table
    • PostgreSQL cluster
    • PostgreSQL Replication
    • PostgreSQL Logical Replication
    • PostgreSQL flush privileges
    • PostgreSQL Tablespaces
    • CAST in PostgreSQL
    • PostgreSQL CTE
    • hstore in PostgreSQL
    • PostgreSQL DECODE()
    • PostgreSQL Vacuum
    • PostgreSQL EXCLUDE
    • Postgres Change Password
    • Postgres Delete Cascade
    • PostgreSQL EXCEPT
    • PostgreSQL Roles
    • PostgreSQL Link
    • PostgreSQL Partition
    • PostgreSQL column does not exist
    • PostgreSQL Log Queries
    • PostgreSQL escape single quote
    • PostgreSQL Query Optimization
    • PostgreSQL Character Varying
    • PostgreSQL Transaction
    • PostgreSQL Extensions
    • PostgreSQL Import CSV
    • PostgreSQL Client
    • PostgreSQL caching
    • PostgreSQL JDBC Driver
    • PostgreSQL Interview Questions
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - All in One Data Science Bundle (360+ Courses, 50+ projects) Learn More