Reputation: 471
As a starting point I have the following query. I know that it works and produces the result I'm looking for but could it be done in a faster/more efficient way since it will potentially be processing large amounts of data to find what I want to return.
(ID in the example below is an auto-increment PK field)
select x, y, z
from table
where id = (select max(id) from table where z = someValue)
Upvotes: 0
Views: 306
Reputation: 1269873
I would suggest:
select top (1) x, y, x
from table
where z = somevalue
order by id desc;
For performance, you want an index on (z, id)
.
Upvotes: 3
Reputation: 5707
I like using a CTE for this, as you can do an INNER JOIN
with the source table and the CTE.
;WITH LookupCTE AS
(
select id = MAX(id)
FROM table
WHERE z = someValue
)
SELECT x, y, x
from table t1
INNER join LookupCTE t2 ON t1.id = t2.id
Upvotes: 2