SQL equivalent to Last()

We all love Linq in all its glory, but from time to time you have to write raw SQL queries (c: and it is fun to, don’t get me wrong, but it doest have the same range of ready to use functions as Linq.

This time i needed to find the last element from a table with at least trazillion rows, this is how i did it.

SELECT * FROM  tableName
WHERE   id = (SELECT MAX(id) FROM tableName)

You can posibly wrap it in to a CREATE FUNCTION, but this worked for me as it is,.. (c:

if you table doesn’t have an id with which hold the usable number you can do somthing like this

SELECT MAX(rownr) FROM (
SELECT ROW_NUMBER() OVER(ORDER BY customerText DESC) AS rownr
  FROM bbc) AS Q

the customerText is a name for any kind of column in your table ..

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: