Your NOT EXISTS meta_query Isn’t a NULL Bug: Reading the SQL WordPress Actually Generates

The report is always the same shape. A WP_Query with a meta_query using 'compare' => 'NOT EXISTS' returns a post that, in the editor or in a quick get_post_meta() call, plainly has the key. The first instinct is to blame MySQL NULL semantics: NULL = NULL is NULL, NULL <> NULL is NULL, so surely the comparison is falling through and matching rows it shouldn’t.

That diagnosis is wrong, and it sends people down a rabbit hole of COALESCE() patches and posts_where filters that don’t address the actual query. Core does not compare meta_value to anything for a NOT EXISTS clause. It builds a LEFT JOIN and tests the joined row’s ID column with IS NULL — the one NULL test MySQL handles correctly. If a post with the key is coming back, the cause is almost always in how the clause was assembled, not in how MySQL treats NULL.

This is a trace of what core actually emits, the three ways the query shape drifts from what you intended, and a diagnostic recipe that starts with the generated SQL instead of the query args.

What core actually generates for NOT EXISTS

WP_Meta_Query is the class that turns a meta_query array into JOIN and WHERE fragments attached to the primary query. The WordPress developer reference describes it as a helper that filters results “by generating JOIN and WHERE subclauses to be attached to the primary SQL query string” (WP_Meta_Query reference).

For a first-order clause with 'compare' => 'NOT EXISTS', WP_Meta_Query::get_sql_for_clause() takes a specific branch. The source, as published in the developer reference, reads:

// JOIN clauses for NOT EXISTS have their own syntax.
if ( 'NOT EXISTS' === $meta_compare ) {
    $join .= " LEFT JOIN $this->meta_table";
    $join .= $i ? " AS $alias" : '';
    // ... ON ( primary.id = alias.meta_id AND alias.meta_key = %s )
}

And the matching WHERE fragment:

if ( 'NOT EXISTS' === $meta_compare ) {
    $sql_chunks['where'][] = $alias . '.' . $this->meta_id_column . ' IS NULL';
}

Both quotes are from the get_sql_for_clause() reference page. The important detail: the test is on meta_id, not meta_value. meta_id is the primary key of wp_postmeta and is never NULL for a row that exists. So the IS NULL test is true only when the LEFT JOIN found no matching row — which is exactly the semantics you asked for.

This is also why the MySQL NULL documentation is a red herring here. MySQL’s manual is correct that “you cannot use arithmetic comparison operators such as =, <, or <> to test for NULL” (MySQL 8.0 Reference Manual, 5.3.4.6). But core isn’t doing that. It’s using IS NULL, which the same manual documents as the correct operator. The NULL semantics are being handled correctly; the bug is elsewhere.

The LEFT JOIN promotion rule

There is a second piece of core behavior that matters when a meta_query has more than one clause. WP_Meta_Query::get_sql() contains this block:

/*
 * If any JOINs are LEFT JOINs (as in the case of NOT EXISTS), then all JOINs should
 * be LEFT. Otherwise posts with no metadata will be excluded from results.
 */
if ( str_contains( $sql['join'], 'LEFT JOIN' ) ) {
    $sql['join'] = str_replace( 'INNER JOIN', 'LEFT JOIN', $sql['join'] );
}

Source: WP_Meta_Query::get_sql() reference. The comment is the design intent: if one clause needs a LEFT JOIN to preserve posts with no meta, every other clause in the same query is promoted to LEFT JOIN too, so the whole query doesn’t silently drop those posts.

This is where the query shape can drift from what you expected. A second clause that you wrote as an EXISTS or a value comparison is now a LEFT JOIN with a WHERE condition on the joined alias. Whether that condition still filters as you intended depends on how the WHERE fragment is written — and on whether the second clause’s WHERE is parenthesized correctly against the first clause’s IS NULL test.

If you have a meta_query with a NOT EXISTS clause and a second clause, and the result set includes posts that have the first key, the second clause is the first place to look. Not MySQL NULL handling.

