MySQL UNION usage


Home - Tutorials - MySQL

This article shows you how to use UNION in MySQL to combine more query output into a single result set.

Tutorial info:


Name:MySQL UNION usage
Total steps:1
Category:MySQL
Date:2010-11-10
Level:Beginner
Product:See complete product
Viewed:5648

Bookmark MySQL UNION usage



AddThis Social Bookmark Button

Step 1 - MySQL Union usage


MySQL UNION usage

With UNION you can combine two or more SQL queries into a single result set.

The syntax is the following:

Code:
  1. SELECT field1, field2 ...
  2. UNION [ALL | DISTINCT]
  3. SELECT field1, field2 ...
  4. ...

There are some important rules you have to note:

Let’s see an example if you want to get all brands from your tables like car, computer and clothing. In this case you have 3 query:

Code:
  1. SELECT brand FROM car;
  2. SELECT brand FROM computer;
  3. SELECT brand FROM clothing;
  4.  

To join the 3 result into one:

Code:
  1. SELECT brand FROM car
  2. UNION 
  3. SELECT brand FROM computer
  4. UNION 
  5. SELECT brand FROM clothing;

By default the UNION works as if DISTINCT keyword would be used so no duplication will be present in the result list. If you want to get every record without filtering out duplicated items use the UNION ALL format as here:

Code:
  1. SELECT brand FROM car
  2. UNION ALL
  3. SELECT brand FROM computer
  4. UNION ALL
  5. SELECT brand FROM clothing;






Tags: mysql union, sql union, union, combine result sets, combine

MySQL UNION usage - Table of contents
Step 1 - MySQL Union usage



F1 Site Family
AJAX F1
CSS F1
Database F1
Flash F1
HTML F1
Java F1
JavaScript F1
PhotoShop F1
PHP F1
Scripts F1
Tutorial F1
Windows F1

Family tutorials
PHP Array
PHP Redirect
PHP Session
JavaScript String
JavaScript Timeout
JavaScript Tooltip
AJAX PHP
AJAX File Upload
AJAX Rating System

Total time: 0.0353