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
- Commas and parentheses. A trailing comma before
FROMor), a missing comma between columns, or one parenthesis too few. These are the most common, and the caret points right after them. - Reserved words used as names.
user,order,groupandtableare reserved in PostgreSQL, soCREATE TABLE userfails. The SQL key words appendix says that if you get spurious parser errors for commands that use one of the listed key words as an identifier, you should try quoting the identifier. Quoting works, but every query must then quote it too. Renaming toapp_useris usually the cheaper fix. - MySQL habits. Backticks are not quote characters in PostgreSQL; identifiers are quoted with double quotes.
LIMIT 20, 10gets its own message, LIMIT #,# syntax is not supported, with a hint to use separateLIMITandOFFSETclauses. If you are moving a whole application, see our MySQL to PostgreSQL migration guide. Note that double quotes around a string value are not a syntax error but an identifier, which gives you column does not exist instead. - Empty IN lists. PostgreSQL's grammar requires at least one expression inside
IN ( ). Code that builds the list from user input fails the moment the list is empty. - Client commands sent to the server.
\copy,\dand other backslash commands are psql features. Pasted into a driver, a GUI tool or a migration file run by something other than psql, they reach the server as SQL and fail on the backslash. - Quoting inside function bodies. A single quote inside a function body written with single quotes ends the string early. Dollar quoting (
$$ ... $$, see lexical structure) avoids that. When the closing tag is missing, the error is unterminated dollar-quoted string.
-- 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
- 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 emptyINshould mean. It also keeps one statement shape for every list size. - Quote dynamic identifiers properly. In PL/pgSQL or SQL that builds statements, use
format()with%Ifor identifiers and%Lfor literals rather than concatenating strings. That covers reserved words and odd characters, and it closes the door to SQL injection. - Use the placeholder style of your driver. The server's own parameter markers are
$1,$2. Drivers that accept?or%stranslate 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:
- psql keeps going after an error by default. According to the psql documentation, command processing continues after an error unless
ON_ERROR_STOPis set. A migration file with a typo in statement 7 still runs statements 8 to 40, and you end up with a half-applied schema. Run migrations with-v ON_ERROR_STOP=1. Add--single-transactionwhen everything can run in one transaction, so that a failure rolls back all of it. The documentation warns that this option does not work as intended if the file itself containsBEGIN,COMMITorROLLBACK, and that a command which cannot run inside a transaction block (such asCREATE INDEX CONCURRENTLY) makes the whole transaction fail. - Test against the major version you run. In mixed fleets where some clusters are already on 17 or 18 and others are still on 14, CI should parse every migration against the oldest version it will meet. Otherwise newer syntax passes review and fails on the one old cluster during the rollout.
- Dumps do not always load into older servers. The pg_dump documentation says its output is not guaranteed to load into an older major version, and that by default pg_dump only quotes identifiers that are reserved in its own version. When a dump has to move between versions,
--quote-all-identifiersavoids reserved-word surprises. Plan for some manual edits if you go backwards. - Watch SQLSTATE 42601 right after every deploy. Add
%etolog_line_prefixso every log line carries the SQLSTATE. In our experience, a jump in 42601 within minutes of a release is the fastest and least ambiguous signal that the release shipped broken SQL, often long before error tracking groups the exceptions. Remember thatlog_min_error_statementwrites full statement text to the log, so check what that means for sensitive data and log volume on a busy server. - Keep reserved words out of new schemas. Names that need quotes force every tool, report and future engineer to quote them. That works until someone forgets, so choose plain names when you design tables instead of fixing them during an incident.
# 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
- ERROR 42601 syntax error at or near marks the first token the parser could not use. The mistake is usually just before the caret.
- At end of input means the statement was cut short.
- Most cases are commas, parentheses, reserved words such as
user, MySQL habits, emptyIN ()lists and psql commands sent through other clients. - In code, use
= ANY($1)for lists andformat('%I')for dynamic identifiers. - For migrations, run psql with
ON_ERROR_STOP=1and--single-transactionwhere possible, test against the oldest major version in your fleet, and watch 42601 in the logs after each deploy.