Failure mode 1: a second clause changes the join shape

Consider a query that asks for posts without a _editorial_reviewed key, but only among posts that have a _editorial_status key:

$q = new WP_Query( array(
    'post_type'      => 'post',
    'posts_per_page' => 20,
    'meta_query'     => array(
        'relation' => 'AND',
        array(
            'key'     => '_editorial_reviewed',
            'compare' => 'NOT EXISTS',
        ),
        array(
            'key'     => '_editorial_status',
            'value'   => 'draft',
            'compare' => '=',
        ),
    ),
) );

Because the first clause produces a LEFT JOIN, the second clause’s INNER JOIN is rewritten to LEFT JOIN. The second clause’s WHERE fragment is still alias.meta_value = 'draft', but now it’s evaluated against a LEFT JOINed row that may be NULL. A post with no _editorial_status row at all will have alias.meta_value as NULL, and NULL = 'draft' evaluates to NULL, which is not true — so the post is excluded. That part is fine.

The problem is the opposite case: a post that has _editorial_status = 'draft' but also has _editorial_reviewed. The first clause’s LEFT JOIN matches the _editorial_reviewed row, so alias.meta_id is not NULL, and the IS NULL test fails. The post is excluded. That’s correct behavior for the query as written.

Where it goes wrong is when the second clause is itself a NOT EXISTS or a negative comparison, and the two clauses end up sharing a table alias through find_compatible_table_alias(). The alias reuse is an optimization, but it means the WHERE fragments from both clauses are evaluated against the same joined row. If the first clause’s IS NULL test and the second clause’s condition are not parenthesized as a unit, the boolean logic can produce a row that satisfies one clause’s intent but not the other’s.

The fix is not to patch the SQL. It’s to read it. Dump the generated fragments and see what core actually built.

Failure mode 2: the value is silently ignored

This one is documented in the source and still surprises people. In get_sql_for_clause(), the meta_value switch has this case:

// 'value' is ignored for NOT EXISTS.
case 'NOT EXISTS':
    $where = '';
    break;

Source: get_sql_for_clause() reference. If you write:

array(
    'key'     => '_editorial_reviewed',
    'value'   => 'yes',
    'compare' => 'NOT EXISTS',
)

the 'value' => 'yes' is discarded. The clause means “no row with this key exists,” not “no row with this key and this value exists.” If you wanted the latter, you need a different construction — typically a NOT IN subquery against the post IDs that do have the key/value pair, or a second query that fetches those IDs and passes them to post__not_in.

This is not a NULL bug. It’s a documented behavior of the operator. But it produces exactly the symptom people describe: a post that has the key comes back, because the query never tested the value.

Failure mode 3: the key string doesn’t match

The third failure mode is the least interesting and the most common. The post “has the key” according to the editor or a get_post_meta() call, but the key string the query tests is not byte-identical to the key string stored in wp_postmeta.

Two things make this easy to miss. First, get_post_meta() is documented as case sensitive due to WordPress caching, even when the database collation is case insensitive:

Please note that if a db collation is case insensitive (has with suffix _ci) then update_post_meta and delete_post_meta and get_posts() will update/delete/query the meta records with keys that are upper or lower case. However get_post_meta will apparently be case sensitive due to WordPress caching.

Source: get_post_meta() reference. So a query with 'key' => '_Editorial_Reviewed' may match a stored _editorial_reviewed row in the database (collation-dependent), while a get_post_meta() call with the same mixed-case key returns nothing from cache. The two checks disagree, and the disagreement looks like a query bug.

Second, whitespace and near-duplicate keys are real. A key stored as _editorial_reviewed (trailing space) or _editorial_reviewed_v2 will not match a query for _editorial_reviewed. The admin UI may render them identically if the field label is the same.

The fix is to stop trusting get_post_meta() as the source of truth for “does this key exist” and query wp_postmeta directly. See the diagnostic recipe below.

