SQL Formatter for PostgreSQL
PostgreSQL has one of the richest SQL dialects. ::type casting, RETURNING clauses, JSONB operators like ->, window functions, recursive CTEs — powerful but syntactically dense.
This PostgreSQL SQL formatter is tuned for the Postgres dialect. It preserves cast operators, formats RETURNING clauses cleanly, and handles CTEs without turning them into an indentation disaster.
Why PostgreSQL-Specific Formatting
PostgreSQL differs from standard SQL in ways that affect formatting:
::type casting operators need no space around them — adding one breaks the syntaxRETURNING clauses should stay visually connected to their DML statement- JSONB path expressions like
data->'key'->>0 should not be split across lines - Recursive CTEs need clear visual separation between anchor and recursive members
Generic formatters often add spaces around :: operators. The PostgreSQL dialect avoids this.
PostgreSQL Formatting Examples
Recursive CTE — Before
WITH RECURSIVE subordinates AS (SELECT id,name,manager_id FROM employees WHERE id=1 UNION ALL SELECT e.id,e.name,e.manager_id FROM employees e INNER JOIN subordinates s ON s.id=e.manager_id) SELECT * FROM subordinates;
After (PostgreSQL, 4 spaces)
WITH RECURSIVE subordinates AS (
SELECT id, name, manager_id FROM employees WHERE id = 1
UNION ALL
SELECT e.id, e.name, e.manager_id
FROM employees e
INNER JOIN subordinates s ON s.id = e.manager_id
)
SELECT * FROM subordinates;
The recursive CTE structure is now visible — anchor query on top, recursive member below, final SELECT at the bottom.
Practical Tips for Postgres Users
Format pg_dump output
pg_dump --schema-only output is functional but ugly. Formatting it section by section — tables, indexes, functions — makes reviewing database changes much easier.
Audit JSONB queries
When working with JSONB-heavy queries, format the SQL first, then trace the path expressions to verify they target the right nested keys. Clean formatting makes this kind of auditing practical.
💡 Pro tip: If you use psql with \x auto for expanded display, formatted queries are much easier to align with the expanded output format.
Frequently Asked Questions
Does it handle ::type casting correctly?
Yes. The PostgreSQL dialect preserves ::text, ::integer, and other cast operators without adding spaces around the ::.
What about PL/pgSQL functions?
The formatter handles CREATE FUNCTION blocks with LANGUAGE plpgsql and preserves $$ dollar-quoted function bodies.