UNION
UNION

UNION

Status
Done
image

INTRODUCTION

The UNION operator in MySQL is a powerful tool for combining the results of multiple SELECT statements into a single result set. It's particularly useful when you want to retrieve data from different tables or different parts of the same table that share a similar structure.

Key Points:

  • Combines Results: UNION merges the output from two or more SELECT queries.
  • Removes Duplicates (Default): By default, UNION eliminates duplicate rows from the combined result set. This ensures you only get unique data points.
  • Matching Columns: The SELECT statements used with UNION must have the same number of columns in the same order, and the data types of corresponding columns must be compatible.
  • Column Names: The column names in the final result set are inherited from the first SELECT statement in the UNION chain.
  • The key difference between UNION ALL and UNION is that UNION ALL retains duplicate rows in its output, while UNION automatically removes them.

Syntax:

SELECT 
  column1, 
  column2, 
FROM 
    table_name 
UNION 
     SELECT 
          column1, 
          column2, 
       FROM 
          table_name 
  • SELECT ...: This represents the individual SELECT statements that retrieve data.
  • FROM table1, table2, table3: These are the tables from which data is fetched.
  • UNION: This keyword combines the results from the preceding SELECT statements, removing duplicates (default behavior).

MySQL UNION operator

MySQL UNION vs JOIN

OUTPUT OF UNION AND JOIN

MySQL UNION and column alias examples

MySQL UNION and ORDER BY