JSON in a Cell

Where Did the Field Go? Missing Key, null, and NULL

30 min

The commandant is putting together a profile of the customers. Who are these ten people, how did they use the store, and what did they configure in the app? He suggests starting with something simple: how many customers chose the dark theme, how many chose the light theme, and how many chose no theme at all.

You already know how to extract values: settings ->> 'theme'. The query takes a minute to write. Three customers use the dark theme, two use the light theme, and then NULL starts appearing in the column. Four NULLs among ten customers. The commandant writes in the summary: “Four customers didn't choose a theme.”

You open those four customers' documents one by one, and the summary has to wait. Customer 17 has no theme key in the settings at all. Customers 31 and 91 have the key, but its value is null. Customer 64 doesn't even have a document: the settings column is empty.

QUERY: The table shows four identical NULLs, but they have different causes. Let's count each one separately.

We need to learn how to distinguish these kinds of missing data in a query. We'll discuss why each of the four is empty in a different way, and what that means for the store, in Chapter 5. For now, the task is technical: if we leave all four rows as one NULL, a metric based on an optional field can easily answer the wrong question.

A cadet seen from behind stands in front of three holographic parcels on a table in the Unpacking Room. The first box is open, but there is no compartment inside for the item they need. The second has a compartment marked with a glowing label, but the compartment itself is empty. Only a bright outline remains from the third parcel on the table; there is no box inside it. QUERY, the robot cat, sits between them and looks at the empty outline.
Missing key, null value, missing document. The double arrow makes all three kinds of missing data look the same.

The commandant's query

Let's repeat the commandant's query and look closely at the result. user_settings contains ten customers, one row per customer. In the settings document, the theme key can store dark or light.

Before you run it, estimate how many rows the query will return and how many will have NULL in the theme column. Also find customer 56: their theme cell isn't NULL, but it doesn't contain a theme name either.

SELECT user_id, settings ->> 'theme' AS theme
FROM user_settings
ORDER BY user_id;

What's behind each NULL

The double arrow gave the same result for four customers. Now let's display the documents themselves and see whether their settings are really the same.

Before you run the query, try to spot the differences yourself. For customer 17, look for the word theme in the document. For 31 and 91, check what comes after the colon next to theme. For customer 64, look not at the contents but at the entire cell.

SELECT user_id, settings
FROM user_settings
WHERE user_id IN (17, 31, 64, 91)
ORDER BY user_id;

Three kinds of missing data

We'll need to tell these cases apart from here on, so let's give each one a short name.

Missing key. There is no theme entry in the document. That's customer 17: the settings box exists, but there is no compartment for the theme inside it.

null. The key exists, and its value is null. That's customers 31 and 91: the compartment is labeled, but it's empty inside. Someone explicitly wrote this value into the document; it didn't appear there by itself.

SQL . The document itself is missing, so the settings cell is empty. That's customer 64: the parcel never arrived, so there is nothing to open.

The diagram places these three kinds of missing data next to customer 23's ordinary value. Under each box, you can see what the tools from this lesson return. Don't memorize the whole table yet: we'll build it one column at a time.

The source documents distinguish these kinds of missing data. After ->> and IS NULL, customers 17, 31, and 64 look the same.

What the arrows return

Let's test each kind of missing data with the arrows from the previous lesson. Start with customer 31. They do have a theme key, so -> returns the contents of that key: the value null. This value has the jsonb type and really is stored in the document. That means settings -> 'theme' IS NULL is false for customer 31.

Now for the double arrow. ->> is supposed to return the key's contents as text, but JSON null has no text value. PostgreSQL returns SQL NULL. So settings ->> 'theme' IS NULL is true for customer 31.

For 17 and 64, both arrows return SQL NULL: customer 17 doesn't have the requested key, and customer 64 doesn't have a document to extract anything from.

I'm casting the arrow column to text again. That makes JSON null appear as the word null, so it doesn't blend in with a real NULL in the result. Fill in the rows for customers 17, 23, 64, and 91 in your head, then run the query.

SELECT user_id,
       (settings -> 'theme')::text AS arrow,
       settings ->> 'theme' AS double_arrow,
       settings -> 'theme' IS NULL AS arrow_is_null,
       settings ->> 'theme' IS NULL AS double_is_null
FROM user_settings
WHERE user_id IN (17, 23, 31, 64, 91)
ORDER BY user_id;

