Leakbali
w3 Tutorial, Web Tutorial
Switch to English Bahasa Indonesia 
Register   Login

MySQL - Union


The UNION operator is used to combine the result-set of two or more SELECT statements. Notice that each SELECT statement within the UNION must have the same number of columns. The columns must also have similar data types. Also, the columns in each SELECT statement must be in the same order.

MySQL UNION Syntax

SELECT column_name(s) FROM table_name1
UNION
SELECT column_name(s) FROM table_name2
Note: The UNION operator selects only distinct values by default. To allow duplicate values, use UNION ALL.

MySQL UNION ALL Syntax

SELECT column_name(s) FROM table_name1
UNION ALL
SELECT column_name(s) FROM table_name2
The column names in the result-set of a UNION are always equal to the column names in the first SELECT statement in the UNION.
Look at the following tables:
"Employees_Bali":
E_IDE_Name
01Putu Sanjaya
02Made Sanjaya
03Haru Sanjaya
04Ketut Sanjaya
"Employees_Lombok":
E_IDE_Name
01Lalu Selamet
02Mamiq Djumenah
03Haru Sanjaya
04Amaq Sadikin
Now we want to list all the different employees in Bali and Lombok.

We use the following SELECT statement:
SELECT E_Name FROM Employees_Norway
UNION
SELECT E_Name FROM Employees_USA
The result-set will look like this:
E_Name
Putu Sanjaya
Made Sanjaya
Haru Sanjaya
Ketut Sanjaya
Lalu Selamet
Mamiq Djumenah
Amaq Sadikin
Note: This command cannot be used to list all employees in Bali and Lombok. In the example above we have two employees with equal names, and only one of them will be listed. The UNION command selects only distinct values.
Now we want to list all employees in Bali and Lombok:
SELECT E_Name FROM Employees_Norway
UNION ALL
SELECT E_Name FROM Employees_USA
Result
E_Name
Putu Sanjaya
Made Sanjaya
Haru Sanjaya
Ketut Sanjaya
Lalu Selamet
Mamiq Djumenah
Haru Sanjaya
Amaq Sadikin

References

About Us

Home
About Us
Contact Us
Sitemap

Tools

Google PageRank
Alexa Rank
Keywords Density

Accounts

Register Account
Login
Valid XHTML 1.0 TransitionalValid CSS!
Web Directory


2006 - 2012 © Leakbali.com - Free Web Tutorial, Free Web Articles, Web Sharing, Source Codes, Web References