Be the first to rate this article.
Processing...
# SQL Query Writing taste of a data-minded engineer who wants queries others can read and trust - Write SQL keywords in uppercase and identifiers in snake_case lowercase, one clause per line. Confidence: 0.80 - Put each selected column on its own line with a leading or trailing comma style used consistently across the repo, enforced by sqlfluff. Confidence: 0.75 - Never use SELECT * in application queries or views; list the columns you need. Confidence: 0.90 - Use explicit JOIN ... ON syntax; never comma joins with conditions in WHERE. Confidence: 0.95 - Give every table a short, meaningful alias and qualify every column once more than one table is involved. Confidence: 0.85 - Break long queries into named CTEs that read top to bottom like steps, instead of nesting subqueries three levels deep. Confidence: 0.85 - Check the grain of a query before joining: know what one row means and confirm joins do not fan out rows. Confidence: 0.90 - Prefer EXISTS over IN with a subquery for existence checks, and NOT EXISTS over NOT IN to avoid the NULL trap. Confidence: 0.85 - Treat NULL deliberately: use IS NULL, COALESCE with a documented default and IS DISTINCT FROM for null-safe comparisons. Confidence: 0.90 - Use window functions (ROW_NUMBER, LAG, SUM OVER) for rankings, deduplication and running totals instead of self-joins. Confidence: 0.85 - Filter on half-open date ranges (created_at >= start AND created_at < end) rather than BETWEEN on timestamps. Confidence: 0.90 - Keep predicates sargable: do not wrap indexed columns in functions or casts inside WHERE. Confidence: 0.85 - Always pass values as bound parameters; never build SQL by concatenating user input. Confidence: 1.00 - Use COUNT(*) for row counts and COUNT(column) only when you mean non-null values. Confidence: 0.80 - Put conditions for outer-joined tables in the ON clause, not the WHERE clause, so a LEFT JOIN stays a LEFT JOIN. Confidence: 0.90 - Use CASE expressions with an explicit ELSE so unexpected values are visible instead of silently NULL. Confidence: 0.75 - Add ORDER BY whenever order matters, including with LIMIT; never rely on the natural row order. Confidence: 0.95 - Paginate large result sets with keyset pagination (WHERE id > last_id) instead of big OFFSET values. Confidence: 0.80 - Run EXPLAIN ANALYZE on any query that touches a large table before shipping it, and keep the plan in the pull request. Confidence: 0.80 - Prefer UNION ALL over UNION unless you actually need duplicate removal. Confidence: 0.85 - Write data-changing statements inside a transaction and check the affected row count before committing. Confidence: 0.90 - Comment the business rule behind non-obvious filters, not what the SQL syntax does. Confidence: 0.75 - Keep reusable queries in version-controlled .sql files or views with tests on small fixture data. Confidence: 0.70
Comments & Questions (0)
No comments yet
Be the first to comment!