Fix "syntax error at or near" in PostgreSQL
ERROR: syntax error at or near "FROM"
Postgres read your query word by word and got stuck at the word it shows you. That word is where it noticed the problem, but the actual mistake is often right before it, like an extra comma or a missing one.
Why it happens
- A trailing comma after the last column, right before FROM.
- Clauses in the wrong order. The order is SELECT, FROM, JOIN, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT.
- Syntax from another database, like SELECT TOP 5 from SQL Server.
- A misspelled keyword (FORM, WHRE) or a missing comma between columns.
How to fix it
1. Remove the trailing comma
Fails
SELECT name, email, FROM customers;
Works
SELECT name, email FROM customers;
After a comma Postgres expects another column, so it trips over FROM. This happens a lot after deleting the last column from a list.
2. Put the clauses in the right order
Fails
SELECT id, amount, order_date FROM orders ORDER BY amount DESC WHERE status = 'completed';
Works
SELECT id, amount, order_date FROM orders WHERE status = 'completed' ORDER BY amount DESC;
WHERE always comes before GROUP BY and ORDER BY. ORDER BY and LIMIT go at the very end.
3. Use LIMIT instead of TOP
Fails
SELECT TOP 5 id, amount FROM orders ORDER BY amount DESC;
Works
SELECT id, amount FROM orders ORDER BY amount DESC LIMIT 5;
Postgres has no TOP. It reads TOP as a column name, then chokes on the 5. LIMIT goes after ORDER BY.
Try it yourself
This is the broken query, running on real PostgreSQL in your browser. Press Run to see the error explained, then fix it.
Starting Postgres in your browser…
Real Postgres in your browser. Edit the query and run it, or open it in the full playground.