Rules Hub
Coding Rules Library
← Back to all rules
Rule priority, scope & exceptions
Use this to align rules with the senior-level structure (P0/P1/P2, scope, exceptions/tradeoffs).
backend ruleP2universalStack: SQL
sqlperformancequery-optimizationjoins
Prefer JOIN with GROUP BY over correlated subqueries for aggregation
Rewrite count/aggregate correlated subqueries as a JOIN with GROUP BY where it yields the same result, for clearer and often faster queries.
PR: vinify-backend · org-mining-hist-2026-06Created: Jun 19, 2026
Bad example
Old codesql
| 1 | SELECT s.id, (SELECT COUNT(*) FROM bottles b WHERE b.supplier_id = s.id) AS cnt FROM suppliers s |
Explanation (EN)
Objašnjenje (HR)
Good example
New codesql
| 1 | SELECT s.id, COUNT(b.id) AS cnt |
| 2 | FROM suppliers s |
| 3 | LEFT JOIN bottles b ON b.supplier_id = s.id |
| 4 | GROUP BY s.id |
Explanation (EN)
Objašnjenje (HR)