mysql  union  Operator

mysql union operator allows you to combine two or more result-sets from multiple tables into a single result-set.

note : that each select statement within the union must have the same number of columns.the columns must also have similar data types.

mysql union operator syntax

         select  column_name1 , column_name2

             union     [distinct | all]
                                 
             select    column_name1 , column_name2
                                 
             union    [distinct | all]

note : the union operator in MySQL selects only distinct values by default.to allow duplicate values, use the all keyword with union.


below is selection from the "user" table:

useridfirstnamelastnamemobilenocountry
1sandeepkumar9549293245india
2ramkumar9549293212usa
3shyamdhaka2323234545jaipur
4ankitnehra3423567845uae
5radhakumari2323121212jaipur

and selection from the "company" table:

productidcompanynametypecountry
1facebooksocial websiteusa
2gmailmailing serviceuae
3googlesearch engineindia

mysql union operator example

              select    country    from   user

               union
                    
               select    country    from   company;

mysql union   all example

The following mySQL statement uses UNION ALL to select all (duplicate values also) country from the "user" and "company" tables:

              select    country    from   user

               union    all
                    
               select    country    from   company;