What gets formatted
SQL arrives unreadable in predictable places: Hibernate and ActiveRecord logs, slow-query logs, pg_stat_statements, BI tools that generate 300-character SELECT lists, and migration files nobody has touched since they were written. This page lays out SELECT, INSERT, UPDATE, DELETE, MERGE, DDL and CTEs one clause per line, indents subqueries and CASE expressions, and keeps short parenthesised expressions on one line. Bind placeholders such as ?, $1 and :name are left in place, so a query from a log can be formatted without filling in its values.
Layout is produced by the sql-formatter library. Before it runs, PasteKit’s own tokenizer checks for the mistakes that most often break a query in transit: a string literal with no closing quote, an unclosed /* comment, unbalanced parentheses, and a statement that stops after a keyword such as WHERE or AND, which usually means a log line was cut off. These are reported with the exact line and column.
The checker is lexical, not a database. It does not know whether a column exists, and it does not parse the grammar in full, so a trailing comma before FROM is formatted without complaint and only fails when the query runs. Formatting it does put the comma at the end of its own line, where it is easy to see.
Choose the right dialect
Databases disagree about basic lexical rules, so the Dialect option matters more than it looks:
- Backticks quote identifiers in MySQL, MariaDB, BigQuery and Spark, but are not valid in SQL Server, where
[brackets]are used. 'it\'s'is a valid string in MySQL. In PostgreSQL the backslash is ordinary text, so the same input is reported as an unclosed string; write'it''s'there.$1,?,:nameand@nameplaceholders belong to different drivers and databases.- PostgreSQL and Snowflake allow dollar-quoted bodies (
$$ ... $$); Oracle hasq'[...]'strings.
With Standard SQL selected, T-SQL brackets or MySQL backticks raise a warning that suggests a dialect, and the query still formats. Text the chosen dialect cannot read at all is reported as "..." is not valid Standard SQL syntax. Each database has its own page with specifics: MySQL, PostgreSQL, SQL Server T-SQL, Oracle PL/SQL, SQLite, BigQuery and Snowflake, among others.
Style options
- Keyword case: UPPER (
SELECT), lower or As written. Data types follow the same setting. - Function case: As written, UPPER (
COUNT(*)) or lower. Kept separate because many teams uppercase keywords but not functions. - Indent style: Standard puts each clause on its own line with the body indented below it. Tabular, left-aligned and Tabular, right-aligned put the clause keyword in a fixed-width column with its content beside it, the “river” style some SQL style guides prefer.
- Commas: Trailing or Leading (
, customer_idat the start of each line). Leading commas make it easy to comment out the last column; sql-formatter itself has no such option, so PasteKit rewrites the output without touching commas inside strings or comments. - AND / OR: put logical operators at the Start of line or End of line.
- Blank lines between statements: 0 to 5 empty lines between queries in a script.
Indent size and line width are shared with other formats; the line width also decides how long a parenthesised expression can be before it is broken across lines. For conventions behind these choices, see the SQL style guide.
Keys and minifying
Ctrl/Cmd+Enter formats and Ctrl/Cmd+Shift+M minifies: comments and line breaks are removed, but strings, quoted identifiers, optimizer hints (/*+ ... */) and MySQL /*! ... */ comments are kept. Ctrl/Cmd+Shift+C copies, and Ctrl/Cmd+K opens the command palette. Queries copied from production logs can contain customer emails and IDs; the formatter runs inside your browser, so they stay with you.
Examples
Hibernate query from a debug log
Generated aliases and ? bind placeholders survive untouched, while each selected column and each WHERE condition gets its own line.
select order0_.id as id1_3_, order0_.customer_id as customer2_3_, order0_.placed_at as placed_a3_3_, order0_.status as status4_3_, customer1_.email as email2_1_ from orders order0_ inner join customers customer1_ on order0_.customer_id=customer1_.id where order0_.status=? and order0_.placed_at>=? order by order0_.placed_at desc limit ?SELECT
order0_.id AS id1_3_,
order0_.customer_id AS customer2_3_,
order0_.placed_at AS placed_a3_3_,
order0_.status AS status4_3_,
customer1_.email AS email2_1_
FROM
orders order0_
INNER JOIN customers customer1_ ON order0_.customer_id = customer1_.id
WHERE
order0_.status = ?
AND order0_.placed_at >= ?
ORDER BY
order0_.placed_at DESC
LIMIT
?
SQL Server report with bracketed names
With the T-SQL dialect, bracketed names containing spaces, @ variables and N-prefixed strings are read correctly, and SUM is uppercased by the function case option.
select top (20) o.[OrderID], c.[CompanyName], sum(d.[UnitPrice]*d.[Quantity]) as [Revenue] from [dbo].[Orders] o join [dbo].[Order Details] d on d.[OrderID]=o.[OrderID] join [dbo].[Customers] c on c.[CustomerID]=o.[CustomerID] where o.[OrderDate]>=@from and o.[ShipCountry]=N'Singapore' group by o.[OrderID], c.[CompanyName] order by [Revenue] desc option (recompile);SELECT
TOP (20) o.[OrderID],
c.[CompanyName],
SUM(d.[UnitPrice] * d.[Quantity]) AS [Revenue]
FROM
[dbo].[Orders] o
JOIN [dbo].[Order Details] d ON d.[OrderID] = o.[OrderID]
JOIN [dbo].[Customers] c ON c.[CustomerID] = o.[CustomerID]
WHERE
o.[OrderDate] >= @from
AND o.[ShipCountry] = N'Singapore'
GROUP BY
o.[OrderID],
c.[CompanyName]
ORDER BY
[Revenue] DESC
OPTION
(recompile);
PostgreSQL JSONB query over webhook events
The ->>, ::, @> and FILTER syntax is specific to PostgreSQL. The dialect setting keeps each operator intact and splits the window function across lines.
select id, payload->>'email' as email, created_at::date as event_date, count(*) filter (where payload->>'status'='failed') over (partition by payload->>'email') as failures from webhook_events where created_at>=now()-interval '7 days' and payload @> '{"type":"invoice.payment_failed"}'::jsonb order by created_at desc;SELECT
id,
payload ->> 'email' AS email,
created_at::date AS event_date,
COUNT(*) FILTER (
WHERE
payload ->> 'status' = 'failed'
) OVER (
PARTITION BY
payload ->> 'email'
) AS failures
FROM
webhook_events
WHERE
created_at >= NOW() - INTERVAL '7 days'
AND payload @> '{"type":"invoice.payment_failed"}'::JSONB
ORDER BY
created_at DESC;
Analytics CTE in lower case with leading commas
A common dbt house style: each CTE is indented as its own query, keywords are lower case and column lists start with commas.
with monthly as (select date_trunc('month', placed_at) as month, customer_id, sum(total) as spend from orders where status = 'paid' group by 1, 2), ranked as (select month, customer_id, spend, rank() over (partition by month order by spend desc) as rnk from monthly) select month, customer_id, spend from ranked where rnk <= 3 order by month, rnk;with
monthly as (
select
date_trunc('month', placed_at) as month
, customer_id
, sum(total) as spend
from
orders
where
status = 'paid'
group by
1
, 2
)
, ranked as (
select
month
, customer_id
, spend
, rank() over (
partition by
month
order by
spend desc
) as rnk
from
monthly
)
select
month
, customer_id
, spend
from
ranked
where
rnk <= 3
order by
month
, rnk;
Common errors and how to fix them
| Error | Cause | Fix |
|---|---|---|
This string is never closed — the ' has no matching 'Explained | A quote inside a value, such as O’Brien, ended the string early, or the query was cut off mid-literal. PostgreSQL itself reports this as: unterminated quoted string at or near. | Double the inner quote (‘O’‘Brien’). In MySQL, ' also works if you choose the MySQL dialect. |
This '(' is never closedExplained | A subquery, function call or IN list is missing its closing parenthesis, often after editing a long WHERE clause. | Add the missing ) where the expression ends; the position points at the opening bracket that has no partner. |
Unexpected ')' — there is no matching '(' before itExplained | An extra closing parenthesis, frequently left behind after deleting a function wrapper such as COALESCE(. | Remove the stray ) or restore the opening part of the expression. |
The statement ends with "WHERE" but nothing follows it | The query stops straight after a keyword. Logs that cap line length and truncated copies from a monitoring tool are the usual source. | Copy the complete statement again, or add the missing condition. |
Bracketed names like [id] are T-SQL syntax, not Standard SQL | A warning rather than an error: the query uses SQL Server quoting while the Dialect is set to Standard SQL. It still formats. | Pick the matching Dialect, for example T-SQL (SQL Server), which understands its quoting and variables. |
ERROR: syntax error at or near "FROM" | Reported by PostgreSQL, not by this page, and often caused by a trailing comma after the last selected column. MySQL shows ERROR 1064 (42000) and SQL Server shows Incorrect syntax near the keyword ‘FROM’. | Format the query and look at the end of the SELECT list, where the extra comma sits alone at the end of its line. Remove it. |
Frequently asked questions
Does the SQL formatter change what my query does?
No. Only whitespace, line breaks and the case of keywords and functions change. Strings, quoted identifiers and comments are left as they are, so the formatted query runs exactly like the original.
How do I format SQL in SQL Server Management Studio or DBeaver?
DBeaver has Format > Format SQL (Ctrl+Shift+F). SSMS has historically shipped without a T-SQL formatter, so people use extensions or paste into a tool like this one with the T-SQL dialect selected.
Can it validate my SQL?
It catches lexical problems (unclosed strings and comments, unbalanced brackets), statements that stop after a keyword, and text the chosen dialect cannot read. It does not know your schema, so a misspelt table or column passes; run EXPLAIN against a test database for that.
Can I format a query that still has ? or $1 placeholders?
Yes. Bind placeholders are kept exactly where they are, so an ORM log line formats without substituting real values. Choose the dialect that matches your database so its placeholder style is read correctly.
Is my query sent to a server?
No. Formatting runs in your browser, so production queries with real customer values never leave your machine.
Should SQL keywords be uppercase?
Databases do not care. Uppercase keywords remain the most common convention because they separate keywords from identifiers at a glance, but lowercase is popular in dbt and analytics code; pick one and apply it consistently.