Fix “Syntax Error at or Near” in SQL
The parser stopped at the first word it could not use. The quoted token is where it gave up, not always where the mistake is.
The symptom
You run a query and the database rejects it before touching any data, with a message like syntax error at or near "where". Nothing executed. The parser read your statement left to right, reached a word it could not fit into valid SQL, and stopped there.
Why it happens
The quoted word is where the parser gave up, which is usually one step past the real mistake. In the query below the problem is the emptyFROM clause, but the parser only notices when it reacheswhere and finds no table name in front of it.
So read the quoted token, then look at what comes immediately before it. The common causes are a missing table name, a trailing comma beforeFROM, a missing closing parenthesis, a misspelled keyword, and a reserved word used as an unquoted column name.
The fix
Name the table the query reads from. Once FROM products is present the parser has a complete clause and the statement runs.
When the cause is not obvious, cut the query down. Delete clauses from the bottom up, starting with ORDER BY, then WHERE, until it parses. The last clause you removed contains the mistake.
A missing closing parenthesis often reports at the end of the statement rather than at the opening bracket, because the parser keeps reading, expecting the expression to finish. If the quoted token is the last word of your query, count the brackets first.
How other engines word it
| Engine | Message |
|---|---|
| DuckDB | Parser Error: syntax error at or near "where" |
| PostgreSQL | ERROR: syntax error at or near "where" |
| MySQL | You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'where price > 20' |
| SQL Server | Incorrect syntax near the keyword 'where'. |
| Oracle | ORA-00906: missing left parenthesis andORA-00936: missing expression are the usual forms. Oracle names the missing piece rather than the token it stopped on. |
| SQLite | near "where": syntax error |
Learn more
Related
Understand tables, rows, columns, and queries.
Learn the basic shape of relational data.
Run queries and read results in the browser.
Write a first SELECT and read the returned rows.