MySQL UNION

UNION puts the results of two or more SELECT queries one below the other.

  • Every query must have the same number of columns.
  • The columns must have compatible data types, in the same order.
  • The column names of the first query are used in the result.
SELECT city AS name FROM students
UNION
SELECT course_name FROM courses;
Result
name
Delhi
Mumbai
Pune
Jaipur
Python
Java
Web Design
C Programming

UNION removes duplicate rows. Delhi and Mumbai appear twice in the students table, but only once here.


UNION ALL

UNION ALL keeps the duplicates, and it is faster.

SELECT city FROM students
UNION ALL
SELECT course_name FROM courses;

This returns 10 rows: 6 cities (with the repeated Delhi and Mumbai) and 4 courses.


A practical example

SELECT name, 'Top' AS level FROM students WHERE marks >= 85
UNION
SELECT name, 'Low' AS level FROM students WHERE marks < 60;
Result
name level
Robin Top
Maria Top
Asha Top
Neha Low

Note: Put ORDER BY only once, at the very end of the last query. It sorts the whole combined result.

Summary

  • UNION combines results and removes duplicates, UNION ALL keeps them.
  • All queries need the same number of columns.
  • Next: Indexes.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
Write a query to show the student name who has the second highest marks
Write a query to show the names of students with their course names
Write a query to count the students of each course, including empty courses
Write a query to find the students who scored above the average marks
Interview Questions & Answers
What is the difference between INNER JOIN and LEFT JOIN?
What is the difference between UNION and UNION ALL?
What are the types of JOINs in MySQL?
How to find the second highest marks in MySQL?
What is a subquery in MySQL?