Back to Blog
Database
January 15, 20255 min read

SQL Formatting: Making Queries Readable

Code is read far more often than it is written. SQL, with its declarative nature, often ends up as a "wall of text" that hides logic and bugs. Let's look at how to format SQL for humans.

The Cost of Messy SQL

A complex 200-line query with no indentation is a liability. It makes code reviews slower, onboarding more difficult, and significantly increases the chances of logic errors in JOIN conditions or WHERE clauses.

1. Standardize Your Casing

While SQL is case-insensitive, the industry standard is to use UPPERCASE for reserved keywords and snake_case for table and column names.

-- Bad
select name, email from users where id = 10;

-- Good
SELECT name, email 
FROM users 
WHERE id = 10;

2. Use Common Table Expressions (CTEs)

Subqueries are hard to read because they force the reader to work from the "inside out." CTEs allow you to write queries that read linearly from top to bottom.

WITH user_orders AS (
    SELECT user_id, COUNT(*) as order_count
    FROM orders
    GROUP BY user_id
)
SELECT u.name, o.order_count
FROM users u
JOIN user_orders o ON u.id = o.user_id
WHERE o.order_count > 5;

3. The "River" Indentation

Many senior DBAs use the "river" style, where keywords are right-aligned so that the "action" of the query forms a straight vertical line down the page.

SELECT u.name,
       u.email,
       p.profile_pic
  FROM users u
  LEFT JOIN profiles p ON u.id = p.user_id
 WHERE u.active = true
   AND u.created_at > '2025-01-01';

4. Use Meaningful Aliases

Avoid single-letter aliases like a, b, and c. Use u for users, o for orders, or better yet, the full name if the query is complex.

Conclusion

Consistent SQL formatting isn't just about aesthetics; it's about maintainability. Treat your SQL with the same respect as your application code.

Clean up your queries instantly with our SQL Formatter.