SQL
SQL Best Practises
Avoid N+1 Problem Antipattern
The N+1 query antipattern happens when a query is executed for every result of a previous query.
Avoid
Solve by fetching eagerly
Be careful when using ORMs.
Avoid duplicate Calculations with subqueries
To avoid the calculation, we introduce a subquery
:
Avoid Natural Joins
Natural Joins join on a column with the same name.
This can be a problem if both tables contain a column with the same name.
For example, a mod_time
time-stamp column would be used for joining, confusing the developer.
Prefer uncorrelated over correlated sub queries
Correlated sub queries are sub queries that rely on results from a record in the outer most query. This requires the sub query to be executed for every row of the outer most query. Unrelated sub queries are independent and thus only need to be executed once.