Evan Hicks
—The NOT IN operator in Postgres seems like a useful opposite to the IN operator, but it is actually recommended by Postgres to not use this operator in your queries. In fact, they recommend you don’t use any combination of NOT with IN operators because the NOT IN operator behaves strangely with NULL values., e.g. NOT (x IN (SELECT...))
.
SELECT * FROM foo WHERE col NOT IN (1, NULL);
This query will never return any rows, no matter what values are in the col
column. This happens because of the way NULL is evaluated with an IN condition. col IN (1, NULL)
returns either TRUE if col
is 1, or NULL. If you then apply a NOT to that, NOT(NULL) is still NULL. Since NULL is not TRUE, this query will never have any TRUE values and so no rows will be returned.
SELECT * FROM foo WHERE col NOT IN (SELECT other_col FROM bar);
This query will not return any rows if any value from bar.other_col
is NULL. Even if other_col
is never NULL, this query can also suffer from extreme performance issues once the dataset gets above a certain size. That means that the performance might be okay in small tests, but once your queries get above a certain size you will likely see performance degrade by orders of magnitude.
The NOT IN operator is fine to use for comparing against static lists.
SELECT * FROM foo WHERE col NOT IN (1, 2, 3);
As long as you are comparing to small lists of constant values, it might even be advisable to use.
If you’re looking to get a deeper understanding on this solution, or application monitoring in general, take a look at the following articles:
Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.
SEE EPISODESConsidered “not bad” by 4 million developers and more than 100,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.
Here’s a quick look at how Sentry handles your personal information (PII).
×We collect PII about people browsing our website, users of the Sentry service, prospective customers, and people who otherwise interact with us.
What if my PII is included in data sent to Sentry by a Sentry customer (e.g., someone using Sentry to monitor their app)? In this case you have to contact the Sentry customer (e.g., the maker of the app). We do not control the data that is sent to us through the Sentry service for the purposes of application monitoring.
Am I included?We may disclose your PII to the following type of recipients:
You may have the following rights related to your PII:
If you have any questions or concerns about your privacy at Sentry, please email us at compliance@sentry.io.
If you are a California resident, see our Supplemental notice.