Common causes
1. A function call missing its closing parenthesis
In COUNT(order_id AS orders the alias ends up inside the call. Close the call before the alias. PostgreSQL and SQLite both name AS as the problem, which is the token after the missing bracket.
SELECT customer_id, COUNT(order_id AS orders FROM orders GROUP BY customer_id;SELECT customer_id, COUNT(order_id) AS orders FROM orders GROUP BY customer_id;2. An IN list that is never closed
Long value lists, often generated or pasted, lose their final ). The next clause (GROUP BY, ORDER BY) is then read as part of the list.
SELECT id FROM orders WHERE status IN ('paid', 'shipped' ORDER BY id;SELECT id FROM orders WHERE status IN ('paid', 'shipped') ORDER BY id;3. A subquery missing its parenthesis
PostgreSQL reports syntax error at or near ";" when a semicolon arrives inside an open subquery, and syntax error at end of input when the text simply stops there. Count the brackets of each nested SELECT.
SELECT name FROM users WHERE id IN (SELECT user_id FROM orders WHERE total > 100;SELECT name FROM users WHERE id IN (SELECT user_id FROM orders WHERE total > 100);4. One closing parenthesis too many
An extra ) gives “Incorrect syntax near ‘)’” in SQL Server and syntax error at or near ")" in PostgreSQL. In Oracle the code depends on where it sits; ORA-00933 “SQL command not properly ended” is a common one. Remove the bracket.
SELECT COUNT(*)) FROM orders;SELECT COUNT(*) FROM orders;5. A CREATE TABLE left open
Column lists are long and nested, because types such as VARCHAR2(100) have brackets of their own. Losing the last ) is easy, and this is one of the most common places to meet ORA-00907.
CREATE TABLE customers (id INT PRIMARY KEY, name VARCHAR(100);CREATE TABLE customers (id INT PRIMARY KEY, name VARCHAR(100));Read the error as "the token after the gap"
Most databases have no error called “unbalanced parentheses”. They parse until a token cannot continue the expression, and name that token. So the bracket is missing somewhere before the word in the message:
- PostgreSQL:
syntax error at or near "ORDER", orat end of inputif the text runs out. - SQLite:
near "ORDER": syntax error, orincomplete inputif the text runs out. - MySQL and MariaDB:
ERROR 1064, withnear '...'quoting the text from the problem onwards. An emptynear ''means the end of the statement. - SQL Server:
Incorrect syntax near the keyword 'ORDER'.orIncorrect syntax near ')'. - Oracle:
ORA-00907: missing right parenthesiswhen it needed a), and the reverse,ORA-00906: missing left parenthesis, when it required an opening bracket, as afterVALUESin an INSERT.
Databases stop at the first problem. The sample on this page has two unclosed brackets, and PostgreSQL only reports the first one: syntax error at or near "AS".
Finding the bracket in a long statement
Reformatting comes first. With one clause per line and nested parts indented, an unclosed bracket shows up as indentation that never returns. PasteKit’s SQL formatter refuses to format unbalanced SQL and reports the line and column of the bracket instead. It ignores brackets inside strings and comments, and it reports one at a time, so fix that one and run it again.
In psql, watch the prompt. If it changes to mydb(#, you are inside an unclosed parenthesis, and psql will not send the statement even if you type a semicolon.
For a generated statement in a log, a few lines of Python do the counting while skipping strings and comments:
import re
TOKEN = re.compile(r"--[^\n]*|/\*.*?\*/|'[^']*'|\"[^\"]*\"|[()]", re.S)
def unbalanced(sql):
stack = []
for match in TOKEN.finditer(sql):
line = sql.count("\n", 0, match.start()) + 1
if match[0] == "(":
stack.append(line)
elif match[0] == ")":
if not stack:
return f"extra ) on line {line}"
stack.pop()
return f"( never closed, opened on lines {stack}" if stack else "balanced"
For this page’s sample it returns lines 2 and 5. It does not understand MySQL backslash escapes, PostgreSQL dollar quoting or Oracle q'[...]' strings, so treat a surprising result with suspicion.
Preventing it in generated SQL
Most long unbalanced statements are built by code. Two habits remove the problem at the source:
- Bind the list instead of formatting it. In psycopg,
WHERE id = ANY(%s)takes a Python list as one parameter. In SQLAlchemy,bindparam("ids", expanding=True)expands an IN list for you. That also closes the SQL injection hole a joined string leaves open. - Build conditions with a query builder. Dynamic filters that open a bracket in one branch and close it in another are where these errors tend to hide.
For SQL in version control, run a linter in CI. sqlfluff lint --dialect postgres queries/ reports parse failures with the line and position, and its dialect setting helps with engine-specific syntax. Keeping to one clause per line, as in the SQL style guide, also makes an unclosed bracket obvious in a diff.
Frequently asked questions
Does ORA-00907 always mean a parenthesis is missing?
No. Oracle raises it whenever it expected ) and found something else, for example a misplaced keyword in a column definition (such as NOT NULL before DEFAULT) or an ORDER BY inside an IN subquery. Check that the parentheses balance first, then the syntax inside them.
How do I find the unclosed parenthesis in a long query?
Format it: with one clause per line and nested parts indented, an unclosed bracket stands out. PasteKit refuses to format unbalanced SQL and highlights the bracket that has no partner instead.
Can quotes cause bracket errors?
Yes. An unclosed string hides every bracket after it, which can make balanced SQL look unbalanced. See unterminated quoted strings.
Why does PostgreSQL say "syntax error at end of input"?
The statement ended while the parser still wanted more, usually because a bracket or a clause was left unfinished. An ORM or driver that builds the text may have cut it off, so log the final SQL it sent.