IS NULL collapses three cases into one

The commandant selected customers with WHERE settings ->> 'theme' IS NULL. PostgreSQL runs the query without complaint and returns four people. If the question is “whose report row won't contain a theme name?”, the answer is correct. But the original question was different: who didn't choose a theme? Here, the four rows can no longer be treated as one group. They include one customer with no key, two with an explicit null, and one with no document at all.

The difference is even clearer with count. The count(expression) counts only rows where the expression isn't NULL. So count(settings -> 'theme') and count(settings ->> 'theme') return different numbers on this table. The first excludes 17 and 64; the second also excludes 31 and 91.

Before you run it, try to name all four numbers. You already have almost everything you need for the first two: there are ten rows in the table, and only customer 64 has no document.

SELECT count(*) AS all_rows,
       count(settings) AS with_doc,
       count(settings -> 'theme') AS arrow_not_null,
       count(settings ->> 'theme') AS text_not_null
FROM user_settings;

Does the key exist? The ? operator

There is a separate check for the first kind of missing data. The ? operator tells you whether the requested key exists at the top level of the document. settings ? 'theme' checks only whether theme is present; it doesn't care what value the key holds. So the result is true for customer 31 even though the value is null.

Customer 17 doesn't have the key, so the result is false. Customer 64 is trickier: there is no document to check, so ? returns NULL. Negation is a common source of mistakes here. The condition WHERE NOT settings ? 'theme' finds 17 but misses 64: NOT NULL is still NULL in SQL, and WHERE lets through only rows where the condition is true.

There's another boundary that's easy to trip over: ? checks only the top level. Many customers have an email key inside notifications, but settings ? 'email' still returns false. The operator doesn't reach down into notifications.email.

Before you run the query, predict three columns: has_theme, has_experiments, and has_email_top. The document contents will help with experiments: this key is stored only for customers participating in app experiments. Also think separately about what customer 64 will get in all three columns.

SELECT user_id,
       settings ? 'theme' AS has_theme,
       settings ? 'experiments' AS has_experiments,
       settings ? 'email' AS has_email_top
FROM user_settings
ORDER BY user_id;

JSON null: jsonb_typeof(…) = 'null'

The function from the first lesson helps with the second kind of missing data. jsonb_typeof(settings -> 'theme') reports the type of the value under the key. For the themes dark and light, the type is string. For customers 31 and 91, the function returns the word null: there is a value in the document, and its type is called exactly that.

For 17 and 64, the arrow itself returns SQL NULL first. A missing value has no type, so jsonb_typeof also returns NULL. That means the condition jsonb_typeof(settings -> 'theme') = 'null' selects exactly 31 and 91: they have the key, and it contains JSON null.

In this condition, 'null' is ordinary text containing the name of a type. The function also returns words such as string, number, null, and other type names. Here we're comparing the type name, not the JSON value.

There is also a shorter form: settings -> 'theme' = 'null'. The on the right becomes the JSON null value, and PostgreSQL then compares two jsonb values. The result is the same. I prefer jsonb_typeof because the query makes it immediately clear that we're interested in the type.

This technique no longer works with the double arrow. The condition settings ->> 'theme' = 'null' won't find any rows: ->> has already turned JSON null into SQL NULL, and comparing NULL with anything returns NULL. The text null would appear only for the JSON string "null", meaning the four letters inside quotation marks. Our settings don't contain that string.

Before you run it, predict one more row in the result: what type will customer 56 get for an empty string instead of a theme?

SELECT user_id,
       jsonb_typeof(settings -> 'theme') AS theme_kind
FROM user_settings
ORDER BY user_id;

Summary table with literals

With the customers, we tested the tools one at a time. Now let's strip everything else away and put four cases side by side using : a document with a theme, a document with "theme": null, an empty document {}, and SQL NULL instead of a document.

Besides the literal itself, there are five columns here. Fill in the entire table in your head first, then run it. I'd pay especially close attention to arrow_is_null in the second row and has_key in the last one: those are the two cells people most often get wrong.

SELECT doc,
       (doc::jsonb -> 'theme')::text AS arrow,
       doc::jsonb ->> 'theme' AS double_arrow,
       doc::jsonb -> 'theme' IS NULL AS arrow_is_null,
       doc::jsonb ? 'theme' AS has_key,
       jsonb_typeof(doc::jsonb -> 'theme') AS kind
