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
No Content Found.
Interview Questions & Answers
No Content Found.