Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

PostgreSQL Error 22P02: Fix Invalid Text Representation

· 5 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

PostgreSQL error 22P02 occurs when the database tries to convert a text value into a different data type—like integer, numeric, or date—but the text is not valid for that conversion. This is common when importing data, inserting user input, or running queries with type mismatches. The fix involves identifying the malformed value and correcting it at the source. No special tools are required—just access to your database and awareness of your data structure.

What You'll Need

  • Access to the PostgreSQL database (via psql, pgAdmin, DBeaver, or any SQL client)
  • Permissions to read and modify the affected table(s)
  • The exact query or operation that triggered the error
  • Knowledge of the target column’s data type (e.g., INTEGER, DATE, NUMERIC)

Step-by-Step

  1. Copy the full error message. It typically includes the table name, column name, and the invalid value. Example: ERROR: invalid input syntax for integer: "abc" indicates column X contains the text "abc" where an integer was expected.
  2. Identify the table and column causing the issue. Use the error message’s reference to the column. If the error mentions "column price" in table "products", focus on the "price" column in the "products" table.
  3. Run a query to find all rows with invalid data in that column. For example, if the column is INTEGER, use: SELECT id, price FROM products WHERE price !~ '^[0-9]+$' AND price IS NOT NULL; This finds non-numeric text. Adjust the regex based on your target type—for dates, use WHERE date_column !~ '^[0-9]{4}-[0-9]{2}-[0-9]{2}$' if expecting YYYY-MM-DD.
  4. Examine the results. Look for values like empty strings, letters, symbols, extra spaces, or malformed formats. Common culprits: "N/A", "", "1,000" (with comma), "2023/12/01" instead of "2023-12-01".
  5. Decide how to fix each invalid value. Options: clean it (e.g., remove commas), replace it with NULL, or update it to a valid default. For example: UPDATE products SET price = NULL WHERE price = '' OR price = 'N/A';
  6. For numeric fields with commas, remove them: UPDATE products SET price = REPLACE(price, ',', '') WHERE price LIKE '%,%'; Then verify the new values are numeric with SELECT price FROM products WHERE price !~ '^[0-9.]+$';
  7. For dates, standardize format. If importing "MM/DD/YYYY" into a DATE column expecting "YYYY-MM-DD", convert it: UPDATE events SET event_date = TO_DATE(event_date, 'MM/DD/YYYY') WHERE event_date LIKE '%/%'; Always test with a few rows first.
  8. After cleaning, test the original query that failed. If it still errors, check for hidden characters: SELECT id, LENGTH(price), ASCII(SUBSTRING(price,1,1)) FROM products WHERE price IS NOT NULL LIMIT 5; This reveals leading/trailing spaces or non-printable characters.
  9. Use CAST or CONVERT explicitly in your query if the issue persists in application code. Instead of relying on implicit conversion, write: SELECT CAST(price AS INTEGER) FROM products WHERE price ~ '^[0-9]+$'; This avoids errors by filtering before casting.
  10. Prevent future issues by altering the column to NOT NULL with a DEFAULT if appropriate, or by adding a CHECK constraint: ALTER TABLE products ADD CONSTRAINT valid_price CHECK (price ~ '^[0-9.]+$' OR price IS NULL);

Common Mistakes

  • Assuming all empty strings are NULL—PostgreSQL treats them as text, not null values, so they fail numeric conversions.
  • Trying to convert "1,000" to INTEGER without removing the comma first. The comma is not a valid digit character.
  • Using implicit type casting in application code (e.g., passing a string to a numeric field) instead of validating input before sending it to the database.
  • Running UPDATE queries without a WHERE clause, accidentally corrupting valid data.
  • Ignoring leading/trailing whitespace. Values like " 123 " or "123 " can fail silently or cause errors depending on context.
  • Believing the error means the entire table is broken—it’s usually just one or a few rows.

Tips

  • Always backup your table before running mass updates: CREATE TABLE products_backup AS SELECT * FROM products;
  • Use SELECT before UPDATE. Always test your filtering condition with SELECT to confirm it matches only the bad rows.
  • Use PostgreSQL’s TRY_CAST function (available in version 13+) to safely convert values without error: SELECT TRY_CAST(price AS INTEGER) FROM products; Invalid values return NULL.
  • For imported CSV files, preprocess them with tools like Python (pandas) or Excel to clean data before loading.
  • Log all invalid rows during import into a separate error table for review later.
  • Use data type validation in your application layer—don’t let malformed strings reach the database.

Troubleshooting

If the error persists after cleaning the data:

  1. Restart your database client or connection. Sometimes the client caches the query or misinterprets the result.
  2. Check for triggers or views referencing the column. The error might originate from a trigger that runs on INSERT/UPDATE. Query SELECT tgname, pg_get_triggerdef(oid) FROM pg_trigger WHERE tgrelid = 'products'::regclass; to list triggers on the table.
  3. Verify you’re editing the right table. If you have multiple schemas or databases, confirm the schema prefix: SELECT * FROM myschema.products;
  4. Look for materialized views or functions using the column. Rebuild them after cleaning: REFRESH MATERIALIZED VIEW myview;
  5. If using an ORM like Django or Hibernate, clear its cache or restart the application server—ORMs may cache schema metadata.
  6. Check for hidden Unicode characters using SELECT encode(price::bytea, 'escape') FROM products WHERE id = ; This reveals non-printable bytes like \x00 or \x09 (tab).
  7. If all else fails, export the table as CSV, open it in a text editor, search for the bad value manually, fix it, then re-import with COPY.

Frequently Asked Questions

What does "invalid text representation" mean in PostgreSQL?

It means PostgreSQL tried to convert a string into a non-text data type (like integer, date, or float), but the string didn’t match the expected format—e.g., trying to turn "abc" into a number.

Can I ignore this error and let PostgreSQL handle it?

No. PostgreSQL will reject the operation entirely. You must fix the data before the query can succeed.

Why does "1,000" cause this error but "1000" doesn’t?

PostgreSQL expects numeric values without separators. Commas, spaces, or currency symbols are not valid in numeric literals unless explicitly handled by functions like REPLACE.

Is there a way to automatically clean bad data during import?

Yes. Use the COPY command with a temporary staging table, then use SQL to clean and insert into the final table. Or use pgAdmin’s import wizard with data type mapping options.

Can a trigger cause this error even if my INSERT looks fine?

Yes. Triggers can modify or validate data after your INSERT. Check for triggers on the table using SELECT tgname FROM pg_trigger WHERE tgrelid = 'tablename'::regclass;

How do I prevent this error when accepting user input?

Validate input in your application before sending it to the database. Use type checks, regex patterns, or libraries that enforce format rules—never trust raw user strings for numeric/date columns.