How to Fix Postgres Error 22031 Invalid Argument for SQL Json Datetime Function
The postgres error 22031 invalid argument for sql json datetime function occurs when a JSON path expression receives a bad date, time, or format string. You can fix it by matching your format template to the JSON text or cleaning up bad date strings in your table. Database engines use strict rules when they turn text into date and time values. When a query reads JSON data and finds an unexpected date shape, the query stops right away. Understanding why this happens helps your team keep data pip
Your coding agents run with your access.
Claude Code reaches prod with a developer's credentials, and approval prompts get clicked through. hoop.dev checks every query, masks sensitive data, and holds risky changes for a human.
The postgres error 22031 invalid argument for sql json datetime function occurs when a JSON path expression receives a bad date, time, or format string. You can fix it by matching your format template to the JSON text or cleaning up bad date strings in your table.
Database engines use strict rules when they turn text into date and time values. When a query reads JSON data and finds an unexpected date shape, the query stops right away. Understanding why this happens helps your team keep data pipelines running without crashes.
Root causes of postgres error 22031 invalid argument for sql json datetime function
In the Postgres engine, this failure maps to SQLSTATE 22031. The internal error name is ERRCODE_INVALID_ARGUMENT_FOR_SQL_JSON_DATETIME_FUNCTION. It belongs to the data exception class of database errors.
This error triggers when a JSON path query runs its datetime method on bad input. There are two main ways this method fails during a query run. First, the format string passed to the datetime method might have invalid tokens. If you pass a letter that Postgres does not recognize as a date part, the engine throws SQLSTATE 22031.
Second, the JSON field itself might hold text that does not match any valid date or time. If you do not supply a format template, Postgres tries standard ISO date shapes by default. When a record holds a custom date format or plain text like a word, the parser fails. Even one bad row in a large table will stop the whole read query if the error mode is strict.
Apps often write JSON payloads from external webhooks or user forms without checking date formats first. One upstream app might send a timestamp with a time zone offset, while another sends only a year and month. When a backend job tries to parse both rows with the same rule, the mismatch triggers error 22031.
How to diagnose and fix the failure in production
To find the broken rows in production, you need to check the JSON values safely. Do not grant full table write privileges to developers who only need to inspect the broken payloads. In Postgres, you can grant the SELECT privilege on specific columns of a table or view. This lets engineers read the broken JSON column without exposing other columns that hold private data.
JSON Web Tokens (JWT) + Serverless Function Security: architecture patterns and best practices
Continue reading? Get the full guide.
Free. No spam. Unsubscribe anytime.
You can also set up group roles to manage privileges when many team members need read permissions. Grant the column-level read privilege to the group role, and then add each user to that group. If you work on a shared database, check your schema rules as well. In PostgreSQL 15 and later, the default setup no longer lets every user create objects in the public schema. On older versions, admins should revoke CREATE on the public schema from the PUBLIC role so users cannot create stray debug tables.
Once an engineer has safe read permissions, they can filter the table to find rows with bad date strings. Look for null strings, empty spaces, or dates where the month and day are swapped. Compare those raw strings against the format template used in the JSON path query.
To fix the query without changing the stored data, update the JSON path expression to use a matching format template. You can also use the silent error handling mode inside the JSON path check. When a JSON path runs in silent mode, it returns a null value for bad rows instead of stopping the whole query with error 22031.
Preventing bad JSON datetime inputs in your apps
Fixing the query solves the immediate crash, but you should also stop bad dates from entering the database. Start by checking all incoming JSON payloads at the app layer before writing to Postgres. Convert all dates to a single standard ISO format before you save the record.
You can also add a check constraint on the table to test the JSON date structure on write. That way, if an app sends a bad date string, Postgres rejects the bad write right away. This keeps your stored JSON clean and stops future read queries from failing during batch reports. When teams pair strict input checks with least-privilege read roles, they can find and fix data bugs fast.
Check every Postgres query on the wire
Database roles and network rules decide who can open a session. They do not read what each SQL statement does after login. With hoop.dev, you run an open-source proxy, a sidecar for your Postgres, inline in the Postgres wire protocol. On every query an AI agent or engineer runs against production, hoop.dev decides to pass, mask, block, or hold it for human review. Your apps and agents keep their login details and change only the host and port in the connection string their tool uses.
Before a query runs, hoop.dev guardrails refuse bad deletes or drops with a real Postgres error, or hold risky queries for approval. On the way back, hoop.dev data masking rewrites sensitive values in returned rows in memory, and every verdict goes to the audit trail. Furthermore, hoop.dev holds SOC 2 Type II, is MIT licensed, and generates evidence for HIPAA, GDPR, and PCI DSS. See the code on GitHub.
Frequently asked questions
What does SQLSTATE 22031 mean in Postgres?
SQLSTATE 22031 means a JSON datetime function received an invalid argument. This happens when the format template is broken or the JSON string cannot be parsed as a date or time.
Can one bad row cause error 22031 to fail a whole query?
Yes, if your JSON query uses strict error handling or runs inside a cast, one bad row stops the whole query. Using a silent filter mode lets the query skip broken rows and return null instead.
How can developers inspect bad JSON rows without seeing full table data?
Admins can grant the Postgres SELECT privilege on only the specific JSON column and row ID column. When paired with data masking that rewrites emails, phone numbers, card numbers, or national IDs in query results, developers can debug safely.
Related guides
In this post