=?UTF-8?Q?Ondrej_Ivani=C4=8D?= <ondrej.ivanic@gmail.com> writes:
> work_mem is set to 4 000 000 kb and I do not understand why few
> queries (3 and 5) used disk and the rest fit were able to data into
> memory.
The on-disk representation of sort data is quite a bit more compact than
the in-memory representation. So where it says that 3.5GB of disk were
needed, it's not a surprise that the memory requirement would have
exceeded 4GB to do the sort in-memory.
If you want to know what the conversion factor is for your particular
dataset, try doing the query with small and large work_mem so you can
see what is reported as the amount of space needed each way.
regards, tom lane