Back to Blog
Developer Tools

Format SQL for Readability โ€” SQL Formatting Best Practices

2026-06-03 5 min read

Unformatted SQL is hard to read, review, and maintain. Here are SQL formatting conventions that make queries readable across teams.

Unformatted SQL is as hard to read as minified JavaScript. A SELECT with eight JOINs and a WHERE clause with twelve conditions becomes unmanageable as a single line. Proper SQL formatting is the difference between code you can maintain and code you have to rewrite.

Core SQL formatting rules

There isn't a single universal standard, but these conventions are widely adopted:

  • SQL keywords in UPPERCASE: SELECT, FROM, WHERE, JOIN
  • Each major clause on its own line
  • Column list indented under SELECT
  • JOIN conditions on their own line after ON
  • WHERE conditions aligned under AND/OR

Before and after

Unformatted:

select u.id, u.name, u.email, count(o.id) as order_count, sum(o.total) as total_spent from users u left join orders o on o.user_id = u.id where u.created_at > '2026-01-01' and u.active = true group by u.id, u.name, u.email having count(o.id) > 5 order by total_spent desc limit 10

Formatted:

SELECT
  u.id,
  u.name,
  u.email,
  COUNT(o.id) AS order_count,
  SUM(o.total) AS total_spent
FROM users u
LEFT JOIN orders o
  ON o.user_id = u.id
WHERE
  u.created_at > '2026-01-01'
  AND u.active = TRUE
GROUP BY
  u.id,
  u.name,
  u.email
HAVING COUNT(o.id) > 5
ORDER BY total_spent DESC
LIMIT 10

Subqueries and CTEs

Common Table Expressions (CTEs) make complex queries dramatically more readable by giving names to intermediate results:

WITH active_users AS (
  SELECT id, name, email
  FROM users
  WHERE active = TRUE
    AND created_at > '2026-01-01'
),
user_orders AS (
  SELECT user_id, COUNT(*) AS order_count
  FROM orders
  GROUP BY user_id
)
SELECT
  u.name,
  u.email,
  COALESCE(o.order_count, 0) AS orders
FROM active_users u
LEFT JOIN user_orders o
  ON o.user_id = u.id

Format your SQL instantly with our SQL Formatter.

sql format readability best-practices query

More Articles