Maybe your query result is too large, try checking the max_allowed_packet_size. For example in mysql: https://dev.mysql.com/doc/refman/5.5/en/packet-too-large.html
Maybe what you need to do is paging the results: http://www.petefreitag.com/item/451.cfm