FROM (VALUES ('{"theme": "dark"}'), ('{"theme": null}'), ('{}'), (NULL)) AS demo(doc);

All cases in one column

Let's label each kind of missing data directly in the query. CASE checks conditions from top to bottom and stops at the first true branch, so changing their order here can change the result.

The settings IS NULL check must come first. If you move it lower, customer 64 reaches NOT settings ? 'theme' and gets NULL. That isn't true, so evaluation continues. jsonb_typeof(…) = 'null' also returns NULL, and the row falls into ELSE with the label value. That creates an obvious semantic error: there is no document in the cell, but the query labels it as a value.

The working order is: no document, no key, null, value. After each check, only the rows that didn't match the previous conditions remain.

Before you run it, decide which group customer 56 will fall into.

SELECT user_id,
       settings ->> 'theme' AS theme,
       CASE
         WHEN settings IS NULL THEN 'no document'
         WHEN NOT settings ? 'theme' THEN 'no key'
         WHEN jsonb_typeof(settings -> 'theme') = 'null' THEN 'JSON null'
         ELSE 'value'
       END AS theme_state
FROM user_settings
ORDER BY user_id;

Now repeat the same technique for another key. In these settings, digest stores the mailing mode: weekly, daily, or none. For now, the cell shows only the raw values from settings ->> 'digest'. Apply the classification from the previous cell to digest and immediately count the customers in each group. Before you run it, estimate the numbers: customer 85 has null, 103 has an empty string, and 17 and 64 are in the same situation as with the theme: 17 has no key, while 64 has no document.

SELECT user_id,
       settings ->> 'digest' AS digest
FROM user_settings
ORDER BY user_id;

The same thing in gateway responses

This pattern also appears outside settings. Starting February 17, the payment gateway responds using the new API version, 2025-02: the error key now exists in every response. In every response that isn't a failure, whether successful or still processing, it contains null; for failed payments, it contains an object with an error code. In the old API, 2024-06, error appeared only when a payment failed. The contains seven old responses, numbers 1 through 7, and five new ones, numbers 8 through 12.

Suppose the “payment failures” summary was calculated with the condition response ? 'error'. Before February 17, that really did find failed payments: only those responses had this key. After the gateway update, the query didn't fail and kept returning rows, but now successful payments and a processing payment were included along with the failures. The metric increased even though PostgreSQL reported no error at all.

All twelve payments are below. Before you run the query, give me two numbers: how many rows will get true in has_error_key, and how many will have object in error_kind?

SELECT payment_id,
       response ->> 'status' AS status,
       response ? 'error' AS has_error_key,
       jsonb_typeof(response -> 'error') AS error_kind
FROM payments
ORDER BY payment_id;
Check yourself
An analyst looks for failures with WHERE response -> 'error' IS NOT NULL. How many payments will be returned?

Let's open the commandant's summary again. This time, it should include only customers whose theme key is present and whose value was reset to null. Customers with no key and no document should not be included. The query below runs successfully and currently returns four customers: 17, 31, 64, and 91. Two of them don't belong.

Find and fix the bug
The current condition mixes JSON null with other kinds of missing data. Change only the WHERE clause so that the result contains customers whose theme key exists and whose value is JSON null. Don't change the columns or the sorting.
SELECT user_id, updated_at
FROM user_settings
WHERE settings ->> 'theme' IS NULL
ORDER BY user_id;
Practice: solve the tasks
Solved 0 of 2 · any 1 is enough to pass

Common mistakes

Treating ->> IS NULL as proof that “the key is missing”

Row: customer 31, "theme": null.

Expectation: WHERE settings ->> 'theme' IS NULL finds customers whose settings don't contain a theme.

What actually happens: the query returns four customers: 17 without the key, 31 and 91 with null, and 64 without a document. After the double arrow, null becomes SQL NULL, so these cases can no longer be distinguished.

How to check: look for a missing key with NOT settings ? 'theme', and for JSON null with jsonb_typeof(…) = 'null'.

Expecting -> IS NULL to behave like ->> IS NULL

Row: customer 91.

Expectation: settings -> 'theme' IS NULL is true because the theme is stored as null.

What actually happens: the condition is false. The single arrow returned the JSON value null, which has a type and isn't treated by PostgreSQL as SQL NULL. The error key in the new gateway responses behaves the same way.

