← All posts
·4 min read
#postgres#database#tutorial

How to Format SQL in PostgreSQL: Styles, Tools, and Team Standards

Messy single-line SQL slows everyone down. How to format PostgreSQL properly, which style to pick, and a free formatter that runs in your browser.

The short version

Unformatted SQL — a 400-character single line from your logs, an ORM dump with random indentation — slows down everyone who reads it. Formatting is a solved problem: paste it into a formatter, pick a style, move on.

dbdiagramr's free SQL formatter formats PostgreSQL in your browser. Uppercase or lowercase keywords, 2 or 4 space indent, copy or download. Nothing is uploaded.

What "formatted" actually means

Take this real-world log line:

select u.email, count(p.id) as post_count from users u left join posts p on p.user_id = u.id where u.created_at > now() - interval '30 days' group by u.email order by post_count desc limit 20;

Formatted:

SELECT
  u.email,
  count(p.id) AS post_count
FROM
  users u
  LEFT JOIN posts p ON p.user_id = u.id
WHERE
  u.created_at > now() - interval '30 days'
GROUP BY
  u.email
ORDER BY
  post_count DESC
LIMIT
  20;

Same query. The second version shows the misplaced JOIN or wrong GROUP BY in seconds; the first hides it.

Uppercase vs lowercase keywords

There is no technical difference — Postgres parses both identically. It is purely culture:

  • UPPERCASE — traditional DBA style, SQL Server and Oracle shops, certification materials. Keywords visually pop against table names.
  • lowercase — modern analytics style (dbt, Postgres-first teams). Less shouting, easier to type.

Pick the one that matches your codebase and enforce it with a formatter, not a style doc nobody reads.

Where formatting pays off most

  • Migration PRs — formatted DDL diffs review in minutes; single-line dumps review never.
  • Log triage — paste the slow query from pg_stat_statements or your app logs and read it.
  • Onboarding — new hires can read the schema migrations as documentation.
  • Before diagramming — clean SQL is easier to sanity-check before you visualize it as an ER diagram.

FAQ

Does formatting change what my query does?
No. A formatter only changes whitespace and keyword casing. Same semantics, better manners.

Can I format SELECT queries or only DDL?
Both — SELECTs, CTEs, JOINs, migrations, anything valid PostgreSQL.

Is my SQL sent to a server?
Not with dbdiagramr's formatter — it runs entirely in your browser.

Visualize your own database

Paste your PostgreSQL connection string and get an interactive ER diagram in under 10 seconds. No signup required.

Related guides

Try it on your database