EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials UNION in PostgreSQL
Secondary Sidebar
PostgreSQL Tutorial
  • Advanced
    • PostgreSQL Schema
    • PostgreSQL ANY
    • Entity Framework PostgreSQL
    • PostgreSQL UPSERT
    • PostgreSQL ON CONFLICT
    • PostgreSQL Port
    • Postgres List Schemas
    • PostgreSQL Update
    • PostgreSQL Drop Schema
    • PostgreSQL VARCHAR
    • PostgreSQL Case Insensitive
    • PostgreSQL Timestamp with Timezone
    • PostgreSQL Array Functions
    • Array in PostgreSQL
    • PostgreSQL DDL
    • PostgreSQL List Users
    • Postgres Default User
    • Postgres add user
    • PostgreSQL User Password
    • PostgreSQL log_statement
    • PostgreSQL String Functions
    • PostgreSQL? String Contains
    • PostgreSQL Compare Strings
    • PostgreSQL Text Search
    • PostgreSQL TEXT
    • PostgreSQL?String Array
    • PostgreSQL where in array
    • PostgreSQL Constraints
    • PostgreSQL UNIQUE Constraint
    • PostgreSQL CHECK 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 LEAD()
    • PostgreSQL Table
    • Postgres Show Tables
    • PostgreSQL?Describe Table
    • PostgreSQL?Lock Table
    • PostgreSQL ALTER TABLE
    • Postgres Rename Table
    • PostgreSQL List Tables
    • PostgreSQL TRUNCATE TABLE
    • PostgreSQL Table Partitioning
    • 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 datediff
    • PostgreSQL Timestamp
    • PostgreSQL CURRENT_TIMESTAMP()
    • PostgreSQL Notify
    • PostgreSQL LENGTH()
    • PostgreSQL blob
    • PostgreSQL Median
    • PostgreSQL kill query
    • PostgreSQL Formatter
    • 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 DELETE JOIN
    • 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 UUID
    • PostgreSQL Merge
    • PostgreSQL Database
    • PostgreSQL?Clone Database
    • PostgreSQL Copy Database
    • PostgreSQL Show Databases
    • 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 Show Tables
    • PostgreSQL cluster
    • PostgreSQL Replication
    • PostgreSQL Logical Replication
    • PostgreSQL? flush privileges
    • PostgreSQL Tablespaces
    • CAST in PostgreSQL
    • PostgreSQL CTE
    • hstore in PostgreSQL
    • PostgreSQL Encryption
    • 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 Incremental Backup
    • PostgreSQL Backup
    • PostgreSQL JSON vs JSONNB
    • PostgreSQL JDBC Driver
    • PostgreSQL Interview Questions
    • PostgreSQL drop foreign key
    • PostgreSQL export database
    • PostgreSQL Export CSV
    • PostgreSQL Performance Tuning
    • PostgreSQL Unnest
    • PostgreSQL show version
    • PostgreSQL Full Text Search
    • PostgreSQL max connections
    • Postgres Switch Database
    • PostgreSQL STRING_AGG()
    • PostgreSQL Date Format
    • PostgreSQL SUM()
    • PostgreSQL FORMAT
    • BETWEEN in PostgreSQL
    • PostgreSQL EXISTS
    • PostgreSQL Synonyms
    • PostgreSQL REGEXP_REPLACE
    • PostgreSQL group by month
    • UNION in PostgreSQL
    • PostgreSQL POSITION()
  • Basic
    • What is PostgreSQL
    • PostgreSQL Features
    • How to Install PostgreSQL
    • PostgreSQL Versions
    • PostgreSQL Architecture
    • PostgreSQL GUI
    • Postgres Command-Line
    • PostgreSQLTrigger Functions
    • PostgreSQL jsonb
    • PostgreSQL Table Schema
    • PostgreSQL group by day
    • Postgres ALTER TABLE
    • Postgres Connect to Database
    • PostgreSQL Numeric
    • PostgreSQL dblink
    • PostgreSQL Variables
    • PostgreSQL Data Types
    • PostgreSQL NOT NULL
    • PostgreSQL Integer
    • PostgreSQL Boolean
    • PostgreSQL BIGINT
    • PostgreSQL NULLIF
    • PostgreSQL Administration
    • PostgreSQL Commands
    • PostgreSQL Superuser
    • PostgreSQL ALL
    • PostgreSQL Operators
    • PostgreSQL IN Operator
    • Postgres like query
    • PostgreSQL encode
    • PostgreSQL Cheat Sheet
  • Control Statement
    • PostgreSQL IF Statement
    • PostgreSQL if else
    • PostgreSQL CASE Statement
    • PostgreSQL LOOP
    • PostgreSQL For Loop
    • PostgreSQL While Loop
  • 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
  • Queries
    • PostgreSQL Queries
    • PostgreSQL INSERT INTO
    • PostgreSQL WHERE Clause
    • PostgreSQL WITH Clause
    • PostgreSQL ORDER BY
    • PostgreSQL? ORDER BY? Random
    • PostgreSQL ORDER BY DESC
    • PostgreSQL GROUP BY
    • PostgreSQL group_concat
    • PostgreSQL HAVING
    • PostgreSQL Recursive Query

