How to get the last row from a table in SQL Server?

Database tables are unsorted by nature. There is no last row in the table.

If there is a clustered index, The records are stored in the same order as the clustered index, but that does not mean that’s the order of the rows – Unless you specify an order by clause in your query, no database guarantees the order of the rows returned by said query.

From Wikipedia page on tables (emphasis mine):

In terms of the relational model of databases, a table can be considered a convenient representation of a relation, but the two are not strictly equivalent. For instance, an SQL table can potentially contain duplicate rows, whereas a true relation cannot contain duplicate tuples. Similarly, representation as a table implies a particular ordering to the rows and columns, whereas a relation is explicitly unordered. However, the database system does not guarantee any ordering of the rows unless an ORDER BY clause is specified in the SELECT statement that queries the table.

See also Aaron Betrand’s Bad habits to kick : relying on undocumented behavior, the paragraph titled “Ordering without an ORDER BY”:

… I want to make it quite clear: ordering is arbitrary unless you use an ORDER BY clause. You should never, ever, ever rely on the ordering you observe in a query without an ORDER BY — and you should only issue a query without an ORDER BY clause if you truly do not care what order the results come back. In such a case, you may as well imagine that the rows are going to come back in a different, random order each time, even though that is not truly the case (random has a meaning completely separate from arbitrary, but like I said, just imagine).

Leave a Comment