MySQL UNION usage
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
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:
There are some important rules you have to note:
- Every SELECT statement must have the same number of fields.
- The datatype of the appropriate fields must be the same - or at least convertible - in the various SELECT statements
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:
To join the 3 result into one:
Code:
SELECT brand FROM car
UNIONSELECT brand FROM computer
UNIONSELECT 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:
SELECT brand FROM car
UNION ALL
SELECT brand FROM computer
UNION ALL
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 |