UNION in PostgreSQL

UNION in PostgreSQL

Introduction to UNION in PostgreSQL

Union in PostgreSQL is used to combine the result of two or more select queries without returning duplicate values, union is most important in PostgreSQL. To use this function each select statement must have the same number of columns selected and the same no of column expressions but don’t need to have the same length. Union in PostgreSQL will remove duplicate values from the table and give output to the user. We can combine one or more queries in the result set.

Syntax:

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Below is the syntax which is as follows.

All in One Data Science Bundle(360+ Courses, 50+ projects)
Python TutorialMachine LearningAWSArtificial Intelligence
TableauR ProgrammingPowerBIDeep Learning
Price
View Courses
360+ Online Courses | 50+ projects | 1500+ Hours | Verifiable Certificates | Lifetime Access
4.7 (86,171 ratings)

Select Column_name1, Column_name2, …, Column_nameN from table1
UNION
Select Column_name1, Column_name2, …, Column_nameN from table2

Select expression1, expression2, …, expressionN from table1
UNION
Select expression 1, expression 2, …, expressionN from table2

Select * from table1
UNION
Select * from table2

Below is the parameter description of the above syntax which is as follows.

  • Select: Select statement is used to select no of the column from tables.
  • Column1 to ColumnN: Column used in the select statement to fetch result using union in
    PostgreSQL.
  • Expression1 to ExpressionN: Column used in the select statement to fetch result.
  • Table1 and Table2: Table used to retrieve data using Union operator in PostgreSQL.
  • UNION: UNION operator used to combine results of two or more queries.
  • From: Keyword to define table from which we have fetching data.
  • Asterisk (*): Retrieve all columns in a result set from the specified table.

How does UNION Clause work in PostgreSQL?

  •  If we have to combine results using the UNION clause then both the query must have the same row count to retrieve the output.
  • Also in both, the columns need to have compatible data types.
  • Union operator is used to combining results from one or multiple tables.
  • We have used a union clause or operator to combine data from a similar table that was not perfectly normalized. Such tables were found in database warehouse applications.
  • The union operator in PostgreSQL places the rows in the first query after, between, or before to the second used query.
  • We also use order by clause to sort the result as ascending or descending order.
  • Union clause is used to remove or eliminate duplicate records from the table.

Examples to Implement

We have used employee_test1 and employee_test2 tables to describe.

Example #1 – Employee_Test1

Code:

CREATE TABLE Employee_Test1 ( emp_id INT NOT NULL, emp_name character(10) NOT NULL, emp_address character(20) NOT NULL, emp_phone character(14), emp_salary INT NOT NULL, date_of_joining date NOT NULL, PRIMARY KEY (emp_id));
INSERT INTO Employee_Test1 (emp_id, emp_name, emp_address, emp_phone, emp_salary, date_of_joining) VALUES (1, 'ABC', 'Pune', '1234567890', 20000, '01-01-2020');
INSERT INTO Employee_Test1 (emp_id, emp_name, emp_address, emp_phone, emp_salary, date_of_joining) VALUES (2, 'PQR', 'Pune', '1234567890', 20000, '01-01-2020');
INSERT INTO Employee_Test1 (emp_id, emp_name, emp_address, emp_phone, emp_salary, date_of_joining) VALUES (3, 'XYZ', 'Mumbai', '1234567890', 35000, '02-01-2020');
INSERT INTO Employee_Test1 (emp_id, emp_name, emp_address, emp_phone, emp_salary, date_of_joining) VALUES (4, 'BBS', 'Mumbai', '1234567890', 45000, '02-01-2020');
INSERT INTO Employee_Test1 (emp_id, emp_name, emp_address, emp_phone, emp_salary, date_of_joining) VALUES (5, 'RBS', 'Delhi', '1234567890', 50000, '03-01-2020');

Output:

