Formatting SQL Parentheses: Boolean Logic Precedence and Readability
By Sharon Ben-Moshe · October 12, 2026 · 1 min read
Sharon Ben-Moshe is the founder of sqlfmt, a browser-based SQL formatter and validator with misspelled-keyword suggestions across PostgreSQL, MySQL, SQLite, SQL Server, and BigQuery.
Format complex parentheses and boolean logic in SQL WHERE clauses. Prevent AND/OR operator precedence bugs with clear visual indentation.
Quick answer
In SQL boolean logic, the AND operator has higher operator precedence than OR (AND binds tighter, like multiplication over addition). To prevent critical query logic bugs and maintain readability, format every compound OR expression inside explicit, indented parentheses with opening and closing parentheses aligned vertically.
FAQs
Why does 'A OR B AND C' produce unexpected results?
Because AND takes precedence over OR, the expression evaluates as `A OR (B AND C)`. If a developer intended `(A OR B) AND C`, rows matching A will be returned regardless of whether C is true, exposing sensitive or unverified records.
How should nested parentheses be indented in SQL?
Place the opening parenthesis at the end of the clause or on a new line, indent the enclosed expressions by 2 spaces, and place the closing parenthesis on its own line matching the indentation of the initiating clause.
Does adding redundant parentheses harm query performance?
No. The SQL optimizer builds an abstract syntax tree and evaluates logical truth conditions; parentheses clarify parsing and have zero performance penalty.
How does NOT interact with AND and OR?
The NOT operator has the highest precedence of the three (`NOT > AND > OR`). Always wrap negated compound expressions in explicit parentheses: `NOT (status = 'closed' OR status = 'archived')`.
Keep reading
Building an Enterprise SQL Style Guide: Formatting Standards, Linting, and Team Conventions
By Sharon Ben-Moshe · Oct 13, 2026
The complete blueprint for an enterprise SQL style guide. Standardize formatting, keyword casing, indentation, naming conventions, and CI linting.
Read postThe Master Guide to SQL Common Table Expressions (CTEs): Syntax, Optimization Fences, and Recursion
By Sharon Ben-Moshe · Oct 13, 2026
The definitive guide to SQL Common Table Expressions (CTEs). Master chaining, recursive hierarchies, data-modifying CTEs, and optimization fences.
Read postTry it now
Paste your SQL into sqlfmt — format, validate, and catch typos free in your browser.