How to check: display (settings -> 'theme')::text next to it. The word null means the arrow really returned a JSON value; a real SQL NULL isn't displayed that way.

Losing rows with no document

Row: customer 64, where settings is NULL.

Expectation: WHERE NOT settings ? 'theme' returns everyone without a theme key, including rows where the document itself is missing.

What actually happens: customer 64 disappears from the result. ? applied to NULL returns NULL; after NOT, the result is still NULL, and WHERE filters that row out.

How to check: calculate count(*) - count(settings) first. If the result is greater than zero, decide separately what to do with rows that have no document. If they should be counted together with missing keys, say so explicitly: settings IS NULL OR NOT settings ? 'theme'.

Looking for failures by checking whether the key exists

Row: payment 8, "error": null.

Expectation: response ? 'error' selects failed payments.

What actually happens: the condition returns six of the twelve payments, even though only two have status failed. After the switch to the new API, the error key is present in successful responses too.

How to check: put count(*) FILTER (WHERE response ? 'error') next to count(*) FILTER (WHERE jsonb_typeof(response -> 'error') = 'object'). You'll get different numbers here because the existence of the key no longer means that an error exists.

Treating an empty string as missing data

Row: customer 56, "theme": "".

Expectation: ->> IS NULL finds this row too.

What actually happens: '' stores a zero-length string. For IS NULL, that's an ordinary value, and jsonb_typeof returns string.

How to check: if an empty string also means “nothing” in your metric, add a separate check: settings ->> 'theme' = ''. We'll discuss how to interpret values like this in reports in Chapter 5.

Transfer: four counts before any metric

When I need to build a metric from an optional field, I first count four groups: rows with no document, no key, JSON null, and an ordinary value. You already know the query: it's the same CASE and GROUP BY you built for digest. Instead of one generic NULL, you immediately see how many rows arrived in each state.

Then you can decide which of these groups actually answer the stakeholder's question. For example, “who never chose a theme” and “whose theme was reset” are different conditions. If I need two groups, I list them explicitly with OR so that the SQL itself shows exactly what was counted.

After an API or app version changes, it's worth counting these four groups again. Remember error: the format changed, some successful responses moved from “missing key” to “JSON null,” and the old query kept running without a single error.

I once caught a push notification problem this way. The share of customers with configured notifications was measured by checking whether a key existed. A new app version started writing the key for everyone and put null there for people who hadn't configured anything. Overnight, the metric jumped to almost one hundred percent. The query itself stayed green, so the team treated the spike as a successful release for an entire week.

Also useful

jsonb_strip_nulls(settings) removes keys whose value is null from a document at any depth. For example, for customer 85, digest and notifications.sms disappear after the call. This can be convenient when displaying cleaned-up , but I wouldn't do it before analysis: after cleanup, JSON null turns into “missing key,” and you can't recover the distinction.

The ?| and ?& operators check several keys at once: the first looks for at least one key from the list, while the second requires all of them. For example, settings ?| array['theme', 'digest']. We'll return to them in the next chapter.

When working from Java through JDBC or from PHP through PDO, there is one technical detail: the driver uses the ? character for query parameters. That's why the operator is written as ??; before sending the SQL, the driver turns it back into ?.

Key takeaways
  • We encountered three kinds of missing data in the documents: customer 17 has no key, customers 31 and 91 have null under the key, and customer 64 has no document at all. Customer 56's empty string "" is a separate, fourth case.
  • -> returns JSON null as the jsonb value null, so IS NULL is false for it. After ->>, the same JSON null becomes SQL NULL.
  • settings ->> 'theme' IS NULL returns all three kinds of missing data at once. The query is valid, but it can't tell you why the result is NULL.
  • ? checks for a key only at the top level. If the document itself is SQL NULL, the operator also returns NULL, so NOT … ? loses that row.
  • The condition jsonb_typeof(…) = 'null' separates JSON null from a missing key and a missing document.
  • The existence of a key tells you nothing about its contents by itself: response ? 'error' is true for six payments even though only two of them contain error objects.

Chapter complete. You can now open a parcel, extract a value, and avoid confusing three different reasons for NULL. The commandant has already brought the next task: break payments down by customer city. The city is buried deep in the gateway response, and the format changed after February 17. In the next chapter, we'll follow nested paths and learn how to find what we need inside a document.