RunToolz iconRunToolz
Welcome to RunToolz!
SQLDatabaseCode Quality

Readable SQL Isn't Optional

How to format SQL queries so your future self (and teammates) won't hate you.

RunToolz TeamJanuary 28, 20263 min read

You inherit a query. It's one line. 400 characters. Multiple joins, subqueries, and CASE statements all mashed together.

Good luck understanding it.

SQL formatting isn't about aesthetics. It's about whether queries are maintainable.

The Problem With Dense SQL

SELECT u.id,u.name,o.total,p.name FROM users u JOIN orders o ON u.id=o.user_id JOIN products p ON o.product_id=p.id WHERE o.created_at>'2024-01-01' AND u.status='active' ORDER BY o.total DESC;

Where's the join condition? What's being filtered? Which table does each column come from?

Now imagine debugging this at 2 AM.

Ready to try it yourself?Format SQL

The Same Query, Readable

SELECT
    u.id,
    u.name,
    o.total,
    p.name
FROM users u
JOIN orders o ON u.id = o.user_id
JOIN products p ON o.product_id = p.id
WHERE o.created_at > '2024-01-01'
    AND u.status = 'active'
ORDER BY o.total DESC;

Every clause has its own line. Conditions align. The structure is visible.

Formatting Rules That Work

One clause per line. SELECT, FROM, WHERE, ORDER BY each get their own line.

Columns on separate lines. Long SELECT lists become scannable.

Indent continued conditions. Multiple WHERE conditions align.

Uppercase keywords. SELECT, FROM, WHERE stand out from table names and columns.

Consistent casing. Pick a style. Stick with it.

Subquery Formatting

Subqueries get messy fast. Indent them clearly:

SELECT *
FROM orders
WHERE user_id IN (
    SELECT id
    FROM users
    WHERE status = 'premium'
)

Or use CTEs when subqueries get complex:

WITH premium_users AS (
    SELECT id
    FROM users
    WHERE status = 'premium'
)
SELECT *
FROM orders
WHERE user_id IN (SELECT id FROM premium_users)

CTEs are often clearer than nested subqueries.

JOIN Formatting

Always specify join types. JOIN alone is INNER JOIN, but explicit is better.

SELECT *
FROM orders o
INNER JOIN users u ON o.user_id = u.id
LEFT JOIN shipping s ON o.id = s.order_id

Put the join condition on the same line for simple joins. Break to the next line for complex conditions.

What About Performance?

Formatting doesn't affect execution. The database optimizer doesn't care about whitespace.

But formatted SQL is easier to optimize. You can see the structure, identify unnecessary joins, spot missing indexes.

Unreadable SQL hides performance problems.

Team Standards

Pick a style. Document it. Enforce with automated formatters.

Different styles exist. Some teams put commas at the start of lines. Some uppercase everything. Some don't.

Consistency matters more than which style you choose.


Every query gets read more than it gets written. Format for readability. Your teammates—and your future self—will thank you.