> How is it possible that one connection (query) uses all the ram? And how > can I avoid it?
Uh ... don't do the above. work_mem is the allowed memory consumption per query step, ie per hash or sort operation. A complex query can easily use multiples of work_mem.