What are the potential pitfalls of using UNION in SQL queries for retrieving specific data sets?

Using UNION in SQL queries can potentially slow down performance as it combines multiple result sets into one, which can be resource-intensive. Additionally, it may return duplicate rows if not handled properly. To avoid these pitfalls, consider using UNION ALL instead of UNION if duplicate rows are acceptable, and ensure that the columns selected in each query have the same data types and order.

$query1 = "SELECT column1, column2 FROM table1";
$query2 = "SELECT column1, column2 FROM table2";

$sql = "$query1 UNION ALL $query2";

$result = mysqli_query($connection, $sql);

if($result){
    while($row = mysqli_fetch_assoc($result)){
        // Process each row
    }
} else {
    echo "Error: " . mysqli_error($connection);
}

mysqli_close($connection);