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.
FAQs on MySQL UNION Operator
How does UNION differ from UNION ALL?
UNION removes duplicate rows from the combined result set, while UNION ALL includes all rows, even duplicates.
Do the SELECT statements in a UNION need to have the same number of columns?
Yes, each SELECT statement must have the same number of columns, and the columns must be of compatible data types.
Can you use UNION with ORDER BY?
Yes, you can use ORDER BY to sort the final result set, but it should be applied at the end of the UNION operation, not within individual SELECT statements.
What happens if the columns selected in each SELECT statement have different data types?
The UNION operator requires that the columns in each SELECT statement be of compatible data types. Incompatible types may result in errors or automatic type conversion.
Similar Reads
MySQL UNION Operator
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, eliminat
4 min read
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
Union All Operator in MariaDB
In MariaDB, the Union All operator is a useful tool for combining results from multiple SELECT queries into a single result set. Unlike the Union operator, Union All retains all rows, including duplicates, making it ideal for merging large datasets efficiently. Whether we are consolidating informati
4 min read
MySQL INTERSECT Operator
In MySQL, the INTERSECT operator is used to find common records between two result sets. However, MySQL does not support the INTERSECT operator natively. To achieve similar functionality, you can use alternative methods such as INNER JOINs or subqueries. These techniques allow you to retrieve the in
4 min read
MySQL NOT EQUAL Operator
SQL (Structured Query Language) is a powerful language used for managing and manipulating relational databases. It provides a standardized language for querying the databases which are found to be structured, allowing users to define, manipulate, and control the data retrieval with ease. SQL operate
4 min read
MySQL ANY and ALL Operators
When working with databases, there are often scenarios where we need to compare a value against multiple other values. MySQL offers two powerful operators for this purpose such as ANY and ALL Operators. These operators allow for more complex and flexible data retrieval, enabling comparisons between
5 min read
How to use Relational Operators in MySQL
In the database management area, relational operators are the building blocks for data filtering and querying. MySQL, one of the most popular relational database management systems that are widely used across the world, features a wide range of relational operators that are highly efficient in handl
6 min read
PL/SQL MINUS Operator
The MINUS operator in PL/SQL (and Oracle SQL) is a powerful tool used to compare two datasets and identify differences. It effectively subtracts the result set of the second query from the result set of the first query, returning all rows from the first query that do not appear in the second. In thi
4 min read
SQL IN Operator
The SQL IN operator filters data based on a list of specific values. In general, we can only use one condition in the Where clause, but the IN operator allows us to specify multiple values. In this article, we will learn about the IN operator in SQL by understanding its syntax and examples. IN Opera
4 min read
SQL NOT EQUAL Operator
The SQL NOT EQUAL operator is a comparison operator used to check if two expressions are not equal to each other. It helps filter out records that match certain conditions, making it a valuable tool in SQL queries. In this article, We will explore the SQL NOT EQUAL operator, including its syntax, us
4 min read