Goal: correct, readable SQL that the planner can execute efficiently.
Use for:
- writing queries, joins, and aggregations
- reviewing query correctness and parameter safety
- replacing row-by-row logic with set-based queries
Workflow:
- Express intent as a set operation, not a loop.
- Parameterize all values; never concatenate input.
- Select only the columns you need.
- Join on indexed keys; understand the join type you want.
- Filter early; push predicates into subqueries/CTEs sensibly.
- Verify correctness on edge cases and read the query plan.
Patterns:
- explicit JOIN ... ON over comma joins
- CTEs for readability of multi-step queries
- window functions for ranking and running totals
- GROUP BY with the right aggregates and HAVING
Rules:
- always parameterize; SQL injection is unacceptable
- avoid SELECT *; name your columns
- know whether NULLs change your results
- check the plan before optimizing by guess