5. The apparatus of claim 1 wherein the query optimizer further determines the query contains an Order By clause and that an index exists for a leftmost column but not all the columns of the Order By clause; and wherein the access plan eliminates records prior to a sort by fetching n rows from the index over the leftmost column and remaining rows until a unique value of the index is encountered.
1. An apparatus comprising: at least one processor; a memory coupled to the at least one processor containing a database of records; a query residing in the memory that includes a Select statement with a Fetch First n Rows Only clause, where n is an integer variable; a query optimizer residing in the memory and executed by the at least one processor, wherein the query optimizer: determines that the query can be optimized and generates for the query an optimized access plan that eliminates records defined by a Where clause prior to ordering the records and then returns a first n rows; determines that the query contains a Group By clause and that an index exists for a leftmost column but not all the columns of the Group By clause; and generates an access plan that eliminates records prior to grouping by fetching n rows from the index over the leftmost column and remaining rows until a unique value of the index is encountered.