tags:

views:

65

answers:

5

Say I want to do this with SQL (Sybase): Find all fields of the record with the latest timestamp.

One way to write that is like this:

select * from data where timestamp = (select max(timestamp) from data)

This is a bit silly because it causes two queries - first to find the max timestamp, and then to find all the data for that timestamp (assume it's unique, and yes - i do have an index on timestamp). More so it just seems unnecessary because max() has already found the row that I am interested in so looking for it again is wasteful.

Is there a way to directly access fields of the row that max() returns?

Edit: All answers I see are basically clever hacks - I was looking for a syntactic way of doing something like max(field1).field2 to access field2 of the row with max field1

+4  A: 
SELECT TOP 1 * from data ORDER BY timestamp DESC
alygin
*upvote* - this was the first and correct answer, but not for sybase
Note that if you have multiple rows with the same timestamp, you'll only get one, and it's undefined which one you'll get. It depends on your app whether that's possible or not.
Dewayne Christensen
TOP certainly is available in Sybase (ASE) from at least version 12.5 and possibly from 12.
AdamH
A: 

Can you try this

SELECT TOP 1 *
FROm    data
ORDER BY timestamp DESC
astander
A: 

You're making assumptions about how Sybase optimizes queries. For all you know, it may do precisely what you want it to do - it may notice both queries are from "data" and that the condition is "where =", and may optimize as you suggest.

I know in the case of SQL Server, it's possible to configure indexes to include fields from the indexed row. Doing a select through such an index leaves those fields available.

John Saunders
A: 

This is SQL server, but you'll get the idea.

SELECT TOP(1) * FROM data
ORDER BY timestamp DESC;
Damir Sudarevic
A: 

No, using an aggregate means that you are automatically grouping, so there isn't a single row to get data from even if the group happens to contain a single row.

You can order by the field and get the first row:

set rowcount 1
select * from data order by timestamp desc

(Note that you shouldn't use select *, but rather specify the fields that you want from the query. That makes the query less sensetive to changes in the database layout.)

Guffa