Docs
Docs/SQL Best Practices/Writing Clean SQL

Writing Clean SQL

Formatting and style best practices

Clean, readable SQL is easier to debug, maintain, and review.

Formatting Guidelines

-- GOOD: Readable and well-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 u.id = o.user_id
WHERE u.status = 'active'
  AND u.created_at >= '2024-01-01'
GROUP BY u.id, u.name, u.email
HAVING COUNT(o.id) > 0
ORDER BY total_spent DESC
LIMIT 100;

-- BAD: Hard to read
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 u.id=o.user_id WHERE u.status='active' AND u.created_at>='2024-01-01' GROUP BY u.id,u.name,u.email HAVING COUNT(o.id)>0 ORDER BY total_spent DESC LIMIT 100;

Style Rules

1

Use UPPERCASE for SQL keywords (SELECT, FROM, WHERE)

2

Put each major clause on its own line

3

Use meaningful table aliases (u for users, not t1)

4

Align similar elements vertically when possible

5

Add comments for complex logic

Need help?

Join our Discord community for support and discussions.

Join Discord