I had a postgres database and some query like:

... WHERE x NOT IN (SELECT ...)

and it was slower than I thought it should be. After lots of desperate twiddling I changed it to:

... x NOT IN (SELECT DISTINCT ...)

The query ran almost twice as fast after... What in the world is going on here?

@dingus_spingus I'm curious what the explain plans of those two are.

My guess is that the rewrite's more expensive nested subquery pushed postgres into materializing the subquery.

Databases are weird and sometimes fickle.