DEV Community

GoToolsOnline
GoToolsOnline

Posted on

Reading a one-line SQL query from an ORM log

ORMs and BI tools love logging SQL as one enormous line. The bug is usually in there somewhere, but you can't see it until the query has some shape. A few things to look for once it's formatted:

1. AND/OR precedence. AND binds tighter than OR:

SELECT *
FROM orders
WHERE status = 'paid'
  AND country = 'IN'
   OR country = 'LK'
Enter fullscreen mode Exit fullscreen mode

This returns every Sri Lankan order, paid or not. You almost certainly meant AND (country = 'IN' OR country = 'LK'). On one line it's invisible; on separate lines it jumps out.

2. A filter on a LEFT JOINed table in WHERE. LEFT JOIN payments p ... WHERE p.status = 'ok' silently turns your left join into an inner join, because rows with no payment have p.status = NULL. Move the condition into the ON clause if you want to keep those rows.

3. A missing join condition. If you see FROM a, b or a JOIN with no ON, you have a cross join. Row counts that are suspiciously "rows in A times rows in B" are the giveaway.

4. NOT IN with a subquery that can return NULL. WHERE id NOT IN (SELECT user_id FROM bans) returns nothing at all if any user_id is NULL. NOT EXISTS doesn't have this problem.

5. Dialect quirks. Backticks (MySQL), double quotes (PostgreSQL, standard) and square brackets (SQL Server) all quote names. A formatter set to the wrong dialect may choke on them, which is a hint about where the query came from.

Formatting fixes none of these by itself, but putting each clause on its own line with conditions indented underneath makes them easy to spot, and gives you clean line-by-line diffs in code review.

Disclosure: I run GoToolsOnline. Its free SQL formatter runs in the browser, supports 11 dialects (MySQL, PostgreSQL, SQL Server, Oracle, SQLite, BigQuery, Snowflake and more), lets you pick keyword case and indent, and can minify too: https://gotoolsonline.com/tools/sql-formatter

Top comments (0)