format.CoShareX
HomeBlogFormattersHow to Format SQL Queries
Formatters

How to Format SQL Queries

Published 2026-08-10
4 min read
By CoShareX

SQL queries can quickly become hard to read when writing complex joins, subqueries, or analytics aggregations. Poorly formatted SQL is difficult for developers to review, debug, and optimize.

In this guide, we'll explain how to format and structure your SQL statements for maximum clarity.

Standard SQL Spacing

Consider this unformatted query:

sql
1
select u.name,o.total from users u join orders o on u.id=o.user_id where o.status='paid' order by o.total desc;

Compare it to the formatted version:

sql
1
2
3
4
5
6
7
SELECT
  u.name,
  o.total
FROM users u
JOIN orders o ON u.id = o.user_id
WHERE o.status = 'paid'
ORDER BY o.total DESC;

The formatted version makes the selected fields, tables, joins, filters, and sorting criteria immediately clear.

Capitalization Rules

Standard SQL formatting practices recommend capitalizing keyword clauses (like SELECT, FROM, JOIN, WHERE, GROUP BY, ORDER BY) to distinguish them from field names, tables, and variables.

Featured Tool

SQL Formatter

Format, beautify and indent database SQL queries.

Nested Spacing and Subqueries

For nested queries or subqueries, indent the subquery code blocks (usually using 2 or 4 spaces) to make it clear which query block executes first.

sql
1
2
3
4
5
6
7
SELECT name
FROM users
WHERE id IN (
  SELECT user_id
  FROM orders
  WHERE status = 'active'
);

This hierarchy makes it easy to track query execution logic and optimize database queries.