Handling JSON Null Values in SQL INSERT Statements

Learn how to correctly convert JSON null values to SQL NULL. Covers the difference between missing keys and explicit nulls, nullable columns, and NOT NULL constraint handling.

Basic INSERT

Detailed Explanation

JSON Null to SQL NULL

JSON has a first-class null type, and SQL has the NULL keyword. While they share a concept, the mapping requires careful handling to avoid constraint violations and data integrity issues.

Example JSON

{
  "id": 1,
  "name": "Alice",
  "middle_name": null,
  "email": "alice@example.com",
  "phone": null
}

Generated SQL

INSERT INTO users (id, name, middle_name, email, phone)
VALUES (1, 'Alice', NULL, 'alice@example.com', NULL);

Null vs Missing Keys

There is an important distinction between an explicit null value and a missing key:

JSON state SQL behavior
Key present, value is null Column set to NULL
Key missing entirely Column omitted (uses DEFAULT or NULL)

NOT NULL Constraints

If the target column has a NOT NULL constraint, inserting NULL will cause an error:

ERROR: null value in column "name" violates not-null constraint

The converter should warn when null values target columns known to be non-nullable.

COALESCE for Default Fallbacks

When you want to replace NULL with a default value at query time:

INSERT INTO users (id, name, middle_name)
VALUES (1, 'Alice', COALESCE(NULL, 'N/A'));
-- middle_name will be 'N/A'

NULL in Comparisons

Remember that SQL NULL is not equal to anything, including itself:

SELECT * FROM users WHERE middle_name = NULL;   -- Wrong! Returns nothing
SELECT * FROM users WHERE middle_name IS NULL;   -- Correct

Batch Handling

In multi-row inserts, null values may appear in different columns for different rows. The converter ensures consistent column ordering and fills missing values with NULL so every row has the same number of values.

Use Case

When loading API responses that contain optional fields (such as user profiles with optional phone numbers or bios), correctly mapping JSON nulls to SQL NULL ensures the database schema's nullable columns are populated accurately. This is critical for analytics queries that filter on IS NULL / IS NOT NULL.

Try It — JSON to SQL

Open full tool