Diagnostic recipe: dump the SQL first

Before changing query args, before adding a posts_where filter, before suspecting core, get the generated SQL. WP_Meta_Query::get_sql() applies a filter, get_meta_sql, to the generated fragments, and that filter is the cleanest hook for inspection:

add_filter( 'get_meta_sql', function( $sql, $queries, $type, $primary_table, $primary_id_column, $context ) {
    if ( ! is_admin() && isset( $_GET['debug_meta_sql'] ) ) {
        error_log( 'JOIN: ' . $sql['join'] );
        error_log( 'WHERE: ' . $sql['where'] );
        error_log( 'QUERIES: ' . print_r( $queries, true ) );
    }
    return $sql;
}, 10, 6 );

The filter signature is documented on the get_sql() reference page. The $_GET guard keeps the logging scoped to a single request; remove it or replace it with a constant check for production debugging.

Read the output in this order:

  1. Count the LEFT JOINs. If there is more than one, the promotion rule fired. That’s expected when a NOT EXISTS clause is present, but it means every other clause’s WHERE fragment is now evaluated against a possibly-NULL joined row.
  2. Check the alias on each WHERE fragment. If two clauses share an alias, they are being evaluated against the same joined row. That’s the alias-reuse optimization, and it’s where boolean logic can drift.
  3. Look for IS NULL on a meta_id column. That’s the NOT EXISTS test. If it’s present and the alias matches the LEFT JOIN for the key you care about, the clause is built correctly.
  4. Look for a meta_value condition on the same alias. If the NOT EXISTS clause also has a meta_value condition, the value was not ignored — which means the clause is not actually a NOT EXISTS clause, or a second clause is contributing that condition.

If the SQL looks correct and the post still comes back, the problem is in the data, not the query. Move to the next step.

Verify the meta rows directly

Take the post ID that shouldn’t be in the result set and query wp_postmeta for every row with a key that looks like the one you tested. Use a LIKE with wildcards on both sides to catch whitespace and near-duplicates:

SELECT meta_id, post_id, CONCAT('[', meta_key, ']') AS key_with_brackets, meta_value
FROM wp_postmeta
WHERE post_id = 12345
  AND meta_key LIKE '%editorial_reviewed%';

The CONCAT with brackets makes leading and trailing whitespace visible. If the key is stored as _editorial_reviewed , the brackets will show it. If the key is stored as _Editorial_Reviewed, the case will show it.

If the row exists with the exact key the query tested, and the generated SQL shows a correct LEFT JOIN ... IS NULL on that key, then the post should not be in the result set. At that point the query is not the problem — something else is modifying the results. Check for a posts_results or the_posts filter, a caching layer returning a stale result set, or a pre_get_posts hook that is altering the query after your args are set.

If the row exists with a different key string, the query is correct and the data is wrong. Fix the data, not the query.

WP-CLI checks for self-maintained installs

Two commands cover most of the ground. First, list every distinct meta key that contains the substring you’re testing, with counts, to find near-duplicates:

wp db query "SELECT meta_key, COUNT(*) AS n FROM wp_postmeta WHERE meta_key LIKE '%editorial_reviewed%' GROUP BY meta_key ORDER BY n DESC;"

Second, for a specific post, dump the raw rows without going through the meta cache:

wp db query "SELECT meta_id, meta_key, meta_value FROM wp_postmeta WHERE post_id = 12345 AND meta_key LIKE '%editorial_reviewed%';"

Both commands bypass get_post_meta() and its cache, which is the point. The cache is where the case-sensitivity discrepancy documented above lives.

What to change, and what not to

If the generated SQL shows a correct LEFT JOIN ... IS NULL on the key you tested, and the direct wp_postmeta query shows no row with that exact key for the returned post, then the query is not the cause. Do not add a posts_where filter to “fix” NULL handling. Do not wrap the key in COALESCE(). Do not switch to a raw $wpdb query. Those changes address a problem that isn’t there, and they make the next debugger’s job harder.

