I have a table defined as:
create table Foo (
X integer,
Y timestamp,
Z varchar(255),
primary key (X, Y)
);
For a given X I want to find the most recent row. I’ve come up with the following so far, but would like to know if anyone knows something that will perform better or is just “interesting” such as using a left join on itself (which I haven’t been able to get to work).
select * from Foo where X=1234 order by Y desc limit 0,1;
select * from Foo where X=1234 and Y in (select max(Y) from Foo where X=1234);
Thanks!
In your second example you’re using a correlated subquery. You could use a non-correlated subquery (derived table) instead. This will be faster if you happen to list all the foos, because a correlated subquery would have to be called once for each row of the outer query.
This is an example using a derived table:
Test case:
Result:
However, if you will always be restricting your result to just one
X, your solutions are probably fine. Check out @Mark Byers’ answer for further tips on this.