UNION in PostgreSQL | Output 1

Example #2 – Employee_Test2

Code:

CREATE TABLE Employee_Test2 ( emp_id INT NOT NULL, emp_name character(10) NOT NULL, emp_address character(20) NOT NULL, emp_phone character(14), emp_salary INT NOT NULL, date_of_joining date NOT NULL, PRIMARY KEY (emp_id));
INSERT INTO Employee_Test2 (emp_id, emp_name, emp_address, emp_phone, emp_salary, date_of_joining) VALUES (6, 'PQR', 'Pune', '1234567890', 20000, '01-01-2020');
INSERT INTO Employee_Test2 (emp_id, emp_name, emp_address, emp_phone, emp_salary, date_of_joining) VALUES (7, 'XYZ', 'Mumbai', '1234567890', 35000, '02-01-2020');
INSERT INTO Employee_Test2 (emp_id, emp_name, emp_address, emp_phone, emp_salary, date_of_joining) VALUES (8, 'BBS', 'Mumbai', '1234567890', 45000, '02-01-2020');
INSERT INTO Employee_Test2 (emp_id, emp_name, emp_address, emp_phone, emp_salary, date_of_joining) VALUES (9, 'RBS', 'Delhi', '1234567890', 50000, '03-01-2020');
INSERT INTO Employee_Test2 (emp_id, emp_name, emp_address, emp_phone, emp_salary, date_of_joining) VALUES (10, 'ABC', 'Pune', '1234567890', 20000, '01-01-2020');

Output:

UNION in PostgreSQL | Output 2

select * from Employee_Test1;

UNION in PostgreSQL | Employee_Test1

select * from Employee_Test2;

UNION in PostgreSQL | Employee_Test 2

Please find below an example of a UNION operator in PostgreSQL.

Union operator using all columns from both the table.
  • In the below example, we have retrieved data from all the columns. In such a case, all data is combined with employee_test1 and employee_test2 tables.
  • In this scenario, all records will be retrieved from both tables because in some columns data is different.

testing=# select * from Employee_Test1 UNION select * from Employee_Test2;

Figure 2

Union operator using a specific column from both the table.
  • In the below example we have retrieved data from specific columns. In such a case, only distinct records from both the tables are fetched.
  • Duplicate records from both tables are eliminated or removed.
  • In this scenario, only distinct records will be retrieved from both tables because in some columns data is duplicated.

testing=# select emp_name, emp_address from Employee_Test1 UNION select emp_name, emp_address from Employee_Test2;

figure 3

Union clause using ORDER BY clause in PostgreSQL.
  • To sort result combined from both the query at that time we have used order by clause in PostgreSQL.
  • Using order by clause we sort the result data with ascending and descending order.
  • Below example shows union clause using order by clause in PostgreSQL.

testing=# select * from Employee_Test1 UNION select * from Employee_Test2 order by emp_id ASC;
testing=# select * from Employee_Test1 UNION select * from Employee_Test2 order by emp_id DESC;

 figure 4

Rules for Using UNION in PostgreSQL

  • Below are the rules and regulations while using the union clause in PostgreSQL.
  • We need the same column in both tables while using UNION to combine the results of one or more queries.
  • Also need same data type in both the table column list while combining the result.
  • UNION clause or operator is very useful and important in PostgreSQL to combine the result of one or more queries.
  • For combining the result we need to select the same column from both tables.
  • To sort result by ascending and descending order we use order by clause in UNION operator.

Conclusion

UNION clause is very useful and important in PostgreSQL to combine the result of one or more queries.  We have sorted the data in ascending and descending order. We are using order by clause in the UNION operator. We need the same column to combine the result of one or more queries.

Recommended Articles

This is a guide to a UNION in PostgreSQL. Here we discuss the Introduction and working of UNION in PostgreSQL along with different examples. You may also look at the following articles to learn more –

  1. Indexes in PostgreSQL – Introduction
  2. PostgreSQL Cross Join – Working
  3. PostgreSQL Features – Features
  4. PostgreSQL Architecture – Architecture
Popular Course in this category
PostgreSQL Course (2 Courses, 1 Project)
  2 Online Courses |  1 Hands-on Project |  7+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • 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

ISO 10004:2018 & ISO 9001:2015 Certified

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

EDUCBA
Watch our Demo Courses and Videos

Valuation, Hadoop, Excel, Mobile Apps, Web Development & many more

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

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Watch our Demo Courses and Videos

Valuation, Hadoop, Excel, Mobile Apps, Web Development & many more.

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

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

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

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

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

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more