The SQL UNION operator combines two or more SELECT statements.
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.
Note: The UNION operator selects only distinct values by default. To allow duplicate values, use UNION ALL.
PS: 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_Norway":
| E_ID | E_Name |
|---|---|
| 01 | Hansen, Ola |
| 02 | Svendson, Tove |
| 03 | Svendson, Stephen |
| 04 | Pettersen, Kari |
"Employees_USA":
| E_ID | E_Name |
|---|---|
| 01 | Turner, Sally |
| 02 | Kent, Clark |
| 03 | Svendson, Stephen |
| 04 | Scott, Stephen |
Now we want to list all the different employees in Norway and USA.
We use the following SELECT statement:
The result-set will look like this:
| E_Name |
|---|
| Hansen, Ola |
| Svendson, Tove |
| Svendson, Stephen |
| Pettersen, Kari |
| Turner, Sally |
| Kent, Clark |
| Scott, Stephen |
Note: This command cannot be used to list all employees in Norway and USA. 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 Norway and USA:
Result
| E_Name |
|---|
| Hansen, Ola |
| Svendson, Tove |
| Svendson, Stephen |
| Pettersen, Kari |
| Turner, Sally |
| Kent, Clark |
| Svendson, Stephen |
| Scott, Stephen |
The perfect solution for professionals who need to balance work, family, and career building.
More than 10 000 certificates already issued!
The HTML Certificate documents your knowledge of HTML.
The CSS Certificate documents your knowledge of advanced CSS.
The JavaScript Certificate documents your knowledge of JavaScript and HTML DOM.
The jQuery Certificate documents your knowledge of jQuery.
The XML Certificate documents your knowledge of XML, XML DOM and XSLT.
The ASP Certificate documents your knowledge of ASP, SQL, and ADO.
The PHP Certificate documents your knowledge of PHP and SQL (MySQL).
| WEB HOSTING |
|---|
| Best Web Hosting |
| PHP MySQL Hosting |
| Best Hosting Coupons |
| UK Reseller Hosting |
| Cloud Hosting |
| Top Web Hosting |
| $7.95/mo SEO Hosting |
| Premium Website Design |
| WEB BUILDING |
|---|
| Download XML Editor |
| FREE Website BUILDER |
| Free Website Templates Free CSS Templates |
| Make Your Own Website |
| W3SCHOOLS EXAMS |
|---|
|
Get Certified in: HTML, CSS, JavaScript, XML, PHP, and ASP |
| W3SCHOOLS BOOKS |
|---|
|
New Books: HTML, CSS JavaScript, and Ajax |
| STATISTICS |
|---|
|
Browser Statistics Browser OS Browser Display |
| SHARE THIS PAGE |
|---|