If the generated SQL shows a second clause contributing a WHERE condition on the same alias as the NOT EXISTS clause, the fix is to restructure the meta_query. The most reliable pattern for “posts without key A, among posts with key B” is two queries: one to fetch the post IDs that have key A, and one WP_Query with 'post__not_in' => $ids plus the key B condition. It’s two round trips instead of one, but the SQL is unambiguous and the result set is easy to verify.

If the generated SQL shows the NOT EXISTS clause with a meta_value condition, the value was not ignored — which means the clause is not actually reaching the NOT EXISTS branch. Check the compare string for case and whitespace. 'not exists' is not 'NOT EXISTS'; the source uppercases the compare value, but a typo like 'NOT_EXISTS' will fall through to the default '=' operator and produce a value comparison instead.

If the direct wp_postmeta query shows the key exists with a different string than the one tested, fix the data. A one-off UPDATE or a wp post meta update call is the right tool. The query was correct; the stored key was not.

Why the NULL framing persists

The NULL explanation is appealing because it’s technically true in general and it matches the surface symptom. MySQL’s manual is clear that comparisons with NULL return NULL, and that NULL is not equal to anything, including itself. A developer who knows that and sees a NOT EXISTS query returning a post with the key will reasonably conclude that the NULL comparison is the culprit.

But the retrieved core source shows the operator is implemented with IS NULL on the joined meta_id column, not with a comparison on meta_value. The NULL semantics are handled. The failure modes are in clause assembly, value handling, and key matching — three places that a NULL-focused diagnosis will never look.

The practical takeaway for a self-maintained install is to make the generated SQL the first artifact you inspect, not the last. A five-line get_meta_sql filter and a direct wp_postmeta query will resolve most of these reports in a single request. The NULL theory, however well-intentioned, costs more time than it saves.

FAQ

Does NOT EXISTS behave differently from the older meta_compare shorthand?

No. Both routes end up in WP_Meta_Query::parse_query_vars() and then get_sql_for_clause(), which is where the LEFT JOIN and IS NULL construction lives. The generated SQL is the same shape regardless of whether you pass 'compare' => 'NOT EXISTS' inside a meta_query array or use the older top-level meta_key / meta_compare arguments.

Can a NOT EXISTS clause match a row where meta_value is NULL?

No, and this is the part the NULL theory gets backwards. The IS NULL test is on meta_id, which is the primary key of wp_postmeta and is never NULL for an existing row. A row with a NULL meta_value still has a non-NULL meta_id, so the LEFT JOIN matches it and the IS NULL test fails. The post is correctly excluded. If you want to match posts whose key exists but whose value is NULL, that’s a different query — typically 'compare' => '=' with 'value' => null won’t work either, because of the same NULL comparison rules. You need a raw $wpdb query with meta_value IS NULL.

Why does the same query return different results on staging and production?

Two likely causes. First, the database collation may differ. A _ci collation makes key comparisons case insensitive in SQL, while get_post_meta() remains case sensitive due to caching, as documented on the get_post_meta() reference. Second, the meta rows themselves may differ — a key that was written with different casing or whitespace on one environment will not match a query that tests the canonical form. Run the wp_postmeta LIKE query on both environments and compare the key_with_brackets output.

Is there a core ticket for this?

The retrieved source shows the LEFT JOIN plus IS NULL construction is the intended implementation, not a workaround for a known bug. The behavior described in this article is the documented behavior of the operator, and the failure modes are in how the operator is used, not in how it is implemented. If you believe you have found a case where the generated SQL is correct and the result set is still wrong, the next step is to check for filters on posts_results, the_posts, or pre_get_posts before filing anything.

What about WP_Query returning nothing at all on a fresh install?

That’s a different failure mode with a different diagnostic path. The what to fix first when a new WordPress site says nothing found article covers the empty-result case; this one covers the false-positive case. They share the same first step — read the generated SQL — but the causes diverge after that.