Union and union all in PostgreSQL

Union and union all in PostgreSQL returns the combined (row binded) values from two or more table. Union removes the duplicate after combining. Union all does not remove duplicate.

Both UNION and UNION ALL concatenate the result of two different SQLs. They differ in the way they handle duplicates

.

Union in PostgreSQL: performs a DISTINCT on the result set, eliminating any duplicate rows. Union concatenates and also remove duplicates

Union and union all in PostgreSQL 1

Union all in PostgreSQL: Union all concatenates but does not remove duplicates

Union and union all in PostgreSQL 2

 

Let’s discuss with an example. Let’s take two table for example

 

Table 1 : SummerFruits

Union and union all in PostgreSQL 3

 

 

Table 2 : Fruits

Union and union all in PostgreSQL 4

 

Union in PostgreSQL:

 

SELECT * FROM SummerFruitsUNIONSELECT * FROM Fruits

Union concatenates and also remove duplicates so resultant table will be

Union and union all in PostgreSQL 5

 

 

 

Union ALL in PostgreSQL:

 

SELECT * FROM SummerFruitsUNION ALLSELECT * FROM Fruits

Union all concatenates and does not remove duplicates so resultant table will be

Union and union all in PostgreSQL 6

 

 

Author

  • Sridhar Venkatachalam

    With close to 10 years on Experience in data science and machine learning Have extensively worked on programming languages like R, Python (Pandas), SAS, Pyspark.

    View all posts