April 4, 2026 2 min readUpdated Apr 9, 2026
SQL Query Formatting Best Practices
sqldatabasebest-practicespostgresqlreadability

Why SQL Formatting Matters
SQL is often written once and read many times — by teammates, future-you, or automated audit tools. Good formatting makes structure visible at a glance.
Core Conventions
1. Uppercase SQL Keywords
-- Bad
select id, name from users where active = true;
-- Good
SELECT id, name
FROM users
WHERE active = TRUE;
2. One Clause Per Line
SELECT
u.id,
u.email,
COUNT(o.id) AS order_count
FROM users u
JOIN orders o ON o.user_id = u.id
WHERE u.active = TRUE
GROUP BY u.id, u.email
HAVING COUNT(o.id) > 3
ORDER BY order_count DESC
LIMIT 50;
3. Use Table Aliases Consistently
SELECT
u.id,
u.name,
p.title AS post_title
FROM users u
JOIN posts p ON p.author_id = u.id;
Avoid single-letter aliases for more than 2 tables — use usr, ord, prd instead.
4. Write JOINs Explicitly
-- Avoid
FROM users u, orders o WHERE u.id = o.user_id
-- Prefer
FROM users u
INNER JOIN orders o ON o.user_id = u.id
5. CTEs Over Nested Subqueries
-- Hard to read
SELECT * FROM (SELECT user_id, COUNT(*) AS cnt FROM orders GROUP BY user_id) t WHERE t.cnt > 5;
-- Easy to read
WITH order_counts AS (
SELECT user_id, COUNT(*) AS cnt
FROM orders
GROUP BY user_id
)
SELECT *
FROM order_counts
WHERE cnt > 5;
6. Format Long WHERE Conditions
WHERE
status = 'active'
AND created_at >= '2025-01-01'
AND (
role = 'admin'
OR permissions @> ARRAY['write']
);
Format Your SQL Instantly
Use the free SQL Formatter on konvertio.app to instantly reformat any SQL query with proper indentation, keyword casing, and clause alignment — paste in, copy out, done.