How can the use of NOT IN() be optimized in the context of the provided PHP database query example?

Using NOT IN() in a database query can be optimized by ensuring that the list of values provided is not too large, as it can lead to performance issues. One way to optimize this is to use a subquery to fetch the values instead of hardcoding them in the query. This can help improve the query's performance by reducing the number of comparisons needed.

// Optimized query using a subquery for NOT IN()
$excludedIdsQuery = "SELECT id FROM excluded_table";
$sql = "SELECT * FROM main_table WHERE id NOT IN ($excludedIdsQuery)";

// Execute the query and fetch results
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        // Process fetched data
    }
} else {
    echo "No results found";
}