How to use the TOP clause to return a subset of selected rows
In addition to eliminating duplicate rows, you can limit the number of rows that are retrieved by a SELECT statement. To do that, you use the TOP clause. Figure 3-9 shows you how.
You can use the TOP clause in one of two ways. First, you can use it to retrieve a specific number of rows from the beginning, or top, of the result set. To do that, you code the TOP keyword followed by an integer value that specifies the number of rows to be returned. This is illustrated in the first example in this figure. Here, only five rows are returned. Notice that this statement also includes an ORDER BY clause that sorts the rows by the InvoiceTotal column in descending sequence. That way, the invoices with the highest invoice totals will be returned.
You can also use the TOP clause to retrieve a specific percent of the rows in the result set. To do that, you include the PERCENT keyword as shown in the second example. In this case, the result set includes six rows, which is five percent of the total of 122 rows.
By default, the TOP clause causes the exact number or percent of rows you specify to be retrieved. However, if additional rows match the values in the last row, you can include those additional rows by including WITH TIES in the TOP clause. This is illustrated in the third example in this figure. Here, the SELECT statement says to retrieve the top five rows from a result set that includes the VendorID and InvoiceDate columns sorted by the InvoiceDate column. As you can see, however, the result set includes six rows instead of five. That's because WITH TIES is included in the TOP clause, and the columns in the sixth row have the same values as the columns in the fifth row.
A SELECT statement with a TOP clause
SELECT TOP 5 VendorID, InvoiceTotalFROM InvoicesORDER BY InvoiceTotal DESC
A SELECT statement with a TOP clause and the PERCENT keyword
SELECT TOP 5 PERCENT VendorID, InvoiceTotalFROM InvoicesORDER BY InvoiceTotal DESC
A SELECT statement with a TOP clause and the WITH TIES keyword
SELECT TOP 5 WITH TIES VendorID, InvoiceDateFROM InvoicesORDER BY InvoiceDate DESC
Description
Figure 3-9 How to use the TOP clause to return a subset of selected rows