1. A computer readable medium containing program instructions for executing a query to access data stored in a database, wherein the query includes a plurality of DISTINCT keys, the program instructions for: (a) determining if more than one sort is needed to execute the query; (b) performing a first DISTINCT operation on a first DISTINCT key of the plurality of DISTINCT keys, comprising (b1) optimizing the query; and (b2) analyzing the query comprising (b2i) identifying the plurality of DISTINCT keys; and (b2ii) writing the plurality of DISTINCY keys to a control block, wherein the control block is used to execute the query; (c) storing data from the first DISTINCT operation in a master workfile only if more than one sort is needed to execute the query; and (d) utilizing the master workfile to perform subsequent DISTINCT operations on one or more other of the plurality of DISTINCT keys, wherein the one or more subsequent DISTINCT operations are performed after completion of the first DISTINCT operation, each operation being controlled by the sort process.