SQL Formatter · Tutorial
How to make a long SQL query readable
5 min readbeginnerUpdated
Reporting queries copied from a dashboard or log are often a single line. You will format a PostgreSQL query with a CTE, three joins and two window functions so you can see what each part does.
What you need
- The SQL Formatter
- A long query, or the example monthly revenue report
Steps
Paste the query and pick the dialect
Load the example and set Dialect to PostgreSQL, because the query uses
date_trunc,now()and an interval literal.Read the CTE
The
WITH monthly AS (...)block is now indented on its own, with its joins and filters on separate lines. That is the part that sums revenue per month and category.WITH monthly AS ( SELECT DATE_TRUNC('month', o.created_at) AS sales_month,Follow the window functions
In the final SELECT, the share of each month's revenue and the change since the previous month each sit on their own line, so the
OVER (...)clauses are easy to compare.Match your team's style
Switch Keywords to lower case or move AND / OR to the end of lines if your team prefers, then copy the query into your editor or a review.
Try it yourself
Opens the SQL Formatter with this tutorial's sample loaded.
Common mistakes
- Leaving the dialect on Standard SQL
- Some database-specific syntax isn't understood in Standard SQL and causes an error. Pick your database first.
- Pasting results along with the query
- Copy only the SQL. Extra text such as a result table or a prompt like
postgres=#stops the query being read. - Expecting performance changes
- Formatting changes layout only. To speed up a query, look at its plan with EXPLAIN in your database.
Next steps
Go back to the SQL Formatter, or keep going with one of these: