MySQL UNION

The UNION operator is used to combine the results of two or more SELECT statements. Each SELECT statement within the UNION must have the same number of columns in the result set, with similar data types.

Examples with Tamil Kings

1. Combining Two SELECT Statements

SELECT king_name FROM tamil_kings_auto_increment
UNION
SELECT king_name FROM tamil_kings_other_kingdoms;

Code Explanation: This query combines the king_name columns from two different tables and returns unique values.

2. Using UNION ALL to Include Duplicates

SELECT king_name FROM tamil_kings_auto_increment
UNION ALL
SELECT king_name FROM tamil_kings_other_kingdoms;

Code Explanation: This query combines the king_name columns from two different tables and includes duplicates.

Best Practices

  • Use UNION to merge result sets and remove duplicates automatically.
  • Use UNION ALL when you need to keep all duplicates in the result set.

Key Takeaways

  • The UNION operator combines result sets and removes duplicates.
  • UNION ALL keeps all duplicates in the combined result set.