SQL syntax error: unexpected token
Quick summary
Your SQL has a syntax error — the database parser encountered an unexpected token and could not parse the statement.
Why this happens
A keyword is misspelled or a SQL syntax element is in the wrong position
A string literal is not properly quoted or contains unescaped special characters
Dynamic SQL construction concatenated strings incorrectly, producing invalid SQL
Minimal example
await db.query('SELECT * FROM users WHERE name = ' + userName);
// If userName is O'Brien, SQL becomes: SELECT * FROM users WHERE name = O'Brien — syntax errorawait db.query('SELECT * FROM users WHERE name = $1', [userName]);
// Parameterized query handles quoting automaticallyUsing a parameterized query passes the value separately from the SQL text, avoiding syntax errors from special characters in the value.
How to diagnose
Read the error message for the position of the unexpected token in the SQL
Print the final SQL string if it is dynamically constructed to inspect for issues
Run the SQL in a database client or IDE that highlights syntax errors
How to fix
Correct the SQL syntax — fix misspelled keywords, missing commas, or wrong clause order
Use parameterized queries instead of string concatenation to avoid quoting issues
Validate dynamic SQL with a SQL parser library before sending it to the database
How to prevent
Always use parameterized queries or query builders to avoid SQL syntax errors from string concatenation
Test SQL statements in a database client before embedding them in application code
Related Resources
Related Lessons
- SQL Basics
Learn SQL syntax.