DEV Community

Varun Krishnan
Varun Krishnan

Posted on Originally published at dbdiagramr.space

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

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](https://www.dbdiagramr.space/sql-formatter) formats PostgreSQL in your browser. Uppercase or lowercase keywords, 2 or 4 space indent, copy or download. Nothing is uploaded.
Enter fullscreen mode Exit fullscreen mode

What "formatted" actually means

Take this real-world log line:
Enter fullscreen mode Exit fullscreen mode
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;
Enter fullscreen mode Exit fullscreen mode
Formatted:
Enter fullscreen mode Exit fullscreen mode
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;
Enter fullscreen mode Exit fullscreen mode
Same query. The second version shows the misplaced JOIN or wrong GROUP BY in seconds; the first hides it.
Enter fullscreen mode Exit fullscreen mode

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.
Enter fullscreen mode Exit fullscreen mode

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](https://www.dbdiagramr.space/visualize).
Enter fullscreen mode Exit fullscreen mode

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.
Enter fullscreen mode Exit fullscreen mode

Top comments (0)