In this blog, I will show how to use and where to use UNION in SQL. Explain How its work and why we need to use it.

I. SQL means

SQL is a domain-specific language used in programming and designed for managing data held in a relational database management system, or for stream processing in a relational data stream management system

for more blog and topic about SQL , Click to visit HERE.

II. UNION Operator


The SQL UNION operator is used to combine the result sets of 2 or more SELECT statements. It removes duplicate rows between the various SELECT statements. Each SELECT statement within the UNION must have the same number of fields in the result sets with similar data types.

UNION Query

SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;

I have sample simple query here, this is only show how is work, I have table user and user_gender with this column lists .

and first we need to select all Male and second is Female.

  • Male Query
Select * From users A inner Join user_gender B On A.gender = B.id Where B.gender = ‘Male’
  • Female Query
Select * From users A inner Join user_gender B On A.gender = B.id Where B.gender = ‘Female’

NOTE: this is it. this is for example only and you need to jump your thinking out of the box to understand and expound this idea. I am doing this for a reason why I am using simple sample, because I want you to develop your logical and imagination aspect.

I know that the result of this is can be get as simple join query but I use it for other topic. every blog of this site will using simple sample and that your time to expand your logical aspect.

Here we go.

to Union the to query you only need to put Union Operation between to of them.

  Select * From users A inner Join user_gender B On A.gender = B.id Where B.gender = 'Male'
  UNION 
  Select * From users A inner Join user_gender B On A.gender = B.id Where B.gender = 'Female'

Thank you for reading and visiting my site. Please do subscribe to be updated every new posted article here.

Related Topics

❮ PreviousNext ❯

One Reply to “Use UNION Operator in SQL”

  1. I wasn’t sure I could manage writing such a long article in the beginning. Well, your style definitely caught my interest. You always deliver amazing content. Great Article Neil. While I did read it a few weeks ago, I didn’t leave any comments. However , I felt that the article was good enough to deserve a thankyou.

Leave a Reply to Kim Suit Cancel reply

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