2 Bad SQL Usage
This chapter covers
- Avoiding SQL pitfalls
- Exercising due care with your query results
- Improving performance of complex queries
- Checking your queries for correctness
Let’s begin our journey into the land of PostgreSQL mistakes with what most relational database users are familiar with: Structured Query Language (SQL). In this chapter, we examine some bad SQL habits that can lead to bad query performance or, even worse, getting wrong query results. Postgres is very particular about the way it wants queries to be written and in most cases follows a strict interpretation of the SQL Standard. This means you need to be careful about the way you construct those queries and always check that you are actually getting exactly the results you want.
2.1 Using NOT IN to exclude
It’s often that we need to specify a condition with a negative expression. That doesn’t mean that we are trying to be unpleasant, just that instead of specifying what we want, we specify the inverse of that condition or what we don’t want in our results, in order to define the query.
Negative predicates are expressed with the NOT
keyword and they can be used to invert any SQL expression, including those based around IN
.