Skip to main content
C
CodeUtil

SQL Formatting Best Practices for Readable Queries

Learn SQL formatting conventions that make your queries easier to read, maintain, and debug. Covers indentation, keyword casing, JOIN formatting, subqueries, and establishing team standards.

2025-03-2012 min
Related toolSQL Formatter

Use the tool alongside this guide for hands-on practice.

The query that changed how I write SQL

SQL formatting is one of those things I never thought about until I had to review someone else's 200-line query. Unformatted SQL is basically unreadable - I've stared at nested subqueries for 20 minutes before realizing there was a missing JOIN.

Now I'm religious about formatting. At Šikulovi s.r.o., I've gotten our team to adopt consistent standards, and it's made code reviews actually possible. Here's everything I've learned about making SQL readable.

What bad SQL costs you

I used to think formatting was cosmetic. Then I spent 3 hours debugging a query only to find I'd duplicated a JOIN condition. With proper formatting, I'd have seen it in seconds.

  • Debugging takes 5x longer when you cannot see the query structure
  • Code reviews become rubber-stamping because nobody wants to trace through the mess
  • Merge conflicts everywhere when everyone formats differently
  • New team members take weeks longer to understand existing queries
  • Copy-paste errors hide in the chaos - missing WHERE clauses, duplicated conditions
  • Performance issues lurk in unreadable subqueries

The great keyword casing debate

UPPERCASE or lowercase? Here's the thing: it genuinely does not matter which you pick. What matters is picking one and sticking to it.

  • UPPERCASE (SELECT, FROM, WHERE): Traditional, makes keywords pop out
  • lowercase: Modern feel, less visual noise, works well with camelCase columns
  • Mixed case: Never do this. Just... no.
  • I use UPPERCASE because that is what I learned, but plenty of good teams use lowercase
  • The real key: automated formatters enforce your choice, so pick one and move on

Line breaks: where the magic happens

This is where formatting actually matters. Every major clause on its own line. Period.

  • SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY on separate lines
  • Short queries (under 80 characters) may stay on one line
  • Complex WHERE conditions benefit from one condition per line
  • Keep related parts together: column with its alias, table with its alias
  • Blank lines can separate logical sections in very long queries
  • Consistent line length (80-120 characters) prevents horizontal scrolling
  • Right-align keywords for visual alignment (optional, controversial)

Leading commas: the controversial choice I stand by

Most people put commas at the end of lines. I put them at the start. Here is why:

  • Comment out a column? Just comment one line. No trailing comma error.
  • See all your columns lined up? The commas create a visual guide
  • Trailing commas at end of list: syntax error. Leading commas: works fine
  • Yes, it looks weird at first. Give it a week.
  • That said, trailing commas are fine if your whole team uses them consistently

JOINs: where queries go to die

I've seen production queries with 15 JOINs. Formatting is the only thing that makes these survivable.

  • ALWAYS use explicit JOIN syntax (INNER JOIN, LEFT JOIN) - never comma-separated tables in FROM
  • Each JOIN on its own line, ON condition indented below
  • LEFT JOIN or INNER JOIN explicitly - never just JOIN (defaults vary by database)
  • Multiple join conditions: AND at the start of each new line
  • Table aliases are mandatory. orders AS o, customers AS c
  • Meaningful aliases in complex queries - ord, cust - not just single letters

CTEs: your secret weapon

Common Table Expressions changed how I write SQL. When a query gets complex, I reach for WITH clauses instead of nested subqueries.

  • WITH at the top, each CTE named descriptively
  • filtered_orders, active_customers - names that explain what the CTE does
  • Each CTE is a self-contained query - format it like you would any query
  • Blank line between CTEs for visual separation
  • The final SELECT references CTEs by name - suddenly your 100-line query is readable
  • If you are nesting subqueries more than 2 levels, switch to CTEs

DELETE and UPDATE: format like your job depends on it

Because it might. I once saw a DELETE without WHERE that wiped a production table. The WHERE was there - just hidden at the end of a long line nobody read.

  • DELETE FROM on first line, WHERE prominently on its own line
  • No WHERE clause? Add a comment: -- Intentionally deleting all records
  • UPDATE: SET on its own line, one assignment per line
  • Always run SELECT first with the same WHERE to verify what you are about to change
  • Format these statements so the scope of destruction is obvious at a glance

Get a formatter and enforce it

Manual formatting is a waste of time. I format on save and never think about it.

  • sqlfluff: My go-to for CI/CD integration, very configurable
  • Editor plugins: VS Code, IntelliJ - format on save
  • Pre-commit hooks: Nobody commits unformatted SQL
  • I built the SQL Formatter on this site for quick formatting when I am working in a browser
  • Store your formatter config in the repo so everyone uses the same settings

What I actually use day-to-day

After years of tweaking, here is my actual style:

  • UPPERCASE keywords (habit from learning SQL years ago)
  • Leading commas (controversial but I love it)
  • 2-space indentation (matches our codebase)
  • One column per line in SELECT for anything over 3 columns
  • CTEs for anything with nested subqueries
  • Explicit ASC/DESC always - I do not trust defaults
  • Comments for any WHERE condition that is not obvious

The bottom line

Your SQL formatting does not have to match mine. What matters is that your team picks a style and enforces it automatically. The debates about uppercase vs lowercase, leading vs trailing commas - just make a decision and move on.

Get a formatter, configure it once, add it to pre-commit hooks, and never think about it again. Future you will be grateful.

FAQ

Should SQL keywords be uppercase or lowercase?

Honestly, it does not matter. Pick one and stick with it. I use UPPERCASE out of habit, but lowercase is fine too. Just be consistent across your codebase.

Where should I put commas in SQL - at the start or end of lines?

I prefer leading commas because commenting out a column is cleaner. But trailing commas work fine too. The important thing is that everyone on your team does the same thing.

How should I format complex JOIN conditions?

Each JOIN on its own line, ON condition indented below, AND conditions on separate lines starting with AND. Always use explicit JOIN syntax - never comma-separated tables in the FROM clause.

When should I use CTEs instead of subqueries?

Whenever nesting gets more than 2 levels deep, or when you need to reference the same subquery multiple times. CTEs make complex queries readable by giving each piece a name.

What SQL formatter tool should I use?

sqlfluff for CI/CD, your editor's built-in formatter for daily work, and the SQL Formatter on this site when you're working in a browser. Whatever you pick, add it to pre-commit hooks.

How do I enforce SQL formatting in a team?

Automate it. Pick a formatter, configure it, add it to pre-commit hooks. Nobody should have to think about formatting - it should just happen.

Martin Šikula

Founder of CodeUtil. Web developer building tools I actually use. When I'm not coding, I experiment with productivity techniques (with mixed success).

Related articles