One of the major approaches to database performance optimization is to try to minimize the number of round trips between client and server. A related one is to minimize the work done processing database queries. One way to combine these is to perform complex queries inside the database, coding them in pl/pgsql or one of the other " embeddable" languages.