In what scenarios does using multi-query make sense over individual queries, and is UNION a better alternative?

When you need to retrieve data from multiple tables or conditions in a single query, using a multi-query approach can be more efficient than making individual queries for each condition. This can help reduce the number of round trips to the database and improve performance. However, if the queries have different columns or conditions that cannot be combined into a single query, using UNION to merge the results of multiple queries can be a better alternative.

// Using multi-query approach
$query = "SELECT * FROM table1 WHERE condition1; 
          SELECT * FROM table2 WHERE condition2;";
$result = mysqli_multi_query($connection, $query);

if ($result) {
    do {
        if ($result = mysqli_store_result($connection)) {
            while ($row = mysqli_fetch_assoc($result)) {
                // Process the results
            }
            mysqli_free_result($result);
        }
    } while (mysqli_next_result($connection));
}

// Using UNION approach
$query = "(SELECT column1, column2 FROM table1 WHERE condition1) 
          UNION 
          (SELECT column3, column4 FROM table2 WHERE condition2)";
$result = mysqli_query($connection, $query);

if ($result) {
    while ($row = mysqli_fetch_assoc($result)) {
        // Process the results
    }
    mysqli_free_result($result);
}