Fix "syntax error at end of input" in PostgreSQL
ERROR: syntax error at end of input
Postgres reached the end of your query while it was still waiting for more. Something was opened or started and never finished, so the query is cut off from Postgres's point of view.
Why it happens
- A parenthesis that was opened but never closed.
- A condition that ends with AND, OR or a comma, often after commenting out the last line.
- A WITH (CTE) block with no SELECT after it.
- Running only part of a query, for example when just some lines were selected in your editor. With a semicolon at the end, these same mistakes show up as syntax error at or near ";" instead.
How to fix it
1. Close the parenthesis
Fails
SELECT name, country
FROM customers
WHERE country IN ('Canada', 'USA'Works
SELECT name, country
FROM customers
WHERE country IN ('Canada', 'USA');Count the opening and closing parentheses, especially in IN lists, function calls and subqueries.
2. Finish or remove the last condition
Fails
SELECT id, amount FROM orders WHERE status = 'completed' AND -- amount > 100
Works
SELECT id, amount FROM orders WHERE status = 'completed'; -- AND amount > 100
Commenting out the last condition leaves the AND behind with nothing after it. Starting each condition line with AND makes lines safe to comment out.
3. Add the final SELECT after WITH
Fails
WITH customer_totals AS ( SELECT customer_id, SUM(amount) AS total FROM orders GROUP BY customer_id )
Works
WITH customer_totals AS ( SELECT customer_id, SUM(amount) AS total FROM orders GROUP BY customer_id ) SELECT customer_id, total FROM customer_totals WHERE total > 200;
A CTE only defines a named result. It does nothing on its own until a SELECT (or UPDATE, DELETE, INSERT) after it uses it.
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.
Practice so it doesn't happen in an interview
- North American customers who stayedOR · NOT · parentheses
- First-week shipmentsIN · BETWEEN
- Days to first purchaseCTE · MIN · date math