Database management is an important concept of handling and organizing data effectively. One powerful Operator in MySQL for combining results from multiple queries is the UNION operator. This operator allows you to merge the results of two or more SELECT statements into a single result set, eliminating duplicate rows by default.
In this article, we'll explore an in-depth understanding of the UNION operator, along with practical examples to show its usage in managing and querying relational databases.
MySQL UNION Operator
The UNION
operator in MySQL is used to combine the results of two or more SELECT
statements into a single result set. Each SELECT
statement within the UNION
must have the same number of columns in the result sets with similar data types. The columns in the result set are named after the columns in the first SELECT
statement.
Syntax:
The syntax for using UNION Operator in MySQL is as follows:
SELECT column1, column2, ...
FROM table1
WHERE condition
UNION
SELECT column1, column2, ...
FROM table2
WHERE condition;
Parameters
column1, column2, ...
: Columns selected from each SELECT
statement must be the same in number and compatible in data type.table1, table2, ...
: The tables or views from which data is selected.condition
: Optional conditions to filter rows in each SELECT
statement.- The
UNION
operator combines the results of the two SELECT
statements and removes duplicates by default.
MySQL UNION Operator Examples
Let’s look at some examples of the UNION Operator in MySQL. Learning the UNION Operator with examples will help in understanding the concept better.
First, let’s create a table:
Demo MySQL Tables
We create the first table "students" in this example.
CREATE TABLE students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
age INT,
grade VARCHAR(10)
);
INSERT INTO students (name, age, grade) VALUES
('Prakash', 15, '10th'),
('Mahesh', 16, '11th'),
('Suresh', 15, '10th');
SELECT * FROM students;
Output:
+----+---------+------+-------+
| id | name | age | grade |
+----+---------+------+-------+
| 1 | Prakash | 15 | 10th |
| 2 | Mahesh | 16 | 11th |
| 3 | Suresh | 15 | 10th |
+----+---------+------+-------+
To create the second table “teachers“, write the following SQL queries:
CREATE TABLE teachers (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
subject VARCHAR(50),
years_of_experience INT
);
INSERT INTO teachers (name, subject, years_of_experience) VALUES
('Gaurav', 'Mathematics', 8),
('Yuvraj', 'Science', 10),
('Shruti', 'History', 12);
SELECT * FROM teachers;
Output:
+----+--------+-------------+---------------------+
| id | name | subject | years_of_experience |
+----+--------+-------------+---------------------+
| 1 | Gaurav | Mathematics | 8 |
| 2 | Yuvraj | Science | 10 |
| 3 | Shruti | History | 12 |
+----+--------+-------------+---------------------+
Example 1: Combing Names from Students and Teachers Table
In this example, we are using the UNION operator to combine the name column from the students table labeled as 'Student' and the name column from the teachers table labeled as 'Teacher'.
SELECT name, 'Student' AS type
FROM students
UNION
SELECT name, 'Teacher' AS type
FROM teachers;
Output:
+---------+---------+
| name | type |
+---------+---------+
| Prakash | Student |
| Mahesh | Student |
| Suresh | Student |
| Gaurav | Teacher |
| Yuvraj | Teacher |
| Shruti | Teacher |
+---------+---------+
Example 2: Combining Names with Conditions
In this example, we are using the UNION operator to combine names from the students and teachers tables based on specific conditions: selecting students with age greater than 15 labeled as 'Student', and selecting teachers with years of experience greater than 8 labeled as 'Teacher'.
SELECT name, 'Student' AS type
FROM students
WHERE age > 15
UNION
SELECT name, 'Teacher' AS type
FROM teachers
WHERE years_of_experience > 8;
Output:
+--------+---------+
| name | type |
+--------+---------+
| Mahesh | Student |
| Yuvraj | Teacher |
| Shruti | Teacher |
+--------+---------+
Conclusion
In conclusion, the MySQL UNION operator is a useful operator for combining the results of multiple SELECT statements into a single cohesive dataset. By understanding its syntax and practical applications, you can efficiently merge and analyze data from various sources within your database. This operator helps in consolidating similar data structures and eases complex queries, enhancing data management and retrieval.
Similar Reads
MySQL UNION ALL Operator
The UNION ALL operator in MySQL combines the result sets of multiple SELECT statements by retaining all duplicate rows for improved performance and efficiency. It is particularly useful when complete data inclusion, including duplicates is required. In this article, We will learn about the MySQL UNI
4 min read
MySQL IN Operator
The MySQL IN operator is used to filter data based on a specified set of values. It is a shorthand for multiple OR conditions which allows us to specify a list of values in a WHERE clause to match records that have any of those values. This makes your SQL queries more concise and easier to read. MyS
3 min read
SQL UNION Operator
The SQL UNION operator is used to combine the result sets of two or more SELECT queries into a single result set. It is a powerful tool in SQL that helps aggregate data from multiple tables, especially when the tables have similar structures. In this guide, we'll explore the SQL UNION operator, how
4 min read
PL/SQL UNION ALL Operator
In PL/SQL, the UNION ALL operator is a powerful tool that allows us to combine the results of two or more SELECT queries into a single result set. Unlike the UNION operator, which eliminates duplicate rows, UNION ALL includes all rows, including duplicates. This makes it faster and more efficient wh
4 min read
SQLite Union All Operator
SQLite is a server-less database engine written in C programming language. It is developed by D. Richard Hipp in the year 2000. The main moto for developing SQLite is escaping complex database engines like MYSQL etc. It has become one of the most popular database engines as we use it in Television,
6 min read
Union Operator in MariaDB
MariaDB is an Open-Source Database system and MariaDB offers similar security features to MySQL, including access control, user authentication, and encryption. UNION operator is a fundamental part of MariaDB, a well-known database systeÂm. The UNION operator mergeÂs results from different SELECT que
5 min read
PL/SQL UNION Operator
In PL/SQL (Procedural Language/Structured Query Language), the UNION operator is one of the most commonly used set operators. It combines the result sets of two or more SELECT statements into a single result set while removing any duplicate rows. In this article, We will learn about PL/SQL UNION Ope
3 min read
SQLite Union Operator
SQLite is a server-less database engine and it is written in c programming language. It is developed by D. Richard Hipp in the year 2000. The main moto for developing SQLite is to escape from using complex database engines like MYSQL etc. It has become one of the most popular database engines as we
5 min read
MySQL EXISTS Operator
The EXISTS operator in MySQL is a powerful boolean operator used to test the existence of any record in a subquery. It returns true if the subquery yields one or more records, enabling efficient data retrieval and manipulation, particularly in large datasets. The operator is often paired with subque
6 min read
MySQL BETWEEN Operator
MySQL consists of various operators for performing efficient data queries, and the BETWEEN operator is a key operator for filtering records within a specific range. By specifying a lower and upper bound, BETWEEN helps you easily retrieve data that falls between two values. This operator simplifies q
4 min read