SQL unbalanced parentheses: missing right parenthesis

Every ( in a SQL statement needs a matching ): function calls, IN lists, subqueries, column definitions. When one is missing, the database keeps reading the rest of the statement as if it were inside the parentheses and fails at the first keyword that cannot appear there, or at the end of the input. Database messages rarely say which bracket is open; PasteKit points at the exact one.

Seen as:

  • ORA-00907: missing right parenthesis
  • ERROR: syntax error at or near "AS"
  • ERROR: syntax error at end of input
  • Msg 102, Level 15, State 1, Line 7 Incorrect syntax near ')'.
  • ERROR 1064 (42000): 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 'AS orders FROM orders GROUP BY customer_id' at line 1

Input

Settings

History

Load from URL

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.

Before
SELECT customer_id, COUNT(order_id AS orders FROM orders GROUP BY customer_id;
After
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.

Before
SELECT id FROM orders WHERE status IN ('paid', 'shipped' ORDER BY id;
After
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.

Before
SELECT name FROM users WHERE id IN (SELECT user_id FROM orders WHERE total > 100;
After
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.

Before
SELECT COUNT(*)) FROM orders;
After
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.

Before
CREATE TABLE customers (id INT PRIMARY KEY, name VARCHAR(100);
After
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", or at end of input if the text runs out.
  • SQLite: near "ORDER": syntax error, or incomplete input if the text runs out.
  • MySQL and MariaDB: ERROR 1064, with near '...' quoting the text from the problem onwards. An empty near '' means the end of the statement.
  • SQL Server: Incorrect syntax near the keyword 'ORDER'. or Incorrect syntax near ')'.
  • Oracle: ORA-00907: missing right parenthesis when it needed a ), and the reverse, ORA-00906: missing left parenthesis, when it required an opening bracket, as after VALUES in 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.

Related