Incident Response

PostgreSQL ERROR: syntax error at or near

The parser stopped at the first token it could not fit into the grammar and is showing you where. Here is how to read the caret, the mistakes behind most of these errors, and how to keep syntax errors out of production migrations and deploys across a fleet.

· 14 min read · AG Data Team

PostgreSQL ERROR: syntax error at or near means the parser read your statement token by token and reached one it could not fit into SQL grammar at that point. The quoted token is where it stopped, not necessarily where the mistake is. Usually the real problem is just before it: a missing or extra comma, an unclosed parenthesis, or a word PostgreSQL treats as a keyword.

app=# SELECT id, email, FROM customers;
ERROR:  syntax error at or near "FROM"
LINE 1: SELECT id, email, FROM customers;
                          ^

app=# SELECT id FROM customers WHERE id IN (
ERROR:  syntax error at end of input

The SQLSTATE is 42601, syntax_error in the error codes appendix. The wording comes from the scanner source: when the parser stops on a token, the message reads syntax error at or near "token". When it runs out of text first, the message reads syntax error at end of input. The second form almost always means the statement was cut short: a missing closing parenthesis, an unfinished WHERE, or a query built by code that never appended its last part.

Read the caret, then look one step to the left

psql prints the line and a caret under the position the server reported. The parser fails as soon as it reaches the first token it cannot use, so the caret marks the first token that made the statement impossible. In SELECT id, email, FROM customers, nothing is wrong with FROM. The extra comma before it told the parser to expect another column.

For long statements generated by an ORM or a migration tool, get the exact text the server received. Logs or driver debug output are better than the template in your code, because the bug often sits in how the pieces were joined. By default, log_min_error_statement is ERROR, so the server log already contains the failing statement next to the error (logging documentation).

The mistakes behind most syntax errors

-- 1. a trailing (or missing) comma
SELECT id, email, FROM customers;           -- at or near "FROM"

-- 2. a reserved word used as a name
CREATE TABLE user (id int);                 -- at or near "user"
CREATE TABLE "user" (id int);               -- works, but now always needs quotes
CREATE TABLE app_user (id int);             -- better

-- 3. MySQL habits
CREATE TABLE `orders` (id int);             -- at or near "`"
SELECT * FROM orders LIMIT 20, 10;          -- LIMIT #,# syntax is not supported
SELECT * FROM orders LIMIT 10 OFFSET 20;    -- PostgreSQL form

-- 4. an empty IN list built by application code
SELECT * FROM orders WHERE id IN ();        -- at or near ")"

Fixes that hold up in application code

  1. Pass lists as one array parameter. id = ANY($1) works for any list length. The documentation defines the result for an empty array as false, which is exactly what an empty IN should mean. It also keeps one statement shape for every list size.
  2. Quote dynamic identifiers properly. In PL/pgSQL or SQL that builds statements, use format() with %I for identifiers and %L for literals rather than concatenating strings. That covers reserved words and odd characters, and it closes the door to SQL injection.
  3. Use the placeholder style of your driver. The server's own parameter markers are $1, $2. Drivers that accept ? or %s translate them before sending. In our experience, a raw ? reaching the server usually means a query bypassed the driver's parameter handling, which is worth checking for injection risks too.
-- one statement for any list length, including zero
SELECT * FROM orders WHERE id = ANY($1);    -- $1 is an int[] parameter

-- quote dynamic identifiers instead of concatenating them
SELECT format('SELECT count(*) FROM %I', 'user');  -- SELECT count(*) FROM "user"

If a syntax error appears only in production, compare versions first. SQL that parses on your laptop can fail on the server because the server runs an older major version. MERGE and UNIQUE NULLS NOT DISTINCT, for example, arrived in PostgreSQL 15. On PostgreSQL 14 both fail as syntax errors. Run SELECT version(); on both sides before you debug the query.

Syntax errors at scale: migrations, deploys and fleets

One syntax error in an interactive session costs a retry. In a migration that runs against a large, busy database, or in a release that rolls out to hundreds of application servers, the cost is very different. These are the points that matter:

# run migrations so the first error stops everything and rolls back
psql -v ON_ERROR_STOP=1 --single-transaction -f migration_0142.sql

# log_line_prefix with %e puts the SQLSTATE into every log line
log_line_prefix = '%m [%p] %e %u@%d '
# then count syntax errors (42601) per minute after a deploy
grep ' 42601 ' postgresql.log | cut -c1-16 | uniq -c

Key takeaways

PostgreSQL Errors SQL Migrations
Work with us

Migrations failing halfway through?

We review and run PostgreSQL migrations, check SQL against the versions you actually run, and set up logging that shows a bad deploy within minutes.

Get in touch More from the blog