What does the SQL Formatter & Query Beautifier do?
The SQL Formatter & Query Beautifier parses dense, unformatted, or minified SQL statements and formats them into structured multiline code. It applies uniform keyword casing (UPPERCASE, lowercase, or unchanged), aligns compound clauses (LEFT JOIN, GROUP BY, ORDER BY), and indents nested query statements across MySQL, PostgreSQL, Microsoft SQL Server (T-SQL), SQLite, and Oracle databases.
Core Concepts
Understanding SQL query formatting and clause alignment:
- Clause-Level Line Splitting: Breaks queries onto distinct lines at major structural clauses (
FROM,WHERE,JOIN,HAVING,LIMIT). - Compound Clause Preservation: Protects multi-word SQL clauses (such as
LEFT OUTER JOIN,ON DUPLICATE KEY UPDATE, andCROSS APPLY) from premature line breaks. - Dialect Keyword Standardization: Applies dialect-specific keyword casing rules for PostgreSQL (
RETURNING,ILIKE), MySQL (STRAIGHT_JOIN), Oracle (ROWNUM,CONNECT BY), and MSSQL (CROSS APPLY).
How to use the tool?
- Paste SQL Query: Enter or paste your raw SQL statement into the input editor or click Load Sample.
- Configure Dialect & Formatting:
- Choose your target SQL Dialect (Standard ANSI SQL, MySQL, PostgreSQL, MSSQL, Oracle, or SQLite).
- Select Keyword Case (UPPERCASE or lowercase) and Indentation (2 or 4 spaces).
- Format & Copy: Click Format & Beautify SQL, then click Copy or Download to export the beautified query.
Related Developer Utilities
If you work with database queries, API schemas, and structured data formats, explore these complementary tools:
- SQL Parameter Unbinder: Hydrate parameterized SQL log queries (?, $1, :name) with variable values.
- JSON Formatter: Format and validate structured JSON documents.
- JSON Syntax Validator: Validate JSON payloads and locate syntax errors.
- CSV Formatter: Clean and format tabular CSV data.
REST API Integration
Blueutils provides a free REST API endpoint (POST https://blueutils.com/api/sql/sql-formatter) to programmatically format, indent, and beautify SQL queries across MySQL, PostgreSQL, MSSQL, SQLite, and Oracle databases.
API Request Parameters
| Name | Type | Description | Example |
|---|---|---|---|
rawText |
String | Raw SQL query payload to format. | "select id, name from users where id = 1" |
options.dialect |
String | Optional. Dialect: "standard", "mysql", "postgresql", "mssql", "oracle", "sqlite". |
"postgresql" |
options.keywordCase |
String | Optional. Keyword casing: "uppercase", "lowercase", "unchanged". |
"uppercase" |
options.indentSize |
Number | Optional. Spaces per indent level (2 or 4). |
2 |
API Request Payload Examples
cURL
curl -X POST https://blueutils.com/api/sql/sql-formatter \
-H "Content-Type: application/json" \
-d '{
"rawText": "select id, name from users left join roles on users.role_id = roles.id where status = '\''active'\'' order by id desc",
"options": { "dialect": "postgresql", "keywordCase": "uppercase", "indentSize": 2 }
}'Python
import requests
url = "https://blueutils.com/api/sql/sql-formatter"
payload = {
"rawText": "select id, name from users left join roles on users.role_id = roles.id where status = 'active' order by id desc",
"options": { "dialect": "postgresql", "keywordCase": "uppercase", "indentSize": 2 }
}
headers = {"Content-Type": "application/json"}
response = requests.post(url, json=payload, headers=headers)
print(response.json())Java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class Main {
public static void main(String[] args) throws Exception {
String jsonPayload = """
{
"rawText": "select id, name from users left join roles on users.role_id = roles.id where status = 'active' order by id desc",
"options": { "dialect": "postgresql", "keywordCase": "uppercase", "indentSize": 2 }
}
""";
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://blueutils.com/api/sql/sql-formatter"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(jsonPayload))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
}
}API Response Parameters
| Name | Type | Description | Example |
|---|---|---|---|
isValid |
Boolean | Indicates whether formatting succeeded. | true |
queryType |
String | Detected SQL statement type (SELECT, INSERT, UPDATE, etc.). |
"SELECT" |
dialect |
String | Name of the SQL dialect applied. | "PostgreSQL" |
lineCount |
Number | Total number of formatted lines. | 5 |
formattedSql |
String | Clean, indented, uppercase-keyword SQL string. | "SELECT id, name\nFROM users..." |
API Response Payload Examples
Success Response (HTTP 200 OK)
{
"isValid": true,
"queryType": "SELECT",
"dialect": "PostgreSQL",
"lineCount": 5,
"formattedSql": "SELECT id, name\nFROM users\nLEFT JOIN roles\n ON users.role_id = roles.id\nWHERE status = 'active'\nORDER BY id DESC"
}Validation Failure Response (HTTP 400 Bad Request)
{
"isValid": false,
"error": "Invalid input: SQL query payload cannot be empty."
}Rate Limit Exceeded Response (HTTP 429 Too Many Requests)
{
"error": "API rate limit exceeded. Please wait or contact support@blueutils.com."
}Why use an API to format SQL queries?
Integrating the SQL Formatter API into backend database migration pipelines, query loggers, or AI agent tool calling provides key benefits:
- Rapid Script Validation: Structures dynamic database queries before saving them to audit logs or executing migrations.
- Optimized Token Efficiency for AI Agents: LLMs frequently stumble over long, dense unformatted SQL queries. Formatting the query with the API simplifies LLM parsing and eliminates hallucinated join syntax.
- Deterministic Accuracy Without Hallucinations: Ensures 100% accurate clause alignment, keyword casing, and subquery indentation across all SQL dialects.
Native Usage
How to format SQL queries locally in terminal environments or scripts:
Windows (CMD / PowerShell)
# Format SQL keywords in PowerShell
(Get-Content -Path .\query.sql) -replace '\bselect\b', 'SELECT' -replace '\bfrom\b', 'FROM'Linux / Unix (Bash)
# Format SQL keywords using sed in Linux
sed -i -E 's/\bselect\b/SELECT/g; s/\bfrom\b/FROM/g; s/\bwhere\b/WHERE/g' query.sqlPython
Using Python sqlparse:
import sqlparse
raw_sql = "select id, name from users left join roles on users.role_id = roles.id where status = 'active'"
formatted = sqlparse.format(raw_sql, reindent=True, keyword_case='upper')
print(formatted)Java
Using Java String.replaceAll:
import java.nio.file.*;
public class SqlFormatExample {
public static void main(String[] args) throws Exception {
String sql = Files.readString(Paths.get("query.sql"));
String formatted = sql
.replaceAll("(?i)\\bselect\\b", "SELECT")
.replaceAll("(?i)\\bfrom\\b", "\nFROM")
.replaceAll("(?i)\\bwhere\\b", "\nWHERE");
System.out.println(formatted);
}
}