|
Getting the last n records |
|||||||||||||||||||||||||||||||||||||
|
Wouldn't it be nice if SQL had a BOTTOM keyword, that did the opposite of TOP?
To retrieve the first 100 records in a table, I can use the following query: SELECT TOP 100 MyField FROM MyTable But how can I get the last 100 records? Firstly, it is worth pointing out that this question has no meaning unless the result set is ordered on some field. If an ORDER BY clause is not specified, then SQL does not guarantee that records will be returned in any particular order. So asking for the last 100 records could theoretically return the same results as would be obtained by asking for the first 100 records. If an ORDER BY clause is specified, then using TOP will return the TOP n records after sorting has occurred. If I have the following table of names:
then the query SELECT TOP 3 GivenName FROM Names will return Bob To return the last 3 names, the records must be sorted in descending order: SELECT TOP 3 GivenName FROM Names will return Steven To return the last 3 names, but in ascending order, use a subquery: SELECT GivenName FROM Names This query may return more than 3 names if GivenName is not unique. If another "Ondrej" is added to the table, then the above query will return Ondrej To limit the output to exactly 3 records requires some decision about which Ondrej to include. For the sake of this example, I will add an identity column to the Names table:
The following query will make an arbitrary choice between the two Ondrejs, and will output exactly 3 records: SELECT GivenName FROM Names Adelle.
|
|||||||||||||||||||||||||||||||||||||