sqlstreak

SQL error

invalid input syntax for type integer: "3 years"

Updated · Tested on PostgreSQL 18.6 and SQLite 3.54.1 (results generated , re-checked on every release)

Short answer

PostgreSQL tried to turn a piece of text into an integer and the text isn't a valid number. Compare with a real number, or clean the text before casting.

The exact messages

  • PostgreSQLERROR: invalid input syntax for type integer: "3 years"
  • SQLiteNo error, but a silent surprise: see below.

How to read this message

This is what PostgreSQL 18.6 prints for the broken query below, the way psql shows it. LINE gives the line it was reading when it gave up, and the ^ marks the exact spot.

ERROR:  invalid input syntax for type integer: "3 years"
LINE 2: WHERE age = '3 years';
                    ^

Why it happens

Comparing a number column with text

WHERE age = '3 years': the quoted value has to become an integer, and it can't.

Casting messy imported data

CAST(budget AS integer) fails on values like '$120' or ''. Strip the junk first and turn empty strings into NULL with NULLIF(x, '').

Reproduce it, then fix it

Both queries run on a real database in your browser. Switch dialects to compare.

Broken
SELECT name FROM pets
WHERE age = '3 years';
Fixed
SELECT name FROM pets
WHERE age = 3;

Compare numbers with numbers. For messy text columns, see the data-cleaning guide for safe ways to convert them.

The fix returns, PostgreSQL: 3 rows

name
Biscuit
Clover
Pumpkin

The fix returns, SQLite: 3 rows

name
Biscuit
Clover
Pumpkin

Experiment with it: PostgreSQL playground·SQLite playground

What SQLite does instead

SQLite doesn't complain: it compares the text '3 years' with numbers, finds nothing equal and returns zero rows. (And CAST('abc' AS INTEGER) silently gives 0.)

Official documentation

Stop hitting this error

Practise the concept behind it in a five-minute lesson, or read the full guide: Data cleaning in SQL.