Gice

Technology and General Blog

This tutorial will display you how to use PostgreSQL Union and Union All queries to merge final results from choose statements.

How PostgreSQL Union Query Performs

The PostgreSQL question is quite uncomplicated. It functions by combining two or a lot more Pick out info end result to build a solitary larger sized established.

For illustration, if we consider just one consequence of a find statement as X and the consequence of an additional pick out statement as Y, the ensuing UNION of these two statements is the complete of equally Select X and Y with out any duplicates.

Primary Usage

The basic syntax for the UNION query in PostgreSQL is:

Whilst you will generally be choosing particular columns, you can pass other legitimate PostgreSQL expressions to the choose statements.

PostgreSQL Union Query Case in point

Permit us illustrate how to use the UNION query utilizing a basic example.

Get started by developing a sample database and populate it with sample details as revealed in the queries below:

Drop Databases IF EXISTS union_db
Develop Databases union_db
Fall Table IF EXISTS best_databases
Develop Desk top_database(
   id serial,
   db_title VARCHAR NOT NULL
)
Drop Table IF EXISTS all_db
Generate Desk all_db(
   id SERIAL,
   db_identify VARCHAR
)
INSERT INTO best_databases(db_name) VALUES (‘MySQL’), (‘PostgreSQL’), (‘Microsoft SQL Server’), (‘SQLite’), (‘MongoDB’)
INSERT INTO all_db(dB_title) VALUES (‘MySQL’), (‘Elasticsearch’), (‘SQLite’), (‘DynamoDB’), (‘Redis’)

Using the earlier mentioned sample databases and tables, we can perform a UNION as:

The over query should return a solitary set with the values blended as shown under:

To run a UNION query successfully, the specified variety and get of columns in the find statements ought to be identical, and the facts types will have to be compatible.

PostgreSQL Union All

A question very similar to the UNION assertion is the UNION ALL. This question performs the same way the UNION does but does not eliminate duplicate values from the specified established.

We can illustrate this performance by employing the exact query above.

In this case, we ought to return the merged values which include the duplicates as revealed underneath:

Summary

Both equally UNION and UNION ALL have their distinct use conditions. They are practical to developers due to the fact they make it less complicated to combination facts into different sets.

Leave a Reply

Your email address will not be published. Required fields are marked *