How to Format SQL Queries
March 22, 2026 · 4 min read
Unformatted SQL is hard to read, hard to debug, and hard to maintain. Whether you're pulling a query from a log file, inheriting someone else's code, or building a complex join, proper formatting makes a huge difference.
This guide covers the key principles of SQL formatting and shows you how to clean up any query — manually or with a free SQL formatter.
Why Format SQL?
Consider this query:
It works, but good luck finding a bug in it. Now compare the formatted version:
Same query, but now you can instantly see which columns are selected, which tables are joined, and what the conditions are.
SQL Formatting Rules
1. Major Keywords on New Lines
Each major SQL clause should start on a new line:
- SELECT
- FROM
- WHERE
- JOIN / INNER JOIN / LEFT JOIN
- GROUP BY
- HAVING
- ORDER BY
- LIMIT
2. Indent Column Lists and Conditions
Columns in SELECT, conditions in WHERE, and join conditions should be indented under their keyword:
3. Uppercase Keywords
A common convention is to write SQL keywords in UPPERCASE and table/column names in lowercase:
4. One Column Per Line in SELECT
When selecting multiple columns, put each on its own line. This makes diffs cleaner and makes it easy to comment out individual columns during debugging.
5. Align JOINs Consistently
6. Use Subquery Indentation
Format SQL Instantly
Don't want to format by hand? Paste your SQL into the UtilShed SQL Formatter and get clean, readable output in one click.
Paste messy SQL, get properly indented and formatted output.
Open SQL FormatterSQL Formatting in Your Editor
VS Code
Install the SQL Formatter extension (by adpyke). Right-click any SQL file and select "Format Document" or use Shift+Alt+F.
JetBrains (IntelliJ, DataGrip)
Built-in: Ctrl+Alt+L (or Cmd+Alt+L on Mac) formats SQL in any .sql file or SQL console.
Command Line
SQL Style Guides
If your team doesn't have a SQL style guide, consider adopting one of these:
- Simon Holywell's SQL Style Guide — widely referenced, covers naming, indentation, and alignment
- GitLab SQL Style Guide — practical, battle-tested at scale
- Kickstarter SQL Style Guide — concise and opinionated
The most important rule: pick a style and be consistent. Formatted SQL is easier to read, review, and debug.
Related Tools
- SQL Formatter — format and beautify SQL queries online
- JSON Formatter — format JSON data with syntax highlighting
- CSS Minifier — minify CSS for production
- JavaScript Beautifier — format and indent JavaScript code